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
3e0c879734dc38a04061f74e0e80e3a7e0a04308
1,719
java
Java
src/main/java/com/ac/mylib/java/guava/GuavaTester.java
shahainloong/mylib
403aee7f16dbba375b100d532d3ecb1d1cf928b7
[ "Apache-2.0" ]
1
2020-05-12T15:14:07.000Z
2020-05-12T15:14:07.000Z
src/main/java/com/ac/mylib/java/guava/GuavaTester.java
shahainloong/mylib
403aee7f16dbba375b100d532d3ecb1d1cf928b7
[ "Apache-2.0" ]
1
2021-04-26T08:24:54.000Z
2021-04-26T08:24:54.000Z
src/main/java/com/ac/mylib/java/guava/GuavaTester.java
shahainloong/mylib
403aee7f16dbba375b100d532d3ecb1d1cf928b7
[ "Apache-2.0" ]
null
null
null
36.574468
79
0.643397
5,324
package com.ac.mylib.java.guava; import com.google.common.base.*; import java.util.ArrayList; public class GuavaTester { public static void main(String args[]) { final long startTime = System.nanoTime(); GuavaTester guavaTester = new GuavaTester(); Integer value1 = null; Integer value2 = new Integer(10); //Optional.fromNullable - allows passed parameter to be null. Optional<Integer> a = Optional.fromNullable(value1); //Optional.of - throws NullPointerException if passed parameter is null Optional<Integer> b = Optional.of(value2); System.out.println(guavaTester.sum(a, b)); ArrayList<String> list = new ArrayList<>(); Runnable runnable = () -> System.out.println("hello"); String s = Functions.toStringFunction().apply("hello".length()); System.out.println(s); Function<String, Integer> function = (String it) -> it.length(); System.out.println(function.apply("hello")); final long endTime = System.nanoTime(); System.out.println("The total time is: " + (endTime - startTime)); } public Integer sum(Optional<Integer> a, Optional<Integer> b) { //Optional.isPresent - checks the value is present or not System.out.println("First parameter is present: " + a.isPresent()); System.out.println("Second parameter is present: " + b.isPresent()); //Optional.or - returns the value if present otherwise returns //the default value passed. Integer value1 = a.or(new Integer(0)); //Optional.get - gets the value, value should be present Integer value2 = b.get(); return value1 + value2; } }
3e0c887bdbea9ce1035f50842718917a5eb7a0d6
445
java
Java
src/main/java/com/bsi/ms/model/TestKey.java
cuiouyang/-
2afeef7605c1ac251591f12f5055fa002721e830
[ "MIT" ]
3
2020-06-07T03:44:16.000Z
2021-12-15T00:59:53.000Z
src/main/java/com/bsi/ms/model/TestKey.java
cuiouyang/-
2afeef7605c1ac251591f12f5055fa002721e830
[ "MIT" ]
4
2021-01-20T21:37:02.000Z
2021-12-10T00:47:17.000Z
src/main/java/com/bsi/ms/model/TestKey.java
cuiouyang/-
2afeef7605c1ac251591f12f5055fa002721e830
[ "MIT" ]
null
null
null
19.347826
60
0.624719
5,325
package com.bsi.ms.model; public class TestKey { private Integer problemId; private String userId; public Integer getProblemId() { return problemId; } public void setProblemId(Integer problemId) { this.problemId = problemId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } }
3e0c8930f571249552f825f84c2cb9cd53fc4314
226
java
Java
ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/cdn/website/OvhDomain.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
12
2017-04-04T07:20:48.000Z
2021-04-20T07:54:21.000Z
ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/cdn/website/OvhDomain.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
7
2017-04-05T04:54:16.000Z
2019-09-24T11:17:05.000Z
ovh-java-sdk-cdnwebsite/src/main/java/net/minidev/ovh/api/cdn/website/OvhDomain.java
marstona/ovh-java-sdk
b574fbbac59832fda7a4fedaf3cb1f074135f714
[ "BSD-3-Clause" ]
3
2019-10-10T13:51:22.000Z
2020-11-13T14:30:45.000Z
13.294118
40
0.650442
5,326
package net.minidev.ovh.api.cdn.website; /** * Domain on CDN */ public class OvhDomain { /** * canBeNull && readOnly */ public String domain; /** * canBeNull && readOnly */ public OvhDomainStatusEnum status; }
3e0c8933547f0f6c6d928731fb4665b292b52b95
4,038
java
Java
src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java
pieterjanpintens/wiremock
e80dc14c2a3bd19661c2ec01a6d0269893f6c234
[ "Apache-2.0" ]
4,473
2015-01-01T01:00:16.000Z
2021-09-20T09:02:58.000Z
src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java
pieterjanpintens/wiremock
e80dc14c2a3bd19661c2ec01a6d0269893f6c234
[ "Apache-2.0" ]
1,259
2015-01-01T21:07:01.000Z
2021-09-16T22:22:13.000Z
src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyUtils.java
pieterjanpintens/wiremock
e80dc14c2a3bd19661c2ec01a6d0269893f6c234
[ "Apache-2.0" ]
1,217
2015-01-06T01:42:33.000Z
2021-09-20T12:27:01.000Z
35.421053
114
0.698366
5,327
/* * Copyright (C) 2011 Thomas Akehurst * * 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.github.tomakehurst.wiremock.jetty9; import static com.github.tomakehurst.wiremock.common.Exceptions.throwUnchecked; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.Socket; import java.net.URI; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import org.eclipse.jetty.http.HttpURI; import org.eclipse.jetty.io.ssl.SslConnection; import org.eclipse.jetty.server.HttpChannel; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Response; public class JettyUtils { private static final Map<Class<?>, Method> URI_METHOD_BY_CLASS_CACHE = new HashMap<>(); private static final boolean IS_JETTY; static { // do the check only once per classloader / execution IS_JETTY = isClassExist("org.eclipse.jetty.server.Request"); } private JettyUtils() { // Hide public constructor } public static boolean isJetty() { return IS_JETTY; } private static boolean isClassExist(String type) { try { ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); ClassLoader loader = contextCL == null ? JettyUtils.class.getClassLoader() : contextCL; Class.forName(type, false, loader); return true; } catch (Exception e) { return false; } } public static Response unwrapResponse(HttpServletResponse httpServletResponse) { if (httpServletResponse instanceof HttpServletResponseWrapper) { ServletResponse unwrapped = ((HttpServletResponseWrapper) httpServletResponse).getResponse(); return (Response) unwrapped; } return (Response) httpServletResponse; } public static Socket getTlsSocket(Response response) { HttpChannel httpChannel = response.getHttpOutput().getHttpChannel(); SslConnection.DecryptedEndPoint sslEndpoint = (SslConnection.DecryptedEndPoint) httpChannel.getEndPoint(); Object endpoint = sslEndpoint.getSslConnection().getEndPoint(); try { return (Socket) endpoint.getClass().getMethod("getSocket").invoke(endpoint); } catch (Exception e) { return throwUnchecked(e, Socket.class); } } public static boolean uriIsAbsolute(Request request) { HttpURI uri = getHttpUri(request); return uri.getScheme() != null; } private static HttpURI getHttpUri(Request request) { try { return (HttpURI) getURIMethodFromClass(request.getClass()).invoke(request); } catch (Exception e) { throw new IllegalArgumentException(request + " does not have a getUri or getHttpURI method"); } } private static Method getURIMethodFromClass(Class<?> requestClass) throws NoSuchMethodException { if(URI_METHOD_BY_CLASS_CACHE.containsKey(requestClass)){ return URI_METHOD_BY_CLASS_CACHE.get(requestClass); } Method method; try { method = requestClass.getDeclaredMethod("getUri"); } catch (NoSuchMethodException ignored) { method = requestClass.getDeclaredMethod("getHttpURI"); } URI_METHOD_BY_CLASS_CACHE.put(requestClass, method); return method; } }
3e0c8946fef45c43e9c3d506562cc31a19bc5ff4
1,856
java
Java
src/main/java/pulse/bep/util/LZ4Compression.java
dapperstout/pulse-java
eca51efc17eb4f9f1439b05bc1f9f3f4f7cb6951
[ "MIT" ]
10
2015-02-06T04:50:41.000Z
2021-02-05T01:29:14.000Z
src/main/java/pulse/bep/util/LZ4Compression.java
dapperstout/pulse-java
eca51efc17eb4f9f1439b05bc1f9f3f4f7cb6951
[ "MIT" ]
null
null
null
src/main/java/pulse/bep/util/LZ4Compression.java
dapperstout/pulse-java
eca51efc17eb4f9f1439b05bc1f9f3f4f7cb6951
[ "MIT" ]
5
2015-04-27T23:39:28.000Z
2016-12-26T15:38:51.000Z
35.692308
97
0.696121
5,328
package pulse.bep.util; import net.jpountz.lz4.LZ4Compressor; import net.jpountz.lz4.LZ4Exception; import net.jpountz.lz4.LZ4Factory; import net.jpountz.lz4.LZ4FastDecompressor; import static java.lang.System.arraycopy; import static java.util.Arrays.copyOf; import static pulse.bep.util.Bytes.*; public class LZ4Compression { private static final int MAX_BUFFER_LENGTH = 8 * 1024 * 1024; private static LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); private static LZ4Compressor compressor = lz4Factory.fastCompressor(); private static LZ4FastDecompressor decompressor = lz4Factory.fastDecompressor(); public static byte[] compress(byte[] data) { int maxCompressedLength = compressor.maxCompressedLength(data.length); byte[] compressed = new byte[4 + maxCompressedLength]; arraycopy(bytes(data.length), 0, compressed, 0, 4); int compressedLength = compressor.compress(data, 0, data.length, compressed, 4); return copyOf(compressed, 4 + compressedLength); } public static byte[] decompress(byte[] data) { long decompressedLength = unsigned(concatenateBytes(data[0], data[1], data[2], data[3])); if (decompressedLength > MAX_BUFFER_LENGTH) { throw new DecompressedDataTooLarge(); } try { return decompressor.decompress(data, 4, (int)decompressedLength); } catch(LZ4Exception exception) { throw new InvalidLZ4Data(exception); } } public static class InvalidLZ4Data extends RuntimeException { public InvalidLZ4Data(Throwable cause) { super(cause); } } public static class DecompressedDataTooLarge extends RuntimeException { public DecompressedDataTooLarge() { super("Decompressed data exceeds maximum size"); } } }
3e0c8960bf5fc1bb9e6e4dc1b5b23252ccfd1811
3,853
java
Java
presto-raptor/src/main/java/com/facebook/presto/raptor/storage/Row.java
houshanren/presto
32c7b6e86b81816acd9910791e927a181d3f2972
[ "Apache-2.0" ]
456
2015-04-23T09:24:25.000Z
2022-01-11T08:49:25.000Z
presto-raptor/src/main/java/com/facebook/presto/raptor/storage/Row.java
houshanren/presto
32c7b6e86b81816acd9910791e927a181d3f2972
[ "Apache-2.0" ]
10
2015-08-02T15:37:23.000Z
2020-11-18T07:33:46.000Z
presto-raptor/src/main/java/com/facebook/presto/raptor/storage/Row.java
gcnonato/presto
d58caea92031fd5cdd8b9f2620c7619c372bc148
[ "Apache-2.0" ]
123
2015-04-30T04:04:40.000Z
2021-04-08T09:57:34.000Z
34.711712
153
0.63483
5,329
/* * 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.facebook.presto.raptor.storage; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.VarcharType; import io.airlift.slice.Slice; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Verify.verify; import static io.airlift.slice.SizeOf.SIZE_OF_BYTE; import static io.airlift.slice.SizeOf.SIZE_OF_DOUBLE; import static io.airlift.slice.SizeOf.SIZE_OF_LONG; import static java.util.Objects.requireNonNull; public class Row { private final List<Object> columns; private final int sizeInBytes; public Row(List<Object> columns, int sizeInBytes) { this.columns = requireNonNull(columns, "columns is null"); checkArgument(sizeInBytes >= 0, "sizeInBytes must be >= 0"); this.sizeInBytes = sizeInBytes; } public List<Object> getColumns() { return columns; } public int getSizeInBytes() { return sizeInBytes; } public static Row extractRow(Page page, int position, List<Type> types) { checkArgument(page.getChannelCount() == types.size(), "channelCount does not match"); checkArgument(position < page.getPositionCount(), "Requested position %s from a page with positionCount %s ", position, page.getPositionCount()); RowBuilder rowBuilder = new RowBuilder(); for (int channel = 0; channel < page.getChannelCount(); channel++) { Block block = page.getBlock(channel); Type type = types.get(channel); if (block.isNull(position)) { rowBuilder.add(null, SIZE_OF_BYTE); } else if (type.getJavaType() == boolean.class) { rowBuilder.add(type.getBoolean(block, position), SIZE_OF_BYTE); } else if (type.getJavaType() == long.class) { rowBuilder.add(type.getLong(block, position), SIZE_OF_LONG); } else if (type.getJavaType() == double.class) { rowBuilder.add(type.getDouble(block, position), SIZE_OF_DOUBLE); } else if (type.getJavaType() == Slice.class) { byte[] bytes = type.getSlice(block, position).getBytes(); Object value = type.equals(VarcharType.VARCHAR) ? new String(bytes) : bytes; rowBuilder.add(value, bytes.length); } else { throw new AssertionError("unimplemented type: " + type); } } Row row = rowBuilder.build(); verify(row.getColumns().size() == types.size(), "Column count in row: %s Expected column count: %s", row.getColumns().size(), types.size()); return row; } private static class RowBuilder { private int rowSize; private final List<Object> columns; public RowBuilder() { this.columns = new ArrayList<>(); } public void add(Object value, int size) { columns.add(value); rowSize += size; } public Row build() { return new Row(columns, rowSize); } } }
3e0c89655c9c71c616f1dcd55ede7a16020d95e2
1,154
java
Java
compiler/extensions/doc/src/zserio/emit/doc/IterableComparator.java
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
2
2019-02-06T17:50:24.000Z
2019-11-20T16:51:34.000Z
compiler/extensions/doc/src/zserio/emit/doc/IterableComparator.java
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
1
2019-11-25T16:25:51.000Z
2019-11-25T18:09:39.000Z
compiler/extensions/doc/src/zserio/emit/doc/IterableComparator.java
Klebert-Engineering/zserio-1
fbb4fc42d9ab6f3afa6c040a36267357399180f4
[ "BSD-3-Clause" ]
null
null
null
29.589744
102
0.62825
5,330
package zserio.emit.doc; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; /** * A lexicographical comparator on sequences. * * @param <T> Type of the element of the sequence. The type itself must implement Comparable&lt;T&gt;. */ class IterableComparator<T extends Comparable<T>> implements Comparator<Iterable<T>>, Serializable { @Override public int compare(Iterable<T> a, Iterable<T> b) { Iterator<T> iteratorA = a.iterator(); Iterator<T> iteratorB = b.iterator(); while (iteratorA.hasNext() && iteratorB.hasNext()) { final T valueA = iteratorA.next(); final T valueB = iteratorB.next(); final int result = valueA.compareTo(valueB); if (result != 0) return result; } if (!iteratorA.hasNext() && !iteratorB.hasNext()) return 0; // sequences are equal // the lengths of the sequences differs -> shorter is "smaller" return iteratorA.hasNext() ? +1 : -1; } // serializable to satisfy FindBugs private static final long serialVersionUID = 1L; }
3e0c8ae7f9dd4a9701d86cfbd9c117af6537c7be
8,094
java
Java
waltz-integration-test/src/test/java/org/finos/waltz/integration_test/inmem/service/PermissionGroupServiceTest.java
khartec/waltz
fdfa6f386b70f2308b9abeecf804be350707b398
[ "Apache-2.0" ]
77
2016-06-17T11:01:16.000Z
2020-02-28T04:00:31.000Z
waltz-integration-test/src/test/java/org/finos/waltz/integration_test/inmem/service/PermissionGroupServiceTest.java
khartec/waltz
fdfa6f386b70f2308b9abeecf804be350707b398
[ "Apache-2.0" ]
2,778
2016-01-21T20:44:52.000Z
2020-03-09T13:27:07.000Z
waltz-integration-test/src/test/java/org/finos/waltz/integration_test/inmem/service/PermissionGroupServiceTest.java
khartec/waltz
fdfa6f386b70f2308b9abeecf804be350707b398
[ "Apache-2.0" ]
42
2016-01-21T21:54:58.000Z
2020-03-05T21:06:46.000Z
43.751351
152
0.736719
5,331
package org.finos.waltz.integration_test.inmem.service; import org.finos.waltz.integration_test.inmem.BaseInMemoryIntegrationTest; import org.finos.waltz.integration_test.inmem.helpers.AppHelper; import org.finos.waltz.integration_test.inmem.helpers.InvolvementHelper; import org.finos.waltz.integration_test.inmem.helpers.PersonHelper; import org.finos.waltz.model.EntityKind; import org.finos.waltz.model.EntityReference; import org.finos.waltz.model.Operation; import org.finos.waltz.model.permission_group.CheckPermissionCommand; import org.finos.waltz.model.permission_group.ImmutableCheckPermissionCommand; import org.finos.waltz.model.permission_group.Permission; import org.finos.waltz.schema.tables.records.*; import org.finos.waltz.service.permission.PermissionGroupService; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Set; import static java.util.Collections.emptySet; import static org.finos.waltz.common.MapUtilities.indexBy; import static org.finos.waltz.common.SetUtilities.asSet; import static org.finos.waltz.common.SetUtilities.map; import static org.finos.waltz.integration_test.inmem.helpers.NameHelper.mkName; import static org.finos.waltz.schema.tables.InvolvementGroup.INVOLVEMENT_GROUP; import static org.finos.waltz.schema.tables.InvolvementGroupEntry.INVOLVEMENT_GROUP_ENTRY; import static org.finos.waltz.schema.tables.PermissionGroup.PERMISSION_GROUP; import static org.finos.waltz.schema.tables.PermissionGroupEntry.PERMISSION_GROUP_ENTRY; import static org.finos.waltz.schema.tables.PermissionGroupInvolvement.PERMISSION_GROUP_INVOLVEMENT; import static org.junit.jupiter.api.Assertions.*; @Service public class PermissionGroupServiceTest extends BaseInMemoryIntegrationTest { @Autowired private DSLContext dsl; @Autowired private AppHelper appHelper; @Autowired private PermissionGroupService permissionGroupService; @Autowired private PersonHelper personHelper; @Autowired private InvolvementHelper involvementHelper; private final String stem = "pgst"; @Test public void checkPerms() { String u1 = mkName(stem, "user1"); Long u1Id = personHelper.createPerson(u1); String u2 = mkName(stem, "user2"); Long u2Id = personHelper.createPerson(u2); String u3 = mkName(stem, "user3"); Long u3Id = personHelper.createPerson(u3); EntityReference appA = appHelper.createNewApp(mkName(stem, "appA"), ouIds.a); EntityReference appB = appHelper.createNewApp(mkName(stem, "appB"), ouIds.a); long privKind = involvementHelper.mkInvolvementKind(mkName(stem, "privileged")); long nonPrivKind = involvementHelper.mkInvolvementKind(mkName(stem, "non_privileged")); assertTrue(permissionGroupService.hasPermission(mkCommand(u1, appA)), "u1 should have access as is open by default"); setupSpecificPermissionGroupForApp(appB, privKind); involvementHelper.createInvolvement(u1Id, privKind, appB); involvementHelper.createInvolvement(u1Id, nonPrivKind, appB); involvementHelper.createInvolvement(u2Id, nonPrivKind, appB); assertTrue(permissionGroupService.hasPermission(mkCommand(u1, appB)), "u1 should have access as they have the right priv"); assertFalse(permissionGroupService.hasPermission(mkCommand(u2, appB)), "u2 should not have access as they have the wrong priv"); assertFalse(permissionGroupService.hasPermission(mkCommand(u3, appB)), "u3 should not have access as they have the no privs"); } @Test public void findPermissionsForSubjectKind() { EntityReference appA = appHelper.createNewApp(mkName(stem, "appA"), ouIds.a); String u1 = mkName(stem, "user1"); assertEquals(emptySet(), permissionGroupService.findPermissionsForOperationOnEntityRef(appA, Operation.ATTEST, u1), "if person does not exists, should return no permissions"); Long u1Id = personHelper.createPerson(u1); long privKind = involvementHelper.mkInvolvementKind(mkName(stem, "privileged")); Set<Permission> permissionsForOperationOnEntityKind = permissionGroupService.findPermissionsForOperationOnEntityRef(appA, Operation.ATTEST, u1); assertEquals( asSet(EntityKind.LOGICAL_DATA_FLOW, EntityKind.PHYSICAL_FLOW, EntityKind.MEASURABLE_RATING), map(permissionsForOperationOnEntityKind, Permission::subjectKind), "u1 should have default permissions for all attestation qualifiers"); setupSpecificPermissionGroupForApp(appA, privKind); Set<Permission> userHasNoExtraPermissions = permissionGroupService.findPermissionsForOperationOnEntityRef(appA, Operation.ATTEST, u1); Map<EntityKind, Permission> permissionsByKind = indexBy(userHasNoExtraPermissions, Permission::subjectKind); Permission logicalFlowPermission = permissionsByKind.get(EntityKind.LOGICAL_DATA_FLOW); assertNull(logicalFlowPermission, "u1 should have no permissions for data flows as doesn't have the all involvements required"); involvementHelper.createInvolvement(u1Id, privKind, appA); Set<Permission> withExtraPermissions = permissionGroupService.findPermissionsForOperationOnEntityRef(appA, Operation.ATTEST, u1); assertEquals( asSet(EntityKind.LOGICAL_DATA_FLOW, EntityKind.PHYSICAL_FLOW, EntityKind.MEASURABLE_RATING), map(withExtraPermissions, Permission::subjectKind), "u1 should all permissions as they have the extra involvement required for logical flows"); } private CheckPermissionCommand mkCommand(String u1, EntityReference appA) { return ImmutableCheckPermissionCommand .builder() .parentEntityRef(appA) .operation(Operation.ATTEST) .subjectKind(EntityKind.LOGICAL_DATA_FLOW) .qualifierKind(null) .qualifierId(null) .user(u1) .build(); } private Long setupSpecificPermissionGroupForApp(EntityReference appRef, Long involvementKindId) { InvolvementGroupRecord ig = setupInvolvementGroup(involvementKindId); PermissionGroupRecord pg = setupPermissionGroup(appRef, ig); return pg.getId(); } private PermissionGroupRecord setupPermissionGroup(EntityReference appRef, InvolvementGroupRecord ig) { String pgName = mkName(stem, "_pg"); PermissionGroupRecord pg = dsl.newRecord(PERMISSION_GROUP); pg.setDescription("test group: " + pgName); pg.setIsDefault(false); pg.setExternalId(pgName); pg.setName(pgName); pg.setProvenance(mkName(stem, "prov")); pg.insert(); PermissionGroupEntryRecord pge = dsl.newRecord(PERMISSION_GROUP_ENTRY); pge.setPermissionGroupId(pg.getId()); pge.setApplicationId(appRef.id()); pge.insert(); PermissionGroupInvolvementRecord pgi = dsl.newRecord(PERMISSION_GROUP_INVOLVEMENT); pgi.setPermissionGroupId(pg.getId()); pgi.setOperation(Operation.ATTEST.name()); pgi.setSubjectKind(EntityKind.LOGICAL_DATA_FLOW.name()); pgi.setParentKind(EntityKind.APPLICATION.name()); pgi.setInvolvementGroupId(ig.getId()); pgi.insert(); return pg; } private InvolvementGroupRecord setupInvolvementGroup(Long involvementKindId) { String igName = mkName(stem, "_ig"); InvolvementGroupRecord ig = dsl.newRecord(INVOLVEMENT_GROUP); ig.setName(igName); ig.setExternalId(igName); ig.setProvenance(mkName(stem, "prov")); ig.insert(); InvolvementGroupEntryRecord ige = dsl.newRecord(INVOLVEMENT_GROUP_ENTRY); ige.setInvolvementGroupId(ig.getId()); ige.setInvolvementKindId(involvementKindId); ige.insert(); return ig; } }
3e0c8cb65cc25a147a1715cf56028aef9d43f725
550
java
Java
NLPCCd/Camel/1179_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
NLPCCd/Camel/1179_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
NLPCCd/Camel/1179_1.java
sgholamian/log-aware-clone-detection
9993cb081c420413c231d1807bfff342c39aa69a
[ "MIT" ]
null
null
null
30.555556
86
0.774545
5,332
//,temp,sample_2245.java,2,14,temp,sample_2247.java,2,16 //,3 public class xxx { private AtomixReplica getOrCreateReplica() throws Exception { if (atomix == null) { ObjectHelper.notNull(getCamelContext(), "Camel Context"); ObjectHelper.notNull(address, "Atomix Node Address"); ObjectHelper.notNull(configuration, "Atomix Node Configuration"); atomix = AtomixClusterHelper.createReplica(getCamelContext(), address, configuration); if (ObjectHelper.isNotEmpty(configuration.getNodes())) { log.info("bootstrap cluster on address for nodes"); } } } };
3e0c8d7bf24f1928cd3ed8c5adae3c10ba75a0d5
289
java
Java
lib_base/src/main/java/baselib/base2/IView.java
DeIaube/YiXing
3bccb0b3bcfcbe884bb033a9345d15179d6b41c0
[ "Apache-2.0" ]
2
2018-11-04T09:46:51.000Z
2020-02-26T07:48:41.000Z
lib_base/src/main/java/baselib/base2/IView.java
DeIaube/YiXing
3bccb0b3bcfcbe884bb033a9345d15179d6b41c0
[ "Apache-2.0" ]
null
null
null
lib_base/src/main/java/baselib/base2/IView.java
DeIaube/YiXing
3bccb0b3bcfcbe884bb033a9345d15179d6b41c0
[ "Apache-2.0" ]
null
null
null
24.083333
41
0.743945
5,333
package baselib.base2; import androidx.lifecycle.LifecycleOwner; public interface IView { void showLoading(String tips); void hideLoading(); void showErrorView(String errorMsg); void makeToast(String tips); void finishView(); LifecycleOwner getLifecycleOwner(); }
3e0c8f5c9c592c0b094dfbb698aef88a25920a3c
1,887
java
Java
src/main/java/com/badlogic/gdx/tests/AudioDeviceTest.java
guxuede/gm
de58b96e61cb1b34a6579adde2bc33187737ecf5
[ "MIT" ]
1
2017-05-29T21:58:04.000Z
2017-05-29T21:58:04.000Z
src/main/java/com/badlogic/gdx/tests/AudioDeviceTest.java
guxuede/gm
de58b96e61cb1b34a6579adde2bc33187737ecf5
[ "MIT" ]
null
null
null
src/main/java/com/badlogic/gdx/tests/AudioDeviceTest.java
guxuede/gm
de58b96e61cb1b34a6579adde2bc33187737ecf5
[ "MIT" ]
null
null
null
28.590909
101
0.607313
5,334
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.tests; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.AudioDevice; import com.badlogic.gdx.tests.utils.GdxTest; public class AudioDeviceTest extends GdxTest { Thread thread; boolean stop = false; @Override public void create () { if (thread == null) { final AudioDevice device = Gdx.app.getAudio().newAudioDevice(44100, false); thread = new Thread(new Runnable() { @Override public void run () { final float frequency = 440; float increment = (float)(2 * Math.PI) * frequency / 44100; // angular increment for each sample float angle = 0; float samples[] = new float[1024]; while (!stop) { for (int i = 0; i < samples.length; i += 2) { samples[i] = 0.5f * (float)Math.sin(angle); samples[i + 1] = 2 * samples[i]; angle += increment; } device.writeSamples(samples, 0, samples.length); } device.dispose(); } }); thread.start(); } } @Override public void dispose () { stop = true; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
3e0c8f967391db8dc1c81ca0aa19b733e616f79d
6,912
java
Java
vertx-lang-jphp-gen/src/main/java/io/vertx/lang/jphp/generator/PhpClassGenerator.java
vertx-lang-jphp/vertx-lang-jphp
502666d9b039a8f61247ba8baa73d82f6f192941
[ "Apache-2.0" ]
10
2018-12-17T02:05:32.000Z
2021-09-08T12:37:25.000Z
vertx-lang-jphp-gen/src/main/java/io/vertx/lang/jphp/generator/PhpClassGenerator.java
okou19900722/vertx-lang-php
502666d9b039a8f61247ba8baa73d82f6f192941
[ "Apache-2.0" ]
2
2018-12-12T05:32:21.000Z
2018-12-12T05:32:21.000Z
vertx-lang-jphp-gen/src/main/java/io/vertx/lang/jphp/generator/PhpClassGenerator.java
okou19900722/vertx-lang-jphp
502666d9b039a8f61247ba8baa73d82f6f192941
[ "Apache-2.0" ]
1
2019-03-11T16:42:10.000Z
2019-03-11T16:42:10.000Z
35.446154
196
0.613281
5,335
package io.vertx.lang.jphp.generator; import io.vertx.codegen.ClassModel; import io.vertx.codegen.ConstantInfo; import io.vertx.codegen.MethodInfo; import io.vertx.codegen.ParamInfo; import io.vertx.codegen.doc.Tag; import io.vertx.codegen.doc.Text; import io.vertx.codegen.doc.Token; import io.vertx.codegen.type.TypeInfo; import io.vertx.codegen.writer.CodeWriter; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import static java.lang.String.join; public class PhpClassGenerator extends AbstractPhpClassGenerator { @Override public String filename(ClassModel model) { return phpFileName(model); } @Override void genPackageOrNamespace(CodeWriter writer, String packageOrNamespace) { genPhpNamespace(writer, packageOrNamespace); } @Override void genImportsOrUses(ClassModel model, CodeWriter writer) { Set<String> importClassSet = new TreeSet<>(); for (MethodInfo method : model.getMethods()) { addImport(model, importClassSet, method.getReturnType()); for (ParamInfo param : method.getParams()) { addImport(model, importClassSet, param.getType()); } } for (String importClass : importClassSet) { writer.format("use %s;", importClass.replace(".", "\\")).println(); } } @Override void genDeprecatedDoc(ClassModel model, CodeWriter writer) { writer.println(" * @deprecated"); } @Override void genClassStartTemplate(ClassModel model, CodeWriter writer) { writer.format("class %s", model.getIfaceSimpleName()).println(); writer.println("{"); } @Override void genConstant(ClassModel model, ConstantInfo constant, CodeWriter writer) { writer.println("/**"); if (constant.getDoc() != null) { Token.toHtml(constant.getDoc().getTokens(), " *", this::renderLinkToHtml, "\n", writer); } writer.format(" * @var %s", join("|", getPHPDocType(constant.getType(), false))).println(); writer.println(" * phpๆ–‡ไปถๅชๆ˜ฏไธบไบ†ๅ†™ไปฃ็ ๆ–นไพฟ๏ผŒๅธธ้‡็š„ๅฎž้™…ๅ€ผ่ฏทๅ‚่€ƒๅŽŸjavaๆ–‡ไปถ"); writer.println(" */"); writer.format("const %s = %s;", constant.getName(), getReturnInfo(constant.getType())).println(); } @Override void genConstructor(ClassModel model, CodeWriter writer) { writer.println("private function __construct()"); writer.println("{"); writer.indent().println(); writer.unindent().println("}"); } @Override void genMethod(ClassModel model, String methodName, CodeWriter writer) { List<MethodInfo> methods = model.getMethodMap().get(methodName); TypeInfo returnType = null; String returnDescription = ""; int minParamSize = Integer.MAX_VALUE; int maxParamSize = 0; boolean isStatic = false; boolean isFluent = false; for (MethodInfo method : methods) { if (returnType == null) { if (method.isFluent()) { returnType = model.getType(); } else { returnType = method.getReturnType(); } if (method.getReturnDescription() != null) { returnDescription = method.getReturnDescription().getValue(); } } int methodParamSize = method.getParams().size(); if (methodParamSize > maxParamSize) { maxParamSize = methodParamSize; } if (methodParamSize < minParamSize) { minParamSize = methodParamSize; } isStatic = method.isStaticMethod(); isFluent = method.isFluent(); } writer.println("/**"); List<Set<String>> paramTypes = new ArrayList<>(); boolean allDeprecated = true; for (MethodInfo method : methods) { if (method.getDoc() != null) { Token.toHtml(method.getDoc().getTokens(), " *", this::renderLinkToHtml, "\n", writer); writer.println(" *"); } allDeprecated = allDeprecated && method.isDeprecated(); if (methods.size() > 1) { for (ParamInfo param : method.getParams()) { Text t = param.getDescription(); writer.format(" * param $%s %s %s", param.getName(), getPHPDocType(param.getType(), true).stream().collect(Collectors.joining(" | ", "[", "]")), t == null ? "" : t.getValue()).println(); } writer.println(" * <b>"); if (method.isDeprecated()) { writer.println(" * this method is deprecated"); writer.println(" * <s>"); } writer.format(" * %s(", methodName); for (int index = 0; index < method.getParams().size(); index++) { ParamInfo param = method.getParam(index); // Set<String> params = index < paramTypes.size() ? paramTypes.get(index) : null; // if (params == null) { // params = new HashSet<>(); // paramTypes.add(params); // } // List<String> paramTypeList = getPHPDocType(param.getType()); // params.addAll(paramTypeList); if (index > 0) { writer.print(", "); } writer.print("$" + param.getName()); } writer.println(")"); if (method.isDeprecated()) { writer.println(" * </s>"); } writer.println(" * </b>"); writer.println(" *"); } for (int index = 0; index < method.getParams().size(); index++) { ParamInfo param = method.getParam(index); Set<String> params = index < paramTypes.size() ? paramTypes.get(index) : null; if (params == null) { params = new HashSet<>(); paramTypes.add(params); } List<String> paramTypeList = getPHPDocType(param.getType(), true); params.addAll(paramTypeList); // if (index > 0) { // writer.print(", "); // } // writer.print("$" + param.getName()); } } for (int index = 0; index < paramTypes.size(); index++) { writer.format(" * @param $arg%d %s", index, join(" | ", paramTypes.get(index))).println(); } String returnTypeInfo = isFluent ? "$this" : (returnType == null ? "" : join(" | ", getPHPDocType(returnType, false))); writer.format(" * @return %s %s", returnTypeInfo, returnDescription).println(); if (allDeprecated) { writer.println(" * @deprecated"); } writer.println(" */"); writer.print("public"); if (isStatic) { writer.print(" static"); } writer.format(" function %s(%s)", methodName, getParamName(minParamSize, maxParamSize)).println(); writer.println("{"); writer.indent(); if (returnType != null && returnType.getName().equals("void")) { writer.println(); } else { writer.format("return %s;", isFluent ? "$this" : getReturnInfo(returnType)).println(); } writer.unindent().println("}"); } private String getParamName(int min, int max) { return IntStream.range(0, max).mapToObj(i -> "$arg" + i + (i >= min ? " = null" : "")).collect(Collectors.joining(", ")); } @Override String renderLinkToHtml(Tag.Link link) { return renderPhpLinkToHtml(link); } }
3e0c8fd5a520df1ab68f63aa906865548255ce83
2,981
java
Java
tsfile/src/main/java/org/apache/iotdb/tsfile/read/filter/TimeFilter.java
LeiRui/iotdb-s1
aba005265805c88039083f5fa313caa3b225158c
[ "Apache-2.0" ]
42
2018-12-12T02:56:43.000Z
2021-01-01T10:48:48.000Z
tsfile/src/main/java/org/apache/iotdb/tsfile/read/filter/TimeFilter.java
LeiRui/iotdb-s1
aba005265805c88039083f5fa313caa3b225158c
[ "Apache-2.0" ]
88
2018-12-11T14:35:37.000Z
2021-06-21T11:57:21.000Z
tsfile/src/main/java/org/apache/iotdb/tsfile/read/filter/TimeFilter.java
LeiRui/iotdb-s1
aba005265805c88039083f5fa313caa3b225158c
[ "Apache-2.0" ]
15
2018-12-12T02:56:47.000Z
2020-11-02T12:09:22.000Z
26.642857
75
0.722185
5,336
/** * Copyright ยฉ 2019 Apache IoTDB(incubating) (lyhxr@example.com) * * 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.iotdb.tsfile.read.filter; import org.apache.iotdb.tsfile.read.filter.basic.Filter; import org.apache.iotdb.tsfile.read.filter.factory.FilterType; import org.apache.iotdb.tsfile.read.filter.operator.Eq; import org.apache.iotdb.tsfile.read.filter.operator.Gt; import org.apache.iotdb.tsfile.read.filter.operator.GtEq; import org.apache.iotdb.tsfile.read.filter.operator.Lt; import org.apache.iotdb.tsfile.read.filter.operator.LtEq; import org.apache.iotdb.tsfile.read.filter.operator.NotEq; import org.apache.iotdb.tsfile.read.filter.operator.NotFilter; public class TimeFilter { public static TimeEq eq(long value) { return new TimeEq(value); } public static TimeGt gt(long value) { return new TimeGt(value); } public static TimeGtEq gtEq(long value) { return new TimeGtEq(value); } public static TimeLt lt(long value) { return new TimeLt(value); } public static TimeLtEq ltEq(long value) { return new TimeLtEq(value); } public static TimeNotFilter not(Filter filter) { return new TimeNotFilter(filter); } public static TimeNotEq notEq(long value) { return new TimeNotEq(value); } public static class TimeEq extends Eq { private TimeEq(long value) { super(value, FilterType.TIME_FILTER); } } public static class TimeNotEq extends NotEq { private TimeNotEq(long value) { super(value, FilterType.TIME_FILTER); } } public static class TimeGt extends Gt { private TimeGt(long value) { super(value, FilterType.TIME_FILTER); } } public static class TimeGtEq extends GtEq { private TimeGtEq(long value) { super(value, FilterType.TIME_FILTER); } } public static class TimeLt extends Lt { private TimeLt(long value) { super(value, FilterType.TIME_FILTER); } } public static class TimeLtEq extends LtEq { private TimeLtEq(long value) { super(value, FilterType.TIME_FILTER); } } public static class TimeNotFilter extends NotFilter { private TimeNotFilter(Filter filter) { super(filter); } } }
3e0c915de4fea0bda594fe00ce45aeb605f35494
2,043
java
Java
dartagnan/src/main/java/com/dat3m/dartagnan/wmm/relation/unary/RelInverse.java
hernanponcedeleon/Dat3M
556509f6f75e7426db8413802214d48960828fbb
[ "MIT" ]
36
2018-04-04T14:30:53.000Z
2022-03-30T13:52:07.000Z
dartagnan/src/main/java/com/dat3m/dartagnan/wmm/relation/unary/RelInverse.java
hernanponcedeleon/Dat3M
556509f6f75e7426db8413802214d48960828fbb
[ "MIT" ]
148
2018-10-10T15:06:06.000Z
2022-03-21T22:03:02.000Z
dartagnan/src/main/java/com/dat3m/dartagnan/wmm/relation/unary/RelInverse.java
hernanponcedeleon/Dat3M
556509f6f75e7426db8413802214d48960828fbb
[ "MIT" ]
9
2018-07-17T13:36:08.000Z
2022-03-26T16:43:23.000Z
28.774648
115
0.66373
5,337
package com.dat3m.dartagnan.wmm.relation.unary; import com.dat3m.dartagnan.wmm.relation.Relation; import com.dat3m.dartagnan.wmm.utils.Tuple; import com.dat3m.dartagnan.wmm.utils.TupleSet; import com.google.common.collect.Sets; import org.sosy_lab.java_smt.api.BooleanFormula; import org.sosy_lab.java_smt.api.BooleanFormulaManager; import org.sosy_lab.java_smt.api.SolverContext; /** * * @author Florian Furbach */ public class RelInverse extends UnaryRelation { //TODO/Note: We can forward getSMTVar calls // to avoid encoding this completely! public static String makeTerm(Relation r1){ return r1.getName() + "^-1"; } public RelInverse(Relation r1){ super(r1); term = makeTerm(r1); } public RelInverse(Relation r1, String name) { super(r1, name); term = makeTerm(r1); } @Override public TupleSet getMinTupleSet(){ if(minTupleSet == null){ minTupleSet = r1.getMinTupleSet().inverse(); } return minTupleSet; } @Override public TupleSet getMaxTupleSet(){ if(maxTupleSet == null){ maxTupleSet = r1.getMaxTupleSet().inverse(); } return maxTupleSet; } @Override public void addEncodeTupleSet(TupleSet tuples){ TupleSet activeSet = new TupleSet(Sets.intersection(Sets.difference(tuples, encodeTupleSet), maxTupleSet)); encodeTupleSet.addAll(activeSet); activeSet.removeAll(getMinTupleSet()); if(!activeSet.isEmpty()){ r1.addEncodeTupleSet(activeSet.inverse()); } } @Override protected BooleanFormula encodeApprox(SolverContext ctx) { BooleanFormulaManager bmgr = ctx.getFormulaManager().getBooleanFormulaManager(); BooleanFormula enc = bmgr.makeTrue(); for(Tuple tuple : encodeTupleSet){ BooleanFormula opt = r1.getSMTVar(tuple.getInverse(), ctx); enc = bmgr.and(enc, bmgr.equivalence(this.getSMTVar(tuple, ctx), opt)); } return enc; } }
3e0c92c40ca9aac069286e76878b0026f1161edf
546
java
Java
RobotEV3/src/test/java/de/fhg/iais/roberta/syntax/sensors/SoundSensorTest.java
nishanth1232/openroberta-lab
1e50ddebffe1f4769156ea3906f3a7cedfdba663
[ "Apache-2.0" ]
3
2020-01-24T18:29:16.000Z
2020-09-30T10:54:09.000Z
RobotEV3/src/test/java/de/fhg/iais/roberta/syntax/sensors/SoundSensorTest.java
nishanth1232/openroberta-lab
1e50ddebffe1f4769156ea3906f3a7cedfdba663
[ "Apache-2.0" ]
null
null
null
RobotEV3/src/test/java/de/fhg/iais/roberta/syntax/sensors/SoundSensorTest.java
nishanth1232/openroberta-lab
1e50ddebffe1f4769156ea3906f3a7cedfdba663
[ "Apache-2.0" ]
null
null
null
30.333333
127
0.767399
5,338
package de.fhg.iais.roberta.syntax.sensors; import org.junit.Test; import de.fhg.iais.roberta.Ev3LejosAstTest; import de.fhg.iais.roberta.util.test.UnitTestHelper; import de.fhg.iais.roberta.worker.codegen.Ev3JavaGeneratorWorker; public class SoundSensorTest extends Ev3LejosAstTest { @Test public void getSampleSound() throws Exception { String a = "\nhal.getSoundLevel(SensorPort.S1)}"; UnitTestHelper.checkWorkers(testFactory, a, "/syntax/sensors/sensor_getSampleSound.xml", new Ev3JavaGeneratorWorker()); } }
3e0c956b1544cc9e8ec8ececc48b31305d48216e
10,938
java
Java
sources/com/flurry/sdk/C7585qd.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2019-10-01T11:34:10.000Z
2019-10-01T11:34:10.000Z
sources/com/flurry/sdk/C7585qd.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
null
null
null
sources/com/flurry/sdk/C7585qd.java
tusharchoudhary0003/Custom-Football-Game
47283462b2066ad5c53b3c901182e7ae62a34fc8
[ "MIT" ]
1
2020-05-26T05:10:33.000Z
2020-05-26T05:10:33.000Z
36.33887
166
0.553666
5,339
package com.flurry.sdk; import android.app.Activity; import android.content.Context; import com.flurry.sdk.C7531hd.C7532a; import com.flurry.sdk.C7537id.C7538a; import java.lang.ref.WeakReference; import java.util.Map; import java.util.Map.Entry; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicBoolean; /* renamed from: com.flurry.sdk.qd */ public class C7585qd { /* access modifiers changed from: private */ /* renamed from: a */ public static final String f15036a = C7585qd.class.getSimpleName(); /* renamed from: b */ private static C7585qd f15037b; /* renamed from: c */ private final Map<Context, C7531hd> f15038c = new WeakHashMap(); /* renamed from: d */ private final C7590rd f15039d = new C7590rd(); /* renamed from: e */ private final Object f15040e = new Object(); /* renamed from: f */ public long f15041f = 0; /* renamed from: g */ private C7531hd f15042g; /* access modifiers changed from: private */ /* renamed from: h */ public boolean f15043h; /* renamed from: i */ private AtomicBoolean f15044i = new AtomicBoolean(false); /* renamed from: j */ private C7452Sb<C7597sd> f15045j = new C7544jd(this); /* renamed from: k */ private C7452Sb<C7395Ib> f15046k = new C7550kd(this); /* renamed from: a */ static /* synthetic */ void m16789a(C7585qd qdVar, C7531hd hdVar) { synchronized (qdVar.f15040e) { if (qdVar.f15042g == hdVar) { C7531hd hdVar2 = qdVar.f15042g; C7602td.m16825a().mo24026b("ContinueSessionMillis", hdVar2); hdVar2.mo23959a(C7532a.f14871a); qdVar.f15042g = null; } } } private C7585qd() { C7462Ub.m16528a().mo23910a("com.flurry.android.sdk.ActivityLifecycleEvent", this.f15046k); C7462Ub.m16528a().mo23910a("com.flurry.android.sdk.FlurrySessionTimerEvent", this.f15045j); } /* renamed from: a */ public static synchronized C7585qd m16785a() { C7585qd qdVar; synchronized (C7585qd.class) { if (f15037b == null) { f15037b = new C7585qd(); } qdVar = f15037b; } return qdVar; } /* renamed from: a */ public final synchronized void mo23999a(Context context) { if (context instanceof Activity) { if (C7412Lb.m16398a().mo23853b()) { C7513ec.m16639a(3, f15036a, "bootstrap for context:".concat(String.valueOf(context))); m16793e(context); } } } /* renamed from: b */ public final synchronized void mo24002b(Context context) { mo24000a(context, false, false); } /* renamed from: a */ public final synchronized void mo24000a(Context context, boolean z, boolean z2) { if (!C7412Lb.m16398a().mo23853b() || !(context instanceof Activity)) { if (z && z2) { this.f15043h = z2; } C7513ec.m16639a(3, f15036a, "Manual onStartSession for context:".concat(String.valueOf(context))); m16786a(context, z); } } /* access modifiers changed from: private */ /* renamed from: e */ public synchronized void m16793e(Context context) { m16786a(context, false); } /* renamed from: a */ private synchronized void m16786a(Context context, boolean z) { if (mo24006d() != null && mo24006d().mo23956a() && z) { if (!this.f15039d.mo24016a()) { C7513ec.m16639a(3, f15036a, "A background session has already started. Not storing in context map because we use application context only."); return; } C7513ec.m16639a(3, f15036a, "Returning from a paused background session."); } if (mo24006d() == null || mo24006d().mo23956a() || !z) { boolean z2 = true; if (mo24006d() != null && mo24006d().mo23956a() && !z) { C7513ec.m16641a(f15036a, "New session started while background session is running. Ending background session, then will create foreground session."); this.f15044i.set(true); m16790b(C7379Fb.m16300a().f14432d, true); C7379Fb.m16300a().mo23817b(new C7556ld(this, context)); } else if (((C7531hd) this.f15038c.get(context)) == null) { this.f15039d.mo24017b(); C7531hd d = mo24006d(); if (d == null) { if (z) { d = new C7526gd(); } else { d = new C7531hd(); } d.mo23959a(C7532a.f14872b); C7513ec.m16651d(f15036a, "Flurry session started for context:".concat(String.valueOf(context))); C7537id idVar = new C7537id(); idVar.f14883b = new WeakReference<>(context); idVar.f14884c = d; idVar.f14885d = C7538a.f14887a; idVar.mo23885b(); } else { z2 = false; } this.f15038c.put(context, d); synchronized (this.f15040e) { this.f15042g = d; } this.f15044i.set(false); C7513ec.m16651d(f15036a, "Flurry session resumed for context:".concat(String.valueOf(context))); C7537id idVar2 = new C7537id(); idVar2.f14883b = new WeakReference<>(context); idVar2.f14884c = d; idVar2.f14885d = C7538a.f14888b; idVar2.mo23885b(); if (z2) { C7379Fb.m16300a().mo23817b(new C7562md(this, d, context)); } this.f15041f = 0; } else if (C7412Lb.m16398a().mo23853b()) { C7513ec.m16639a(3, f15036a, "Session already started with context:".concat(String.valueOf(context))); } else { C7513ec.m16651d(f15036a, "Session already started with context:".concat(String.valueOf(context))); } } else { C7513ec.m16641a(f15036a, "A Flurry background session can't be started while a foreground session is running."); } } /* renamed from: c */ public final synchronized void mo24005c(Context context) { mo24003b(context, false, false); } /* renamed from: b */ public final synchronized void mo24003b(Context context, boolean z, boolean z2) { if (C7412Lb.m16398a().mo23853b() && (context instanceof Activity)) { return; } if (mo24006d() == null || mo24006d().mo23956a() || !z) { if (z) { if (this.f15043h && !z2) { return; } } C7513ec.m16639a(3, f15036a, "Manual onEndSession for context:".concat(String.valueOf(context))); mo24007d(context); return; } C7513ec.m16641a(f15036a, "No background session running, can't end session."); } /* access modifiers changed from: 0000 */ /* renamed from: d */ public final synchronized void mo24007d(Context context) { m16790b(context, false); } /* renamed from: b */ private synchronized void m16790b(Context context, boolean z) { C7531hd hdVar = (C7531hd) this.f15038c.remove(context); if (z && mo24006d() != null && mo24006d().mo23956a() && this.f15039d.mo24016a()) { m16794f(); } else if (hdVar != null) { C7513ec.m16651d(f15036a, "Flurry session paused for context:".concat(String.valueOf(context))); C7537id idVar = new C7537id(); idVar.f14883b = new WeakReference<>(context); idVar.f14884c = hdVar; C7475Xa.m16549a(); idVar.f14886e = C7475Xa.m16551c(); idVar.f14885d = C7538a.f14889c; idVar.mo23885b(); if (m16795g() == 0) { if (z) { m16794f(); } else { this.f15039d.mo24015a(hdVar.mo23957b()); } this.f15041f = System.currentTimeMillis(); return; } this.f15041f = 0; } else if (C7412Lb.m16398a().mo23853b()) { C7513ec.m16639a(3, f15036a, "Session cannot be ended, session not found for context:".concat(String.valueOf(context))); } else { C7513ec.m16651d(f15036a, "Session cannot be ended, session not found for context:".concat(String.valueOf(context))); } } /* access modifiers changed from: private */ /* renamed from: f */ public synchronized void m16794f() { int g = m16795g(); if (g > 0) { C7513ec.m16639a(5, f15036a, "Session cannot be finalized, sessionContextCount:".concat(String.valueOf(g))); return; } C7531hd d = mo24006d(); if (d == null) { C7513ec.m16639a(5, f15036a, "Session cannot be finalized, current session not found"); return; } String str = f15036a; StringBuilder sb = new StringBuilder("Flurry "); sb.append(d.mo23956a() ? "background" : ""); sb.append(" session ended"); C7513ec.m16651d(str, sb.toString()); C7537id idVar = new C7537id(); idVar.f14884c = d; idVar.f14885d = C7538a.f14890d; C7475Xa.m16549a(); idVar.f14886e = C7475Xa.m16551c(); idVar.mo23885b(); C7379Fb.m16300a().mo23817b(new C7567nd(this, d)); } /* renamed from: b */ public final synchronized void mo24001b() { for (Entry entry : this.f15038c.entrySet()) { C7537id idVar = new C7537id(); idVar.f14883b = new WeakReference<>(entry.getKey()); idVar.f14884c = (C7531hd) entry.getValue(); idVar.f14885d = C7538a.f14889c; C7475Xa.m16549a(); idVar.f14886e = C7475Xa.m16551c(); idVar.mo23885b(); } this.f15038c.clear(); C7379Fb.m16300a().mo23817b(new C7573od(this)); } /* renamed from: g */ private synchronized int m16795g() { return this.f15038c.size(); } /* renamed from: c */ public final synchronized int mo24004c() { if (this.f15044i.get()) { return C7532a.f14872b; } C7531hd d = mo24006d(); if (d == null) { C7513ec.m16639a(2, f15036a, "Session not found. No active session"); return C7532a.f14871a; } return d.mo23961c(); } /* renamed from: d */ public final C7531hd mo24006d() { C7531hd hdVar; synchronized (this.f15040e) { hdVar = this.f15042g; } return hdVar; } }
3e0c959436cbef38443560254a7f7abd4d52a9c1
274
java
Java
core/src/xal/tools/correlator/BinUpdate.java
luxiaohan/openxal-csns-luxh
451f4e8e723237bd50e2815cedca47cf2575552d
[ "BSD-3-Clause" ]
10
2016-01-04T19:00:27.000Z
2021-06-27T13:43:29.000Z
core/src/xal/tools/correlator/BinUpdate.java
luxiaohan/openxal-csns-luxh
451f4e8e723237bd50e2815cedca47cf2575552d
[ "BSD-3-Clause" ]
18
2016-02-09T14:46:47.000Z
2019-02-14T13:17:24.000Z
core/src/xal/tools/correlator/BinUpdate.java
luxiaohan/openxal-csns-luxh
451f4e8e723237bd50e2815cedca47cf2575552d
[ "BSD-3-Clause" ]
8
2016-01-04T14:05:51.000Z
2021-02-06T02:23:27.000Z
15.222222
95
0.660584
5,340
/* * BinUpdate.java * * Created on June 27, 2002, 10:11 AM */ package xal.tools.correlator; /** * * @author tap * @version */ interface BinUpdate<RecordType> { public void newEvent( final String name, final RecordType record, final double timestamp ); }
3e0c95a9b14635c40eea623ba755f948dcb5d73f
395
java
Java
app/src/main/java/com/jaxsen/xianghacaipu/utils/BannerLoader.java
qianligu/xianghacaipu
81e209c420473f3cb7732cc3112f0cd236063aaa
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jaxsen/xianghacaipu/utils/BannerLoader.java
qianligu/xianghacaipu
81e209c420473f3cb7732cc3112f0cd236063aaa
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/jaxsen/xianghacaipu/utils/BannerLoader.java
qianligu/xianghacaipu
81e209c420473f3cb7732cc3112f0cd236063aaa
[ "Apache-2.0" ]
null
null
null
24.6875
78
0.764557
5,341
package com.jaxsen.xianghacaipu.utils; import android.content.Context; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.youth.banner.loader.ImageLoader; public class BannerLoader extends ImageLoader { @Override public void displayImage(Context context, Object o, ImageView imageView) { Glide.with(context).load((String)o).into(imageView); } }
3e0c96044db00e7f55e2759ee3159ffe1a41fa69
589
java
Java
ByteByByte/Sum/SumSolution.java
Gadigeppa-J/ds-algo-java
0f1c12d48e5045baacdf2768daae1fdf42c21893
[ "Apache-2.0" ]
null
null
null
ByteByByte/Sum/SumSolution.java
Gadigeppa-J/ds-algo-java
0f1c12d48e5045baacdf2768daae1fdf42c21893
[ "Apache-2.0" ]
null
null
null
ByteByByte/Sum/SumSolution.java
Gadigeppa-J/ds-algo-java
0f1c12d48e5045baacdf2768daae1fdf42c21893
[ "Apache-2.0" ]
null
null
null
15.918919
107
0.606112
5,342
/** * @author: Gadigeppa Muthu * @date: 06-Apr-2020 * Question: Given two integers, write a function to sum the numbers without using any arithmetic operators. * * LeetCode: 371. Sum of Two Integers (https://leetcode.com/problems/sum-of-two-integers/) **/ public class SumSolution{ public static int sum(int a, int b){ if (a==0) return b; if (b==0) return a; int sum = 0; while(b!=0){ sum = a ^ b; int carry = a & b; a=sum; b=carry<<1; } return sum; } public static void main(String[] args){ System.out.println(sum(-2, 3)); } }
3e0c968234781293d9f77a6dff72e50ed66fe418
1,102
java
Java
discovery/src/main/java/org/ethereum/beacon/discovery/DiscoveryManager.java
ethereum-node/beacon-chain-java
80481930af1e517783080da2451ec8f4fe691829
[ "Apache-2.0" ]
31
2018-12-26T05:47:13.000Z
2021-06-08T23:58:07.000Z
discovery/src/main/java/org/ethereum/beacon/discovery/DiscoveryManager.java
ethereum-node/beacon-chain-java
80481930af1e517783080da2451ec8f4fe691829
[ "Apache-2.0" ]
122
2018-12-25T12:05:54.000Z
2019-11-26T14:54:30.000Z
discovery/src/main/java/org/ethereum/beacon/discovery/DiscoveryManager.java
ethereum-node/beacon-chain-java
80481930af1e517783080da2451ec8f4fe691829
[ "Apache-2.0" ]
9
2019-01-07T09:00:41.000Z
2021-02-24T18:24:03.000Z
30.611111
141
0.735935
5,343
package org.ethereum.beacon.discovery; import org.ethereum.beacon.discovery.enr.NodeRecord; import java.util.concurrent.CompletableFuture; /** * Discovery Manager, top interface for peer discovery mechanism as described at <a * href="https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md">https://github.com/ethereum/devp2p/blob/master/discv5/discv5.md</a> */ public interface DiscoveryManager { void start(); void stop(); /** * Initiates FINDNODE with node `nodeRecord` * * @param nodeRecord Ethereum Node record * @param distance Distance to search for * @return Future which is fired when reply is received or fails in timeout/not successful * handshake/bad message exchange. */ CompletableFuture<Void> findNodes(NodeRecord nodeRecord, int distance); /** * Initiates PING with node `nodeRecord` * * @param nodeRecord Ethereum Node record * @return Future which is fired when reply is received or fails in timeout/not successful * handshake/bad message exchange. */ CompletableFuture<Void> ping(NodeRecord nodeRecord); }
3e0c9713323ec811f3309ec08a3bf2921e04d171
3,613
java
Java
src/raster/Transformer.java
Forceflow/java_rasterizer
f24b3e4671daf9795d1b24f44efe40d8d66249d0
[ "MIT" ]
1
2018-08-13T15:25:46.000Z
2018-08-13T15:25:46.000Z
src/raster/Transformer.java
Forceflow/java_rasterizer
f24b3e4671daf9795d1b24f44efe40d8d66249d0
[ "MIT" ]
null
null
null
src/raster/Transformer.java
Forceflow/java_rasterizer
f24b3e4671daf9795d1b24f44efe40d8d66249d0
[ "MIT" ]
null
null
null
24.412162
83
0.638251
5,344
package raster; import support.Matrix4f; import util.Camerasystem; import util.Point4f; import util.ScreenTriangle; import util.WorldTriangle; public class Transformer { static boolean DEBUG = false; Camerasystem c; Matrix4f ortho; Matrix4f view; Matrix4f persp; Matrix4f total; public Transformer(Camerasystem c) { // set camerasystem and compute matrices once and for all this.c = c; ortho = OrthograpicMatrix(); if(DEBUG){System.out.println("ortho \n" + ortho);} view = ViewMatrix(); if(DEBUG){System.out.println("view \n" + view);} persp = PerspectiveMatrix(); if(DEBUG){System.out.println("persp \n" + persp);} total = ortho.mul_right(persp.mul_right(view)); if(DEBUG){System.out.println("total \n" + total);} } /** * Transform a given point (using the center-of-window approach) and return a copy * @param source * @param screenx * @param screeny * @param camera * @param gaze * @param viewup * @param fov_theta * @param n * @return */ public Point4f transform(Point4f source) { Point4f trans = source.left_mul(total); return trans.scale(1/trans.w); } public ScreenTriangle transform (WorldTriangle d) { Point4f[] vertices = (Point4f[]) d.getVertices(); Point4f a = transform(vertices[0]); if(DEBUG){System.out.println("transformed vertex 1: " + a);} Point4f b = transform(vertices[1]); if(DEBUG){System.out.println("transformed vertex 2: " + b);} Point4f c = transform(vertices[2]); if(DEBUG){System.out.println("transformed vertex 3: " + c);} Point4f[] corners = {a,b,c}; return new ScreenTriangle(corners,d); } public Matrix4f getOrthoMatrix() { return ortho; } public Matrix4f getViewMatrix() { return view; } public Matrix4f getPerspMatrix() { return persp; } public Matrix4f getTotalMatrix() { return total; } private Matrix4f OrthograpicMatrix() { // first matrix Matrix4f mat1 = new Matrix4f(); mat1.m00 = c.getScreenx()/2; mat1.m03 = (c.getScreenx() -1) / 2; mat1.m11 = c.getScreeny()/2; mat1.m13 = (c.getScreeny()-1f) / 2; mat1.m22 = 1; mat1.m33 = 1; if(DEBUG){System.out.println("Ortho1 " + mat1);} // second matrix Matrix4f mat2 = new Matrix4f(); mat2.m00 = (2 / (c.getR()-c.getL())); mat2.m11 = (2 / (c.getT()-c.getB())); mat2.m22 = (2 / (c.getN()-c.getF())); mat2.m33 = 1; if(DEBUG){System.out.println("Ortho2 " + mat2);} // third matrix Matrix4f mat3 = new Matrix4f(); mat3.setIdentity(); mat3.m03 = -((c.getL()+c.getR())/2); mat3.m13 = -((c.getB()+c.getT())/2); mat3.m23 = -((c.getN()+c.getF())/2); if(DEBUG){System.out.println("Ortho3 " + mat3);} // right multiplication return mat1.mul_right(mat2.mul_right(mat3)); } private Matrix4f ViewMatrix () { // build matrix 1 Matrix4f mat1 = new Matrix4f(); mat1.m00 = c.getU().x; mat1.m10 = c.getV().x; mat1.m20 = c.getW().x; mat1.m01 = c.getU().y; mat1.m11 = c.getV().y; mat1.m21 = c.getW().y; mat1.m02 = c.getU().z; mat1.m12 = c.getV().z; mat1.m22 = c.getW().z; mat1.m33 = 1; if(DEBUG){System.out.println("View1 " + mat1);} // build matrix 2 Matrix4f mat2 = new Matrix4f(); mat2.setIdentity(); mat2.m03 = -c.getCamera().x; mat2.m13 = -c.getCamera().y; mat2.m23 = -c.getCamera().z; if(DEBUG){System.out.println("View2 " + mat2);} // multiply and return matrix return mat1.mul_right(mat2); } private Matrix4f PerspectiveMatrix() { Matrix4f mat = new Matrix4f(); mat.m00 = c.getN(); mat.m11 = c.getN(); mat.m22 = c.getN()+c.getF(); mat.m32 = 1; mat.m23 = -c.getF()*c.getN(); return mat; } }
3e0c972e38771b8e19fa189a739b3c03b05e4379
2,352
java
Java
obevo-db-impls/obevo-db-sybase-iq/src/main/java/com/gs/obevo/db/impl/platforms/sybaseiq/IqOldOdbcDataSourceFactory.java
thisisronak/obevo
f9c3e7e3b313630ecac5dd740dfdb0ca90abac28
[ "Apache-2.0" ]
218
2017-04-26T02:43:16.000Z
2022-02-12T06:24:39.000Z
obevo-db-impls/obevo-db-sybase-iq/src/main/java/com/gs/obevo/db/impl/platforms/sybaseiq/IqOldOdbcDataSourceFactory.java
thisisronak/obevo
f9c3e7e3b313630ecac5dd740dfdb0ca90abac28
[ "Apache-2.0" ]
182
2017-04-25T17:06:41.000Z
2022-02-16T00:45:46.000Z
obevo-db-impls/obevo-db-sybase-iq/src/main/java/com/gs/obevo/db/impl/platforms/sybaseiq/IqOldOdbcDataSourceFactory.java
thisisronak/obevo
f9c3e7e3b313630ecac5dd740dfdb0ca90abac28
[ "Apache-2.0" ]
68
2017-04-18T15:51:38.000Z
2022-02-01T15:17:35.000Z
37.935484
133
0.675595
5,345
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.db.impl.platforms.sybaseiq; import java.sql.Driver; import com.gs.obevo.db.api.appdata.DbEnvironment; import com.gs.obevo.util.inputreader.Credential; import org.apache.commons.lang3.SystemUtils; import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.tuple.Tuples; /** * ODBC driver data source factory using the old driver. * See here for the driver history - http://scn.sap.com/community/sql-anywhere/blog/2014/05/02/connecting-to-sql-anywhere-using-jdbc */ public class IqOldOdbcDataSourceFactory extends AbstractIqDataSourceFactory { @Override public boolean isDriverAccepted(Class<? extends Driver> driverClass) { return driverClass.getName().startsWith("ianywhere.ml.jdbcodbc"); } @Override protected Pair<String, String> getUrl(DbEnvironment env, String schema, Credential credential) { String url = "jdbc:ianywhere:" + "ServerName=" + env.getDbServer() + "" + ";LINKS=TCPIP{host=" + env.getDbHost() + ":" + env.getDbPort() + "}" + ";driver=" + getIanywhereDriverProperty(env.getIanywhereDriverProperty()) + ""; return Tuples.pair(url, credential.getPassword()); } @SuppressWarnings("WeakerAccess") protected String getIanywhereDriverProperty(String ianywhereDriverProperty) { if (ianywhereDriverProperty != null) { return ianywhereDriverProperty; } else if (SystemUtils.IS_OS_WINDOWS) { return "Sybase IQ"; } else { return "libdbodbc12_r.so"; } } @Override public boolean isIqClientLoadSupported() { return true; } }
3e0c97e3e20c074a9255d8afba8e28bb73ec6f3c
1,023
java
Java
app/src/main/java/org/sakaiproject/customviews/custom_volley/LruBitmapCache.java
comalat/comalat-android-app
bda61cf98f104b1abc20690c2aade7c38600be18
[ "ECL-2.0" ]
null
null
null
app/src/main/java/org/sakaiproject/customviews/custom_volley/LruBitmapCache.java
comalat/comalat-android-app
bda61cf98f104b1abc20690c2aade7c38600be18
[ "ECL-2.0" ]
null
null
null
app/src/main/java/org/sakaiproject/customviews/custom_volley/LruBitmapCache.java
comalat/comalat-android-app
bda61cf98f104b1abc20690c2aade7c38600be18
[ "ECL-2.0" ]
null
null
null
24.357143
78
0.668622
5,346
package org.sakaiproject.customviews.custom_volley; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.android.volley.toolbox.ImageLoader; /** * Created by vspallas on 09/02/16. */ public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { public static int getDefaultLruCacheSize() { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 8; return cacheSize; } public LruBitmapCache() { this(getDefaultLruCacheSize()); } public LruBitmapCache(int sizeInKiloBytes) { super(sizeInKiloBytes); } @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight() / 1024; } @Override public Bitmap getBitmap(String url) { return get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); } }
3e0c9ad9323534bc4827a2bd57e885359f64d596
353
java
Java
app/src/main/java/com/example/tigol/PaymentVerification.java
dewiayuparaswatti97/TIGOL.com
f3affb2cf34ada03b476f162875e7e42484944cb
[ "MIT" ]
null
null
null
app/src/main/java/com/example/tigol/PaymentVerification.java
dewiayuparaswatti97/TIGOL.com
f3affb2cf34ada03b476f162875e7e42484944cb
[ "MIT" ]
14
2019-02-19T07:03:25.000Z
2019-04-29T11:58:11.000Z
app/src/main/java/com/example/tigol/PaymentVerification.java
dewiayuparaswatti97/TIGOL.com
f3affb2cf34ada03b476f162875e7e42484944cb
[ "MIT" ]
null
null
null
25.214286
63
0.773371
5,347
package com.example.tigol; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class PaymentVerification extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_payment_verification); } }
3e0c9c4c7ad7c68f97d44d82a167cf9b3b542fc9
694
java
Java
src/main/java/com/equator/antlr/grammar/hello/HelloListener.java
libinkai/AntlrLearning
e4c88334b25bb009560e3e15b6d0003c868454ee
[ "MIT" ]
null
null
null
src/main/java/com/equator/antlr/grammar/hello/HelloListener.java
libinkai/AntlrLearning
e4c88334b25bb009560e3e15b6d0003c868454ee
[ "MIT" ]
null
null
null
src/main/java/com/equator/antlr/grammar/hello/HelloListener.java
libinkai/AntlrLearning
e4c88334b25bb009560e3e15b6d0003c868454ee
[ "MIT" ]
null
null
null
34.7
128
0.759366
5,348
// Generated from /Users/bytedance/Desktop/workplace/code/AntlrLearning/src/main/resources/grammar/hello/Hello.g4 by ANTLR 4.9.1 package grammar.hello; import org.antlr.v4.runtime.tree.ParseTreeListener; /** * This interface defines a complete listener for a parse tree produced by * {@link HelloParser}. */ public interface HelloListener extends ParseTreeListener { /** * Enter a parse tree produced by {@link HelloParser#statement}. * @param ctx the parse tree */ void enterStatement(HelloParser.StatementContext ctx); /** * Exit a parse tree produced by {@link HelloParser#statement}. * @param ctx the parse tree */ void exitStatement(HelloParser.StatementContext ctx); }
3e0c9cac10481092f0193018ff96bd3f3d00ff74
4,274
java
Java
app/src/main/java/com/steven/avgraphics/module/av/HWCodec.java
wasd845/AVGraphics
e4cf62cedb33ef8b08ef0b52c1ae3180426dec42
[ "Apache-2.0" ]
121
2018-07-26T06:47:04.000Z
2022-03-20T12:42:04.000Z
app/src/main/java/com/steven/avgraphics/module/av/HWCodec.java
wasd845/AVGraphics
e4cf62cedb33ef8b08ef0b52c1ae3180426dec42
[ "Apache-2.0" ]
2
2019-04-01T07:25:17.000Z
2020-11-12T02:44:27.000Z
app/src/main/java/com/steven/avgraphics/module/av/HWCodec.java
wasd845/AVGraphics
e4cf62cedb33ef8b08ef0b52c1ae3180426dec42
[ "Apache-2.0" ]
46
2018-08-22T11:32:59.000Z
2022-01-21T08:38:52.000Z
35.616667
100
0.579785
5,349
package com.steven.avgraphics.module.av; import android.media.MediaCodec; import android.media.MediaExtractor; import android.media.MediaFormat; import android.media.MediaMuxer; import android.os.Build; import android.util.Log; import android.util.SparseIntArray; import java.io.IOException; import java.nio.ByteBuffer; @SuppressWarnings("WeakerAccess") public class HWCodec { private static final String TAG = "HWCodec"; public static final int MEDIA_TYPE_VIDEO = 1; public static final int MEDIA_TYPE_AUDIO = 2; public static final int MEDIA_TYPE_UNKNOWN = 0; public static final String MIME_TYPE_AVC = "video/avc"; public static final String MIME_TYPE_AAC = "audio/mp4a-latm"; public static int getMediaType(MediaFormat format) { String mime = format.getString(MediaFormat.KEY_MIME); if (mime.startsWith("video/")) { return MEDIA_TYPE_VIDEO; } else if (mime.startsWith("audio/")) { return MEDIA_TYPE_AUDIO; } return MEDIA_TYPE_UNKNOWN; } public static boolean transcode(String srcFilePath, String dstFilePath) { MediaExtractor extractor = null; MediaMuxer muxer = null; try { extractor = new MediaExtractor(); extractor.setDataSource(srcFilePath); muxer = new MediaMuxer(dstFilePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4); doTranscode(extractor, muxer); } catch (IOException e) { Log.e(TAG, "doTranscode io exception: " + e.getLocalizedMessage()); return false; } catch (Exception e) { Log.e(TAG, "doTranscode exception: " + e.getLocalizedMessage()); return false; } finally { try { if (extractor != null) { extractor.release(); } if (muxer != null) { muxer.stop(); muxer.release(); } } catch (Exception e) { Log.e(TAG, "doTranscode close exception: " + e.getLocalizedMessage()); } } return true; } private static void doTranscode(MediaExtractor extractor, MediaMuxer muxer) throws IOException { int trackCount = extractor.getTrackCount(); SparseIntArray trackMap = new SparseIntArray(trackCount); for (int i = 0; i < trackCount; ++i) { MediaFormat format = extractor.getTrackFormat(i); if (getMediaType(format) == MEDIA_TYPE_UNKNOWN) { trackMap.put(i, -1); } else { int trackIndex = muxer.addTrack(format); trackMap.put(i, trackIndex); } } muxer.start(); for (int i = 0; i < trackCount; ++i) { int trackIndex = trackMap.get(i); if (trackIndex == -1) { continue; } extractor.selectTrack(i); MediaFormat format = extractor.getTrackFormat(i); int maxBufferSize = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE); long timeUnit = 0; boolean isVideo = getMediaType(format) == MEDIA_TYPE_VIDEO; if (isVideo) { int framerate = format.getInteger(MediaFormat.KEY_FRAME_RATE); timeUnit = 1000 * 1000 / framerate; } ByteBuffer source = ByteBuffer.allocate(maxBufferSize); MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); int size; while ((size = extractor.readSampleData(source, 0)) >= 0) { bufferInfo.offset = 0; bufferInfo.size = size; bufferInfo.flags = extractor.getSampleFlags(); // api 24 ไปฅไธŠๅฏไปฅๅฐ่ฃ… b ๅธง๏ผŒไน‹ๅ‰็‰ˆๆœฌ็š„่ง†้ข‘ๅธง็š„ pts ๅฟ…้กปๆ˜ฏ้€’ๅขž็š„ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || !isVideo) { bufferInfo.presentationTimeUs = extractor.getSampleTime(); } else { bufferInfo.presentationTimeUs += timeUnit; } muxer.writeSampleData(trackIndex, source, bufferInfo); extractor.advance(); } extractor.unselectTrack(i); } } }
3e0c9ce6b29ddef798319e31096f3989f63adbe2
9,941
java
Java
java/java-impl/src/com/intellij/codeInspection/java18api/Java8CollectionRemoveIfInspection.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2019-04-28T07:48:50.000Z
2020-12-11T14:18:08.000Z
java/java-impl/src/com/intellij/codeInspection/java18api/Java8CollectionRemoveIfInspection.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2022-02-19T09:45:05.000Z
2022-02-27T20:32:55.000Z
java/java-impl/src/com/intellij/codeInspection/java18api/Java8CollectionRemoveIfInspection.java
dunno99/intellij-community
aa656a5d874b947271b896b2105e4370827b9149
[ "Apache-2.0" ]
2
2020-03-15T08:57:37.000Z
2020-04-07T04:48:14.000Z
51.507772
140
0.709486
5,350
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.java18api; import com.intellij.codeInsight.daemon.QuickFixBundle; import com.intellij.codeInspection.*; import com.intellij.codeInspection.util.ForEachCollectionTraversal; import com.intellij.codeInspection.util.IterableTraversal; import com.intellij.codeInspection.util.IteratorDeclaration; import com.intellij.codeInspection.util.LambdaGenerationUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.TextRange; import com.intellij.pom.java.JavaFeature; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.intellij.psi.codeStyle.SuggestedNameInfo; import com.intellij.psi.codeStyle.VariableKind; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import com.siyeh.ig.psiutils.CommentTracker; import com.siyeh.ig.psiutils.ControlFlowUtils; import com.siyeh.ig.psiutils.VariableAccessUtils; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static com.intellij.util.ObjectUtils.tryCast; public class Java8CollectionRemoveIfInspection extends AbstractBaseJavaLocalInspectionTool { @NotNull @Override public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) { if (!JavaFeature.ADVANCED_COLLECTIONS_API.isFeatureSupported(holder.getFile())) { return PsiElementVisitor.EMPTY_VISITOR; } return new JavaElementVisitor() { void handleIteratorLoop(PsiLoopStatement statement, PsiJavaToken endToken, IteratorDeclaration declaration) { if (endToken == null || declaration == null || !declaration.isCollection()) return; PsiStatement[] statements = ControlFlowUtils.unwrapBlock(statement.getBody()); if (statements.length == 2 && statements[1] instanceof PsiIfStatement) { PsiVariable element = declaration.getNextElementVariable(statements[0]); if (element == null) return; PsiIfStatement ifStatement = (PsiIfStatement)statements[1]; if(checkAndExtractCondition(declaration, ifStatement) == null) return; registerProblem(statement, endToken); } else if (statements.length == 1 && statements[0] instanceof PsiIfStatement){ PsiIfStatement ifStatement = (PsiIfStatement)statements[0]; PsiExpression condition = checkAndExtractCondition(declaration, ifStatement); if (condition == null) return; PsiElement ref = declaration.findOnlyIteratorRef(condition); if (ref != null && declaration.isIteratorMethodCall(ref.getParent().getParent(), "next") && isAlwaysExecuted(condition, ref)) { registerProblem(statement, endToken); } } } private boolean isAlwaysExecuted(PsiExpression condition, PsiElement ref) { while(ref != condition) { PsiElement parent = ref.getParent(); if(parent instanceof PsiPolyadicExpression) { PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)parent; IElementType type = polyadicExpression.getOperationTokenType(); if ((type.equals(JavaTokenType.ANDAND) || type.equals(JavaTokenType.OROR)) && polyadicExpression.getOperands()[0] != ref) { return false; } } if(parent instanceof PsiConditionalExpression && ((PsiConditionalExpression)parent).getCondition() != ref) { return false; } ref = parent; } return true; } private void registerProblem(PsiLoopStatement statement, PsiJavaToken endToken) { holder.registerProblem(statement, new TextRange(0, endToken.getTextOffset() - statement.getTextOffset() + 1), QuickFixBundle.message("java.8.collection.removeif.inspection.description"), new ReplaceWithRemoveIfQuickFix()); } @Nullable private PsiExpression checkAndExtractCondition(IterableTraversal traversal, PsiIfStatement ifStatement) { PsiExpression condition = ifStatement.getCondition(); if (condition == null || ifStatement.getElseBranch() != null) return null; PsiStatement thenStatement = ControlFlowUtils.stripBraces(ifStatement.getThenBranch()); if (!(thenStatement instanceof PsiExpressionStatement)) return null; if (!traversal.isRemoveCall(((PsiExpressionStatement)thenStatement).getExpression())) return null; if (!LambdaGenerationUtil.canBeUncheckedLambda(condition)) return null; PsiReferenceExpression iterable = tryCast(PsiUtil.skipParenthesizedExprDown(traversal.getIterable()), PsiReferenceExpression.class); PsiVariable iterableVariable = iterable != null ? tryCast(iterable.resolve(), PsiVariable.class) : null; if (iterableVariable != null && VariableAccessUtils.variableIsUsed(iterableVariable, condition)) return null; return condition; } @Override public void visitForStatement(PsiForStatement statement) { super.visitForStatement(statement); IteratorDeclaration declaration = IteratorDeclaration.fromLoop(statement); handleIteratorLoop(statement, statement.getRParenth(), declaration); } @Override public void visitWhileStatement(PsiWhileStatement statement) { super.visitWhileStatement(statement); IteratorDeclaration declaration = IteratorDeclaration.fromLoop(statement); handleIteratorLoop(statement, statement.getRParenth(), declaration); } @Override public void visitForeachStatement(PsiForeachStatement statement) { super.visitForeachStatement(statement); ForEachCollectionTraversal traversal = ForEachCollectionTraversal.fromLoop(statement); if (traversal == null) return; PsiIfStatement ifStatement = tryCast(ControlFlowUtils.stripBraces(statement.getBody()), PsiIfStatement.class); if (ifStatement == null) return; PsiExpression condition = checkAndExtractCondition(traversal, ifStatement); if (condition == null) return; PsiJavaToken endToken = statement.getRParenth(); if (endToken == null) return; registerProblem(statement, endToken); } }; } private static class ReplaceWithRemoveIfQuickFix implements LocalQuickFix { @Nls @NotNull @Override public String getFamilyName() { return QuickFixBundle.message("java.8.collection.removeif.inspection.fix.name"); } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getStartElement(); if(!(element instanceof PsiLoopStatement)) return; PsiLoopStatement loop = (PsiLoopStatement)element; PsiStatement[] statements = ControlFlowUtils.unwrapBlock(loop.getBody()); PsiIfStatement ifStatement = tryCast(ArrayUtil.getLastElement(statements), PsiIfStatement.class); if (ifStatement == null) return; PsiExpression condition = ifStatement.getCondition(); if (condition == null) return; String replacement; CommentTracker ct = new CommentTracker(); if (loop instanceof PsiForeachStatement) { ForEachCollectionTraversal traversal = ForEachCollectionTraversal.fromLoop((PsiForeachStatement)loop); if (traversal == null || statements.length != 1) return; replacement = generateRemoveIf(traversal, ct, condition, traversal.getParameter().getName()); } else { IteratorDeclaration declaration = IteratorDeclaration.fromLoop(loop); if (declaration == null) return; switch (statements.length) { case 1: PsiElement ref = declaration.findOnlyIteratorRef(condition); if (ref == null) return; PsiElement call = ref.getParent().getParent(); if (!declaration.isIteratorMethodCall(call, "next")) return; PsiType type = ((PsiExpression)call).getType(); JavaCodeStyleManager javaCodeStyleManager = JavaCodeStyleManager.getInstance(project); SuggestedNameInfo info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, type); if (info.names.length == 0) { info = javaCodeStyleManager.suggestVariableName(VariableKind.PARAMETER, "value", null, type); } String paramName = javaCodeStyleManager.suggestUniqueVariableName(info, condition, true).names[0]; ct.replace(call, JavaPsiFacade.getElementFactory(project).createIdentifier(paramName)); replacement = generateRemoveIf(declaration, ct, condition, paramName); break; case 2: PsiVariable variable = declaration.getNextElementVariable(statements[0]); if (variable == null) return; replacement = generateRemoveIf(declaration, ct, condition, variable.getName()); break; default: return; } ct.delete(declaration.getIterator()); } PsiElement result = ct.replaceAndRestoreComments(loop, replacement); LambdaCanBeMethodReferenceInspection.replaceAllLambdasWithMethodReferences(result); CodeStyleManager.getInstance(project).reformat(result); } @NotNull private static String generateRemoveIf(IterableTraversal traversal, CommentTracker ct, PsiExpression condition, String paramName) { return (traversal.getIterable() == null ? "" : ct.text(traversal.getIterable()) + ".") + "removeIf(" + paramName + "->" + ct.text(condition) + ");"; } } }
3e0c9db12ae1171a220784a62dec80494a4715eb
4,036
java
Java
Java Programming Build a Recommendation System/Recommendation System/src/com/company/RecommendationRunner.java
AhmedShouman1991/java-programming-and-software-engineering-fundamentals-specialization-ntl
1472faf65e41a645b1bc60ccd7e5fb45b27cee73
[ "MIT" ]
null
null
null
Java Programming Build a Recommendation System/Recommendation System/src/com/company/RecommendationRunner.java
AhmedShouman1991/java-programming-and-software-engineering-fundamentals-specialization-ntl
1472faf65e41a645b1bc60ccd7e5fb45b27cee73
[ "MIT" ]
null
null
null
Java Programming Build a Recommendation System/Recommendation System/src/com/company/RecommendationRunner.java
AhmedShouman1991/java-programming-and-software-engineering-fundamentals-specialization-ntl
1472faf65e41a645b1bc60ccd7e5fb45b27cee73
[ "MIT" ]
null
null
null
33.633333
112
0.522795
5,351
package com.company; import java.util.ArrayList; import java.util.Random; public class RecommendationRunner implements Recommender { @Override public ArrayList<String> getItemsToRate() { ArrayList<String> movies = MovieDatabase.filterBy(new TrueFilter()); ArrayList<String> outPut = new ArrayList<>(); for (String movieId : movies) { if (MovieDatabase.getGenres(movieId).contains("Action") && MovieDatabase.getYear(movieId) >= 2012) { outPut.add(movieId); if (outPut.size() >= 12) break; } } return outPut; } @Override public void printRecommendationsFor(String webRaterID) { FourthRatings fr = new FourthRatings(); ArrayList<Rating> webRatings = fr.getSimilarRatings(webRaterID, 1, 3); ArrayList<Rating> recommendations = new ArrayList<>(); int howMany = 6; if (webRatings.size() < 6 && webRatings.size() > 0) { howMany = webRatings.size(); } if (webRatings.size() == 0) { ArrayList<String> randomMovie = MovieDatabase.filterBy(new TrueFilter()); Random r = new Random(); for (int i = 0; i < 6; i++) { int index = r.nextInt(randomMovie.size()); String movieID = randomMovie.get(index); double movieRate = 5; recommendations.add(new Rating(movieID, movieRate)); } } for (int i = 0; i < howMany; i++) { recommendations.add(webRatings.get(i)); } System.out.println("<html>"); System.out.println("<head>"); System.out.println("<style>"); System.out.println("body{background-color :SpringGreen;}"); System.out.println(" title{\n" + " font-family:\"Courier New\", Courier, monospace;\n" + " font-size:30px;\n" + "}"); System.out.println("h2{\n" + " font-family:\"Courier New\", Courier, monospace;\n" + " color:white;\n" + " margin:0pt;\n" + " text-align: center;\n" + " padding-top:5px;\n" + " padding-bottom:10px;\n" + " border:solid;\n" + " color:black;\n"+ "}"); System.out.println("p{\n" + " font-family:\"Courier New\", Courier, monospace;\n" + " text-align: center;\n" + " background-color:white;\n" + "}"); System.out.println("</style>"); System.out.println("<title> <b> Welcome to MyRecommendation website</b></title>"); System.out.println("</head>"); System.out.println("<body>"); System.out.println("<h2> your top recommendation are : </h2>"); System.out.println("<p>"); System.out.println("<table>"); System.out.println("<tr>"); System.out.println("<th> Movie ID </th>"); System.out.println("<th> Movie title </th>"); System.out.println("<th> Movie year </th>"); System.out.println("<th> Movie Genre </th>"); System.out.println("<th> Duration </th>"); System.out.println("</tr>"); for (Rating rating : recommendations) { System.out.println("<tr>"); System.out.println("<td> "+ rating.getItem() + " </td>"); System.out.println("<td> " + MovieDatabase.getTitle(rating.getItem()) + " </td>"); System.out.println("<td> " + MovieDatabase.getYear(rating.getItem()) + " </td>"); System.out.println("<td> " + MovieDatabase.getGenres(rating.getItem()) + " </td>"); System.out.println("<td> " + MovieDatabase.getMinutes(rating.getItem()) + " </td>"); System.out.println("</tr>"); } System.out.println("</table>"); System.out.println("</p>"); System.out.println("</body>"); System.out.println("</html>"); } }
3e0c9ec2ce9bf27c43add9d523ca723f6848e4d8
3,554
java
Java
ide/versionvault/src/org/netbeans/modules/versionvault/options/ClearcaseOptions.java
HCL-TECH-SOFTWARE/netbeans
3b3599ba62d7f4ead6d939bf6b90bdf6121feff1
[ "Apache-2.0" ]
null
null
null
ide/versionvault/src/org/netbeans/modules/versionvault/options/ClearcaseOptions.java
HCL-TECH-SOFTWARE/netbeans
3b3599ba62d7f4ead6d939bf6b90bdf6121feff1
[ "Apache-2.0" ]
null
null
null
ide/versionvault/src/org/netbeans/modules/versionvault/options/ClearcaseOptions.java
HCL-TECH-SOFTWARE/netbeans
3b3599ba62d7f4ead6d939bf6b90bdf6121feff1
[ "Apache-2.0" ]
null
null
null
41.325581
95
0.746201
5,352
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved. * * Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ /* * Copyright 2021 HCL America, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.netbeans.modules.versionvault.options; import org.netbeans.spi.options.AdvancedOption; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.NbBundle; /** * Clearcase Options. * * @author Maros Sandor */ public final class ClearcaseOptions extends AdvancedOption { public String getDisplayName() { return NbBundle.getMessage(ClearcaseOptions.class, "Options.displayName"); // NOI18N } public String getTooltip() { return NbBundle.getMessage(ClearcaseOptions.class, "Options.toolTip"); // NOI18N } public OptionsPanelController create() { return new ClearcaseOptionsController(); } }
3e0ca05ab92d91fdb30993a3b2c061fbe0756921
2,840
java
Java
src/com/biomatters/plugins/biocode/assembler/verify/VerifyTaxonomyResultsDocument.java
Biomatters/biocode-lims
0ff2fdc046c6a0648e66f0203e3f4e5fa3a9f810
[ "BSD-3-Clause" ]
6
2019-04-25T13:44:16.000Z
2022-02-25T19:17:57.000Z
src/com/biomatters/plugins/biocode/assembler/verify/VerifyTaxonomyResultsDocument.java
Biomatters/biocode-lims
0ff2fdc046c6a0648e66f0203e3f4e5fa3a9f810
[ "BSD-3-Clause" ]
58
2018-08-23T23:36:25.000Z
2021-03-22T20:43:30.000Z
src/com/biomatters/plugins/biocode/assembler/verify/VerifyTaxonomyResultsDocument.java
Biomatters/biocode-lims
0ff2fdc046c6a0648e66f0203e3f4e5fa3a9f810
[ "BSD-3-Clause" ]
null
null
null
31.555556
99
0.692606
5,353
package com.biomatters.plugins.biocode.assembler.verify; import com.biomatters.geneious.publicapi.documents.AbstractPluginDocument; import com.biomatters.geneious.publicapi.documents.DocumentUtilities; import com.biomatters.geneious.publicapi.documents.XMLSerializationException; import com.biomatters.geneious.publicapi.plugin.Geneious; import com.biomatters.plugins.biocode.BiocodePlugin; import org.jdom.Element; import java.util.ArrayList; import java.util.List; /** * @author Richard */ public class VerifyTaxonomyResultsDocument extends AbstractPluginDocument { /** * Map of query to results */ private List<VerifyResult> results; private Element binningOptionsValues = null; public static final String BINNING_ELEMENT_NAME = "binningParameters"; public VerifyTaxonomyResultsDocument() { } public VerifyTaxonomyResultsDocument(List<VerifyResult> results, String keywords) { this.results = results; String nameForDocument = "Verify Taxonomy Results"; if (BiocodePlugin.compareVersions(Geneious.getApiVersion(), "4.51") < 0) { // from 5.5.1 onwards the document name will be uniqued by core nameForDocument = DocumentUtilities.getUniqueNameForDocument("Verify Taxonomy Results"); } setFieldValue("name", nameForDocument); setFieldValue("keywords", keywords); } public String getName() { return (String)getFieldValue("name"); } public String getDescription() { return null; } public String toHTML() { return null; } public List<VerifyResult> getResults() { return results; } @Override public Element toXML() { Element element = super.toXML(); Element resultsElement = new Element("results"); for (VerifyResult result : results) { resultsElement.addContent(result.toXML()); } element.addContent(resultsElement); Element binningElement = new Element(BINNING_ELEMENT_NAME); if (binningOptionsValues != null) { binningElement.addContent(binningOptionsValues.cloneContent()); } element.addContent(binningElement); return element; } @Override public void fromXML(Element root) throws XMLSerializationException { super.fromXML(root); results = new ArrayList<VerifyResult>(); for (Element result : root.getChild("results").getChildren()) { results.add(new VerifyResult(result)); } binningOptionsValues = root.getChild(BINNING_ELEMENT_NAME); } public Element getBinningOptionsValues() { return binningOptionsValues; } public void setBinningOptionsValues(Element binningOptionsValues) { this.binningOptionsValues = binningOptionsValues; } }
3e0ca3567639ad3ceae994a23a34e9c66a3029c8
1,837
java
Java
samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java
lucassales2/swagger-codegen
0bf7926a5eee9394e1aac564374db5efc2324852
[ "Apache-2.0" ]
14,570
2015-01-01T21:46:46.000Z
2022-03-31T22:28:15.000Z
samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java
lucassales2/swagger-codegen
0bf7926a5eee9394e1aac564374db5efc2324852
[ "Apache-2.0" ]
9,058
2015-01-08T15:49:17.000Z
2022-03-31T13:10:01.000Z
samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/Tag.java
lucassales2/swagger-codegen
0bf7926a5eee9394e1aac564374db5efc2324852
[ "Apache-2.0" ]
6,907
2015-01-02T05:29:47.000Z
2022-03-31T00:55:45.000Z
18.938144
75
0.606424
5,354
package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; public class Tag { @JsonProperty("id") private Long id = null; @JsonProperty("name") private String name = null; /** **/ public Tag id(Long id) { this.id = id; return this; } @ApiModelProperty(value = "") @JsonProperty("id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } /** **/ public Tag name(String name) { this.name = name; return this; } @ApiModelProperty(value = "") @JsonProperty("name") public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Tag tag = (Tag) o; return Objects.equals(id, tag.id) && Objects.equals(name, tag.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
3e0ca44b31218ad8ae7d245717c26df5e333ca89
407
java
Java
gulimall-wms/src/main/java/com/atguigu/gulimall/wms/dao/WareOrderTaskDetailDao.java
xiaoyumen/gulimall
c6ba2ff89d6333d9f088b4ac7312fa133c78587c
[ "Apache-2.0" ]
2
2019-08-01T10:00:50.000Z
2019-08-01T10:00:52.000Z
gulimall-wms/src/main/java/com/atguigu/gulimall/wms/dao/WareOrderTaskDetailDao.java
xiaoyumen/-
c6ba2ff89d6333d9f088b4ac7312fa133c78587c
[ "Apache-2.0" ]
5
2021-04-22T16:53:35.000Z
2021-09-20T20:50:59.000Z
gulimall-wms/src/main/java/com/atguigu/gulimall/wms/dao/WareOrderTaskDetailDao.java
xiaoyumen/gulimall
c6ba2ff89d6333d9f088b4ac7312fa133c78587c
[ "Apache-2.0" ]
null
null
null
22.444444
87
0.782178
5,355
package com.atguigu.gulimall.wms.dao; import com.atguigu.gulimall.wms.entity.WareOrderTaskDetailEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * ๅบ“ๅญ˜ๅทฅไฝœๅ• * * @author xieweiquan * @email lyhxr@example.com * @date 2019-08-01 19:46:54 */ @Mapper public interface WareOrderTaskDetailDao extends BaseMapper<WareOrderTaskDetailEntity> { }
3e0ca4560a3a4fa2bf5f48405c48ae66e07c040e
1,348
java
Java
mybatis-04/src/test/java/org/example/dao/UserMapperTest.java
ouyangjunfei/MyBatisStudy
d0c478ec712c3ee62fb5256a798adfe13b09f596
[ "Apache-2.0" ]
null
null
null
mybatis-04/src/test/java/org/example/dao/UserMapperTest.java
ouyangjunfei/MyBatisStudy
d0c478ec712c3ee62fb5256a798adfe13b09f596
[ "Apache-2.0" ]
null
null
null
mybatis-04/src/test/java/org/example/dao/UserMapperTest.java
ouyangjunfei/MyBatisStudy
d0c478ec712c3ee62fb5256a798adfe13b09f596
[ "Apache-2.0" ]
null
null
null
28.680851
75
0.627596
5,356
package org.example.dao; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import org.example.pojo.User; import org.example.utils.MyBatisUtils; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; public class UserMapperTest { static Logger logger = Logger.getLogger(UserMapperTest.class); @Test public void getUserByIdTest() { try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.getUserById(3); System.out.println(user); } } @Test public void testLog4j() { logger.info("่ฟ™ๆ˜ฏINFO็ญ‰็บง"); logger.warn("่ฟ™ๆ˜ฏWARN็ญ‰็บง"); logger.debug("่ฟ™ๆ˜ฏDEBUG็ญ‰็บง"); logger.error("่ฟ™ๆ˜ฏERROR็ญ‰็บง"); } @Test public void getUserByLimitTest() { try (SqlSession sqlSession = MyBatisUtils.getSqlSession()) { UserMapper userMapper = sqlSession.getMapper(UserMapper.class); Map<String, Object> map = new HashMap<>(); map.put("startIndex", 0); map.put("offset", 2); List<User> userList = userMapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } } } }
3e0ca4cfff334c884988a79bf36a07de3844605e
25,124
java
Java
phenomatch.core/src/main/java/genomicregions/CNV.java
ibn-salem/position_effect
8d6d916c769177774e6c65c854a8031a2563fb76
[ "MIT" ]
null
null
null
phenomatch.core/src/main/java/genomicregions/CNV.java
ibn-salem/position_effect
8d6d916c769177774e6c65c854a8031a2563fb76
[ "MIT" ]
5
2017-08-10T21:51:34.000Z
2021-11-06T17:39:50.000Z
phenomatch.core/src/main/java/genomicregions/CNV.java
ibn-salem/position_effect
8d6d916c769177774e6c65c854a8031a2563fb76
[ "MIT" ]
1
2017-08-10T13:34:39.000Z
2017-08-10T13:34:39.000Z
38.306402
179
0.630666
5,357
/* * Copyright (c) 2014, Jonas Ibn-Salem <anpch@example.com> * 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. * * 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package genomicregions; import annotation.AnnotateCNVs; import io.Utils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import ontologizer.go.Term; import org.apache.commons.lang3.StringUtils; // provides a join(iterable, char) function import phenotypeontology.PhenotypeData; import phenotypeontology.TermPair; /** * This class implements a copy number variation (CNV) object. The CNV has a * defined type and location in a reference genome. Furthermore it is associated to * phenotypes observed in the patient that carries the CNV. Several members of * this object can be used to annotate the CNV with respect to other genomic * elements and potential effect mechanisms. * * @author jonas */ public class CNV extends GenomicElement { /** * Type of CNV ("loss", "gain", "inversion"). This field can be later used to indicate * more complex structural variations. */ private final String type; /** * Phenotype terms of the CNV carrier as {@link HashSet} of {@link Term} objects. */ private final HashSet<Term> phenotypes; /** Target term or phenotype category as single general HPO term ID. */ private final Term targetTerm; /** List of overlapping boundaries. */ private GenomicSet<GenomicElement> boundaryOverlap; /** List of overlapping genes (any overlap) */ private GenomicSet<Gene> genesInOverlap; /** List of overlapping genes in overlapping TADs */ private GenomicSet<Gene> genesInOverlapTADs; /** Adjacent genomic region on the left (5') site of the CNV. */ private GenomicElement leftAdjacentRegion; /** Adjacent genomic region on the right (3') site of the CNV. */ private GenomicElement rightAdjacentRegion; /** {@link GenomicSet} of {@link Genes} in the left adjacent region of this CNV. */ private GenomicSet<Gene> genesInLeftRegion; /** {@link GenomicSet} of {@link Genes} in the right adjacent region of this CNV. */ private GenomicSet<Gene> genesInRightRegion; /** {@link GenomicSet} of enhancers in the left adjacent region of this CVN. */ private GenomicSet<GenomicElement> enhancersInLeftRegion; /** {@link GenomicSet} of enhancers in the right adjacent region of this CVN. */ private GenomicSet<GenomicElement> enhancersInRightRegion; /** Overlapped genomic region in the domain overlapping the 3' end of the CNV */ private GenomicElement leftOverlappedDomainRegion; /** Overlapped genomic region in the domain overlapping the 5' end of the CNV */ private GenomicElement rightOverlappedDomainRegion; /** Phenogram score of all genes overlapped by the CNV. */ private Double overlapPhenogramScore; /** Phenogram score of genes in the left adjacent region. */ private Double leftAdjacentPhenogramScore; /** Phenogram score of genes in the right adjacent region. */ private Double rightAdjacentPhenogramScore; /** * Constructor for CNV object. * Construct a {@link GenomicElement} and sets all {@link CNV} specific * annotations to default values. * * @param chr Chromosome identifier * @param start Start coordinate (0-based) * @param end End coordinate (0-based, half-open) * @param name Name or ID of the CNV * @param type CNV type (e.g. loss or gain) * * @throws IllegalArgumentException */ public CNV(String chr, int start, int end, String name, String type) throws IllegalArgumentException { super(chr, start, end, name); this.overlapPhenogramScore = -1.0; this.genesInOverlap = new GenomicSet(); this.boundaryOverlap = new GenomicSet(); // set default values for annotations this.type = type; this.phenotypes = new HashSet<Term>(); this.targetTerm = null; this.boundaryOverlap = new GenomicSet<GenomicElement>(); this.genesInOverlap = new GenomicSet<Gene>(); this.overlapPhenogramScore = -1.0; this.genesInLeftRegion = new GenomicSet<Gene>(); this.leftAdjacentPhenogramScore = -1.0; this.genesInRightRegion = new GenomicSet<Gene>(); this.rightAdjacentPhenogramScore = -1.0; this.enhancersInLeftRegion = new GenomicSet<GenomicElement>(); this.enhancersInRightRegion = new GenomicSet<GenomicElement>(); } /** * Constructor for {@link CNV} object. * Construct an CNV object by taking only chr, start, end, name, and * phenotypes as arguments. * * @param chr Chromosome identifier * @param start Start coordinate (0-based) * @param end End coordinate (0-based, half-open) * @param name Name or ID of the CNV * @param phenotypes List of HPO term IDs that represent the phenotypes used to annotate the patient carrying the CNV. */ public CNV(String chr, int start, int end, String name, HashSet<Term> phenotypes){ // consturct an CVN object using the constructor of the {@link GenomicElement} super calss super(chr, start, end, name); this.overlapPhenogramScore = -1.0; this.genesInOverlap = new GenomicSet(); this.boundaryOverlap = new GenomicSet(); // add annotations this.type = null; this.phenotypes = phenotypes; this.targetTerm = null; // set default annotaton for other fealds this.boundaryOverlap = new GenomicSet<GenomicElement>(); this.genesInOverlap = new GenomicSet<Gene>(); this.genesInOverlapTADs = new GenomicSet<Gene>(); this.overlapPhenogramScore = -1.0; this.genesInLeftRegion = new GenomicSet<Gene>(); this.leftAdjacentPhenogramScore = -1.0; this.genesInRightRegion = new GenomicSet<Gene>(); this.rightAdjacentPhenogramScore = -1.0; this.enhancersInLeftRegion = new GenomicSet<GenomicElement>(); this.enhancersInRightRegion = new GenomicSet<GenomicElement>(); } /** * Constructor for {@link CNV} object. * Construct an CNV object by taking all annotations as arguments. * * @param chr Chromosome identifier * @param start Start coordinate (0-based) * @param end End coordinate (0-based, half-open) * @param name Name or ID of the CNV * @param type CNV type (loss or gain) * @param phenotypes List of HPO term IDs that represent the phenotypes used to annotate the patient carrying the CNV. * @param targetTerm A unspecific target term as a HPO term ID that is used to group patients in cohort or associate patients to tissues for which enhancer data his available. */ public CNV(String chr, int start, int end, String name, String type, HashSet<Term> phenotypes, Term targetTerm){ // consturct an CVN object using the constructor of the {@link GenomicElement} super calss super(chr, start, end, name); this.overlapPhenogramScore = -1.0; this.genesInOverlap = new GenomicSet(); this.boundaryOverlap = new GenomicSet(); // add annotations this.type = type; this.phenotypes = phenotypes; this.targetTerm = targetTerm; // set default annotaton for other fealds this.boundaryOverlap = new GenomicSet<GenomicElement>(); this.genesInOverlap = new GenomicSet<Gene>(); this.genesInOverlapTADs = new GenomicSet<Gene>(); this.overlapPhenogramScore = -1.0; this.genesInLeftRegion = new GenomicSet<Gene>(); this.leftAdjacentPhenogramScore = -1.0; this.genesInRightRegion = new GenomicSet<Gene>(); this.rightAdjacentPhenogramScore = -1.0; this.enhancersInLeftRegion = new GenomicSet<GenomicElement>(); this.enhancersInRightRegion = new GenomicSet<GenomicElement>(); } /** * This function constructs a ArrayList of {@link String} that represents * output lines for each gene overlapped by this CNV. * * @param phenotypeData a {@link PhenotypeData} object to calculate phenoMatch scores * @param genes set of genes to consider * @return a TAB-separated output line to write BED like files. */ public ArrayList<String> getOverlappedGenesOutputLine(PhenotypeData phenotypeData, GenomicSet<Gene> genes){ ArrayList<String> outLines = new ArrayList<>(); //convert phenotpye terms to Strings HashSet<String> phenotypesIDs = new HashSet<>(); for (Term t : this.phenotypes){ phenotypesIDs.add(t.getIDAsString()); } // For columns with multiple elements, separate them by semiclon ';' String phenotypeCol = StringUtils.join(phenotypesIDs, ';'); // initialize maximal score per CNV Double maxScore = 0.0; // if CNV does overlap any gene add output line for each gene with score > 0 if (!genes.isEmpty() ){ for (Gene g : genes.values()){ String geneSymbol = g.getSymbol(); //double geneScore = phenotypeData.phenoMatchScore(this.phenotypes, g); ArrayList<TermPair> termMatching = phenotypeData.phenoMatchScoreWithMatching(this.phenotypes, g); double maxGeneScore = 0.0; double sumGeneScore = 0.0; String maxPatientMatchTerms = ""; String maxGeneMatchTerms = ""; String maxLca = ""; if(termMatching.size() > 0){ TermPair maxPair = Collections.max(termMatching, TermPair.TERM_PAIR_SCORE_ORDER); maxGeneScore = maxPair.getS(); for (TermPair tp: termMatching){ sumGeneScore += tp.getS(); } maxPatientMatchTerms = maxPair.getPp().getIDAsString(); maxGeneMatchTerms = maxPair.getGp().getIDAsString(); maxLca = maxPair.getLca().getIDAsString(); } String sumScoreStr = Utils.roundToString(sumGeneScore); String maxScoreStr = Utils.roundToString(maxGeneScore); // only if there is a score larger than zero output the gene if (maxGeneScore > 0){ String allPatientMatchTerms = ""; String allGeneMatchTerms = ""; String allLca = ""; String allMatchScores = ""; String sep = ""; for (TermPair tp: termMatching){ if (allPatientMatchTerms.length() > 0){ sep=";"; } allPatientMatchTerms += sep + tp.getPp().getIDAsString(); allGeneMatchTerms += sep + tp.getGp().getIDAsString(); allLca += sep + tp.getLca().getIDAsString(); allMatchScores += sep + Utils.roundToString(tp.getS()); } String [] cnvAnnotations = new String[]{ phenotypeCol, geneSymbol, sumScoreStr, maxScoreStr, maxPatientMatchTerms, maxGeneMatchTerms, maxLca, allPatientMatchTerms, allGeneMatchTerms, allLca, allMatchScores }; // put togeter all annotation string separated by TAB String outLineGene = super.toOutputLine() + "\t" + StringUtils.join(cnvAnnotations, '\t'); // append to output lines outLines.add(outLineGene); // upate maxScore if (maxGeneScore > maxScore){ maxScore = maxGeneScore; } } } } // if CNV does not overlap any gene or overlapped genes have score 0 if( maxScore == 0.0){ String outLineCNV = super.toOutputLine() + "\t" + StringUtils.join(new String[]{ phenotypeCol, ".", Utils.roundToString(0.0), Utils.roundToString(0.0), ".", ".", ".", ".", ".", ".", Utils.roundToString(0.0) }, '\t'); // append to output lines outLines.add(outLineCNV); } return outLines; } /** * Type of CNV ("loss", "gain" or "inversion"). This field can be later used to indicate * more complex structural variations. * * @return the type */ public String getType() { return type; } /** * Phenotype terms of the {@link CNV} carrier as {@link HashSet} of {@link Term} objects. * @return */ public HashSet<Term> getPhenotypes() { return this.phenotypes; } /** * Target term or phenotype category as single general HPO term ID * @return the targetTerm */ public Term getTargetTerm() { return this.targetTerm; } /** * {@link GenomicSet} of overlapping boundaries. * @return the boundaryOverlap */ public GenomicSet<GenomicElement> getBoundaryOverlap() { return boundaryOverlap; } /** * {@link GenomicSet} of overlapping boundaries. * @param boundaryOverlap the boundaryOverlap to set */ public void setBoundaryOverlap(GenomicSet<GenomicElement> boundaryOverlap) { this.boundaryOverlap = boundaryOverlap; } /** * Should be {@code true} if CNV overlaps a boundary element. * @return the hasBoundaryOverlap */ public boolean hasBoundaryOverlap() { return ! boundaryOverlap.isEmpty(); } /** * {@link GenomicSet} of overlapping {@link Gene}s (any overlap) * @return the genesInOverlap */ public GenomicSet<Gene> getGenesInOverlap() { return genesInOverlap; } /** * {@link GenomicSet} of overlapping {@link Gene}s (any overlap) * @param genesInOverlap the genesInOverlap to set */ public void setGenesInOverlap(GenomicSet<Gene> genesInOverlap) { this.genesInOverlap = genesInOverlap; } /** * {@link GenomicSet} of {@link Gene}s overlapping TADs that overlap the CNV. * @return */ public GenomicSet<Gene> getGenesInOverlapTADs() { return genesInOverlapTADs; } /** * {@link GenomicSet} of {@link Gene}s overlapping TADs that overlap the CNV. * @param genesInOverlapTADs */ public void setGenesInOverlapTADs(GenomicSet<Gene> genesInOverlapTADs) { this.genesInOverlapTADs = genesInOverlapTADs; } /** * Phenogram score of all genes overlapped by the CNV. * @return the overlapPhenogramScore */ public Double getOverlapPhenogramScore() { return overlapPhenogramScore; } /** * Phenogram score of all genes overlapped by the CNV. * @param overlapPhenogramScore the overlapPhenogramScore to set */ public void setOverlapPhenogramScore(Double overlapPhenogramScore) { this.overlapPhenogramScore = overlapPhenogramScore; } /** * Add a phenotype {@link Term} to the set of {@Term}s. * This method is just for creating artificial CNV objects for testing. * @param t */ public void addPhenotypeTerm(Term t) { this.phenotypes.add(t); } /** * Adjacent genomic region on the left (5') site of the CNV. * @return the leftAdjacentRegion */ public GenomicElement getLeftAdjacentRegion() { return leftAdjacentRegion; } /** * Adjacent genomic region on the left (5') site of the CNV. * @param leftAdjacentRegion the leftAdjacentRegion to set */ public void setLeftAdjacentRegion(GenomicElement leftAdjacentRegion) { this.leftAdjacentRegion = leftAdjacentRegion; } /** * Adjacent genomic region on the right (3') site of the CNV. * @return the rightAdjacentRegion */ public GenomicElement getRightAdjacentRegion() { return rightAdjacentRegion; } /** * Adjacent genomic region on the right (3') site of the CNV. * @param rightAdjacentRegion the rightAdjacentRegion to set */ public void setRightAdjacentRegion(GenomicElement rightAdjacentRegion) { this.rightAdjacentRegion = rightAdjacentRegion; } /** * Phenogram score of genes in the left adjacent region. * @return the leftAdjacentPhenogramScore */ public Double getLeftAdjacentPhenogramScore() { return leftAdjacentPhenogramScore; } /** * Phenogram score of genes in the left adjacent region. * @param leftAdjacentPhenogramScore the leftAdjacentPhenogramScore to set */ public void setLeftAdjacentPhenogramScore(Double leftAdjacentPhenogramScore) { this.leftAdjacentPhenogramScore = leftAdjacentPhenogramScore; } /** * Phenogram score of genes in the right adjacent region. * @return the rightAdjacentPhenogramScore */ public Double getRightAdjacentPhenogramScore() { return rightAdjacentPhenogramScore; } /** * Phenogram score of genes in the right adjacent region. * @param rightAdjacentPhenogramScore the rightAdjacentPhenogramScore to set */ public void setRightAdjacentPhenogramScore(Double rightAdjacentPhenogramScore) { this.rightAdjacentPhenogramScore = rightAdjacentPhenogramScore; } /** * {@link GenomicSet} of {@link Genes} in the left adjacent region of this CNV. * @return the genesInLeftRegion */ public GenomicSet<Gene> getGenesInLeftRegion() { return genesInLeftRegion; } /** * {@link GenomicSet} of {@link Genes} in the left adjacent region of this CNV. * @param genesInLeftRegion the genesInLeftRegion to set */ public void setGenesInLeftRegion(GenomicSet<Gene> genesInLeftRegion) { this.genesInLeftRegion = genesInLeftRegion; } /** * {@link GenomicSet} of {@link Genes} in the right adjacent region of this CNV. * @return the genesInRightRegion */ public GenomicSet<Gene> getGenesInRightRegion() { return genesInRightRegion; } /** * {@link GenomicSet} of {@link Genes} in the right adjacent region of this CNV. * @param genesInRightRegion the genesInRightRegion to set */ public void setGenesInRightRegion(GenomicSet<Gene> genesInRightRegion) { this.genesInRightRegion = genesInRightRegion; } /** * {@link GenomicSet} of enhancers in the left adjacent region of this CVN. * @return the enhancersInLeftRegion */ public GenomicSet<GenomicElement> getEnhancersInLeftRegion() { return enhancersInLeftRegion; } /** * {@link GenomicSet} of enhancers in the left adjacent region of this CVN. * @param enhancersInLeftRegion the enhancersInLeftRegion to set */ public void setEnhancersInLeftRegion(GenomicSet<GenomicElement> enhancersInLeftRegion) { this.enhancersInLeftRegion = enhancersInLeftRegion; } /** * {@link GenomicSet} of enhancers in the right adjacent region of this CVN. * @return the enhancersInRightRegion */ public GenomicSet<GenomicElement> getEnhancersInRightRegion() { return enhancersInRightRegion; } /** * {@link GenomicSet} of enhancers in the right adjacent region of this CVN. * @param enhancersInRightRegion the enhancersInRightRegion to set */ public void setEnhancersInRightRegion(GenomicSet<GenomicElement> enhancersInRightRegion) { this.enhancersInRightRegion = enhancersInRightRegion; } /** * Overlapped genomic region in the domain overlapping the 3' end of the CNV * @return the leftOverlappedDomainRegion * @see AnnotateCNVs.defineOverlappedDomainRegions */ public GenomicElement getLeftOverlappedDomainRegion() { return leftOverlappedDomainRegion; } /** * Overlapped genomic region in the domain overlapping the 3' end of the CNV * @param leftOverlappedDomainRegion the leftOverlappedDomainRegion to set * @see AnnotateCNVs.defineOverlappedDomainRegions */ public void setLeftOverlappedDomainRegion(GenomicElement leftOverlappedDomainRegion) { this.leftOverlappedDomainRegion = leftOverlappedDomainRegion; } /** * Overlapped genomic region in the domain overlapping the 5' end of the CNV * @return the rightOverlappedDomainRegion * @see AnnotateCNVs.defineOverlappedDomainRegions */ public GenomicElement getRightOverlappedDomainRegion() { return rightOverlappedDomainRegion; } /** * Overlapped genomic region in the domain overlapping the 5' end of the CNV * @param rightOverlappedDomainRegion the rightOverlappedDomainRegion to set * @see AnnotateCNVs.defineOverlappedDomainRegions */ public void setRightOverlappedDomainRegion(GenomicElement rightOverlappedDomainRegion) { this.rightOverlappedDomainRegion = rightOverlappedDomainRegion; } public void debugPrint(){ System.out.println("DEBUG CNV: " + this.toString()); System.out.println("DEBUG CNV type " + this.type); System.out.println("DEBUG CNV phenotype: " + this.phenotypes); System.out.println("DEBUG CNV targetTerm: " + this.targetTerm); System.out.println("DEBUG CNV boundaryOverlap: " + this.boundaryOverlap); System.out.println("DEBUG CNV genesInOverlap: " + this.genesInOverlap); System.out.println("DEBUG CNV overlapPhenogramScore: " + this.overlapPhenogramScore); System.out.println("DEBUG CNV leftAdjacentRegion: " + this.leftAdjacentRegion); System.out.println("DEBUG CNV enhancersInLeftRegion: " + this.enhancersInLeftRegion); System.out.println("DEBUG CNV genesInLeftRegion: " + this.genesInLeftRegion); System.out.println("DEBUG CNV leftAdjacentPhenogramScore: " + this.leftAdjacentPhenogramScore); System.out.println("DEBUG CNV rightAdjacentRegion: " + this.rightAdjacentRegion); System.out.println("DEBUG CNV enhancersInRightRegion: " + this.enhancersInRightRegion); System.out.println("DEBUG CNV genesInRightRegion: " + this.genesInRightRegion); System.out.println("DEBUG CNV rightAdjacentPhenogramScore: " + this.rightAdjacentPhenogramScore); System.out.println("DEBUG CNV leftOverlappedDomainRegion: " + this.leftOverlappedDomainRegion); System.out.println("DEBUG CNV rightOverlappedDomainRegion: " + this.rightOverlappedDomainRegion); } }
3e0ca4def92b56929ccb399361b833708f6e3f7d
1,993
java
Java
core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsGuavaPositiveCase.java
gururajrkatti/error-prone
00bf001c2c698f0e618dbcb39eeb76ddb9132a8a
[ "Apache-2.0" ]
6
2020-07-26T18:24:07.000Z
2022-01-21T07:17:42.000Z
core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsGuavaPositiveCase.java
gururajrkatti/error-prone
00bf001c2c698f0e618dbcb39eeb76ddb9132a8a
[ "Apache-2.0" ]
44
2022-01-13T23:27:31.000Z
2022-03-21T16:15:56.000Z
core/src/test/java/com/google/errorprone/bugpatterns/testdata/SelfEqualsGuavaPositiveCase.java
Oleksandr82/error-prone
804cdbdf40ffb8ed093d7be49567db33af3d38d6
[ "Apache-2.0" ]
1
2021-11-25T18:35:50.000Z
2021-11-25T18:35:50.000Z
31.68254
86
0.703908
5,358
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.testdata; import com.google.common.base.Objects; /** @author envkt@example.com (Alex Eagle) */ public class SelfEqualsGuavaPositiveCase { private String field = ""; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SelfEqualsGuavaPositiveCase other = (SelfEqualsGuavaPositiveCase) o; boolean retVal; // BUG: Diagnostic contains: Objects.equal(field, other.field) retVal = Objects.equal(field, field); // BUG: Diagnostic contains: Objects.equal(other.field, this.field) retVal &= Objects.equal(field, this.field); // BUG: Diagnostic contains: Objects.equal(this.field, other.field) retVal &= Objects.equal(this.field, field); // BUG: Diagnostic contains: Objects.equal(this.field, other.field) retVal &= Objects.equal(this.field, this.field); return retVal; } @Override public int hashCode() { return Objects.hashCode(field); } public static void test() { ForTesting tester = new ForTesting(); // BUG: Diagnostic contains: Objects.equal(tester.testing.testing, tester.testing) Objects.equal(tester.testing.testing, tester.testing.testing); } private static class ForTesting { public ForTesting testing; public String string; } }
3e0ca4f902893f1acd380bd54ded1279901cbf67
799
java
Java
app/to/StaffAssignment.java
SamirPT/blackMCVE
d14aa1264cfd0729c44ecca7eda57e62b6ecdd88
[ "Apache-2.0" ]
null
null
null
app/to/StaffAssignment.java
SamirPT/blackMCVE
d14aa1264cfd0729c44ecca7eda57e62b6ecdd88
[ "Apache-2.0" ]
null
null
null
app/to/StaffAssignment.java
SamirPT/blackMCVE
d14aa1264cfd0729c44ecca7eda57e62b6ecdd88
[ "Apache-2.0" ]
null
null
null
18.581395
77
0.717146
5,359
package to; import models.ReservationUser; import models.VenueRole; /** * Created by arkady on 17/05/16. */ public class StaffAssignment extends SearchUserInfo { private VenueRole role; private String userpic; public StaffAssignment() { } public StaffAssignment(ReservationUser assignment) { super(assignment.getUser()); this.role = assignment.getPk().getRole(); this.userpic = assignment.getUser().getUserpic(); } public StaffAssignment(Long id, String name, String phone, VenueRole role) { super(id, name, phone); this.role = role; } public VenueRole getRole() { return role; } public void setRole(VenueRole role) { this.role = role; } public String getUserpic() { return userpic; } public void setUserpic(String userpic) { this.userpic = userpic; } }
3e0ca516511672358627aec06dcdad80d12427a7
2,505
java
Java
client-api/src/main/java/com/streamsets/datacollector/client/ApiException.java
iamontheinet/datacollector-oss
a4cb45967a65f51ff825be32a0795354ebe14eff
[ "Apache-2.0" ]
34
2021-05-07T11:19:23.000Z
2022-01-18T11:46:01.000Z
client-api/src/main/java/com/streamsets/datacollector/client/ApiException.java
iamontheinet/datacollector-oss
a4cb45967a65f51ff825be32a0795354ebe14eff
[ "Apache-2.0" ]
13
2022-01-21T23:49:56.000Z
2022-01-21T23:50:08.000Z
client-api/src/main/java/com/streamsets/datacollector/client/ApiException.java
iamontheinet/datacollector-oss
a4cb45967a65f51ff825be32a0795354ebe14eff
[ "Apache-2.0" ]
48
2021-05-10T20:56:26.000Z
2022-03-17T06:28:58.000Z
30.180723
139
0.73014
5,360
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.datacollector.client; import javax.ws.rs.core.MultivaluedMap; public class ApiException extends Exception { private int code = 0; private MultivaluedMap<String, Object> responseHeaders = null; private String responseBody = null; public ApiException() {} public ApiException(Throwable throwable) { super(throwable); } public ApiException(String message) { super(message); } public ApiException(String message, Throwable throwable, int code, MultivaluedMap<String, Object> responseHeaders, String responseBody) { super(message, throwable); this.code = code; this.responseHeaders = responseHeaders; this.responseBody = responseBody; } public ApiException(String message, int code, MultivaluedMap<String, Object> responseHeaders, String responseBody) { this(message, (Throwable) null, code, responseHeaders, responseBody); } public ApiException(String message, Throwable throwable, int code, MultivaluedMap<String, Object> responseHeaders) { this(message, throwable, code, responseHeaders, null); } public ApiException(int code, MultivaluedMap<String, Object> responseHeaders, String responseBody) { this((String) null, (Throwable) null, code, responseHeaders, responseBody); } public ApiException(int code, String message) { super(message); this.code = code; } public ApiException(int code, String message, MultivaluedMap<String, Object> responseHeaders, String responseBody) { this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } public int getCode() { return code; } /** * Get the HTTP response headers. */ public MultivaluedMap<String, Object> getResponseHeaders() { return responseHeaders; } /** * Get the HTTP response body. */ public String getResponseBody() { return responseBody; } }
3e0ca6f1ade08884dd1813d8bb0938ad5adbc29a
2,009
java
Java
greens-manager/src/main/java/com/ytwman/greens/manager/model/param/UserInfoParam.java
ytwman/greens
ac032999c7436c6cb0e074c9ab8ea6cacb1ff1ab
[ "Apache-2.0" ]
null
null
null
greens-manager/src/main/java/com/ytwman/greens/manager/model/param/UserInfoParam.java
ytwman/greens
ac032999c7436c6cb0e074c9ab8ea6cacb1ff1ab
[ "Apache-2.0" ]
5
2021-03-22T23:31:05.000Z
2022-02-01T00:56:01.000Z
greens-manager/src/main/java/com/ytwman/greens/manager/model/param/UserInfoParam.java
ytwman/greens
ac032999c7436c6cb0e074c9ab8ea6cacb1ff1ab
[ "Apache-2.0" ]
null
null
null
19.891089
75
0.635142
5,361
/* * Copyright (C), 2014-2015, ๆญๅทžๅฐๅก็ง‘ๆŠ€ๆœ‰้™ๅ…ฌๅธ * Author: ๅฟฝๅฟฝ(huhu) * Date: 16/12/18 ไธ‹ๅˆ5:38 * Description: */ package com.ytwman.greens.manager.model.param; import com.ytwman.greens.commons.entity.UserInfoEntity; import com.ytwman.greens.manager.validation.DateRange; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.Date; /** * @author ๅฟฝๅฟฝ(huhu) * @see [็›ธๅ…ณ็ฑป/ๆ–นๆณ•]๏ผˆๅฏ้€‰๏ผ‰ * @since [ไบงๅ“/ๆจกๅ—็‰ˆๆœฌ] ๏ผˆๅฏ้€‰๏ผ‰ */ public class UserInfoParam extends UserInfoEntity implements Serializable { @NotEmpty(message = "ๆœชๅกซๅ†™ๅ็งฐ") private String name; @DateRange(min = "1920-01-01", message = "ๆ—ฅๆœŸๅคงไบŽๅฝ“ๅ‰ๆ—ถ้—ด") @NotNull(message = "ๆœชๅกซๅ†™ๅ‡บ็”Ÿๆ—ฅๆœŸ") private Date birthday; @NotNull(message = "ๆœช้€‰ๆ‹ฉๅŸŽๅธ‚") private Long regionId; @NotNull(message = "ๆœช้€‰ๆ‹ฉๅฐๅŒบ") private Long community; @NotEmpty(message = "ๆœชๅกซๅ†™ๅœฐๅ€") private String address; @NotEmpty(message = "ๆœชๅกซๅ†™ๆ‰‹ๆœบๅท็ ") private String phone; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public Date getBirthday() { return birthday; } @Override public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public Long getCommunity() { return community; } @Override public void setCommunity(Long community) { this.community = community; } @Override public String getAddress() { return address; } @Override public void setAddress(String address) { this.address = address; } @Override public String getPhone() { return phone; } @Override public void setPhone(String phone) { this.phone = phone; } public Long getRegionId() { return regionId; } public void setRegionId(Long regionId) { this.regionId = regionId; } }
3e0ca735038e3561b2ad28dbe3266ad070df1355
1,680
java
Java
spring-cloud-config-azure-keyvault-single-backend-sample/src/test/java/org/srempfer/config/keyvault/ConfigServerSampleApplicationIntegrationTest.java
apeloquin-agilysys/spring-cloud-config-azure-keyvault
5b29fca5fb9fe7e5d9eb9304ee11f764d5ca78c7
[ "MIT" ]
9
2020-05-09T04:21:49.000Z
2021-06-29T16:53:14.000Z
spring-cloud-config-azure-keyvault-single-backend-sample/src/test/java/org/srempfer/config/keyvault/ConfigServerSampleApplicationIntegrationTest.java
apeloquin-agilysys/spring-cloud-config-azure-keyvault
5b29fca5fb9fe7e5d9eb9304ee11f764d5ca78c7
[ "MIT" ]
106
2019-12-22T01:26:28.000Z
2022-03-25T04:08:44.000Z
spring-cloud-config-azure-keyvault-single-backend-sample/src/test/java/org/srempfer/config/keyvault/ConfigServerSampleApplicationIntegrationTest.java
apeloquin-agilysys/spring-cloud-config-azure-keyvault
5b29fca5fb9fe7e5d9eb9304ee11f764d5ca78c7
[ "MIT" ]
2
2020-11-19T09:36:40.000Z
2021-05-06T18:55:58.000Z
46.666667
106
0.752381
5,362
package org.srempfer.config.keyvault; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest ( classes = ConfigServerSampleApplication.class ) @AutoConfigureMockMvc class ConfigServerSampleApplicationIntegrationTest { @Autowired private MockMvc mockMvc; @Test void verifyPropertySources () throws Exception { mockMvc.perform ( get ( "/test-application/default/master" ) ) .andExpect ( status ().isOk () ) .andExpect ( content ().contentType ( MediaType.APPLICATION_JSON ) ) .andExpect ( jsonPath ( "$.propertySources" ).isArray () ) .andExpect ( jsonPath ( "$.propertySources", hasSize ( 1 ) ) ) .andExpect ( jsonPath ( "$.propertySources[0].name", is ( "keyvault-application-default" ) ) ) .andExpect ( jsonPath ( "$.propertySources[0].source", hasEntry ( "simplekey", "dummy" ) ) ); } }
3e0ca9099ffbb6a50c076dd8fd9f563098dfea20
6,838
java
Java
src/main/java/org/gwtproject/i18n/shared/cldr/impl/DateTimeFormatInfoImpl_wae.java
DominoKit/gwt-cldr
02f83dc7c3bba5786b06d3ac13641cf26bd448ab
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/org/gwtproject/i18n/shared/cldr/impl/DateTimeFormatInfoImpl_wae.java
DominoKit/gwt-cldr
02f83dc7c3bba5786b06d3ac13641cf26bd448ab
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/org/gwtproject/i18n/shared/cldr/impl/DateTimeFormatInfoImpl_wae.java
DominoKit/gwt-cldr
02f83dc7c3bba5786b06d3ac13641cf26bd448ab
[ "ECL-2.0", "Apache-2.0" ]
1
2021-04-23T15:06:34.000Z
2021-04-23T15:06:34.000Z
17.35533
80
0.582919
5,363
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.gwtproject.i18n.shared.cldr.impl; // DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA /** * Implementation of DateTimeFormatInfo for the "wae" locale. */ import org.gwtproject.i18n.shared.cldr.DateTimeFormatInfoImpl; public class DateTimeFormatInfoImpl_wae extends DateTimeFormatInfoImpl { @Override public String[] ampms() { return new String[] { "AM", "PM" }; } @Override public String dateFormat() { return dateFormatMedium(); } @Override public String dateFormatFull() { return "EEEE, d. MMMM y"; } @Override public String dateFormatLong() { return "d. MMMM y"; } @Override public String dateFormatMedium() { return "d. MMM y"; } @Override public String dateFormatShort() { return "y-MM-dd"; } @Override public String dateTime(String timePattern, String datePattern) { return dateTimeMedium(timePattern, datePattern); } @Override public String dateTimeFull(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String dateTimeLong(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String dateTimeMedium(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String dateTimeShort(String timePattern, String datePattern) { return datePattern + " " + timePattern; } @Override public String[] erasFull() { return new String[] { "v. Chr.", "n. Chr" }; } @Override public String[] erasShort() { return new String[] { "v. Chr.", "n. Chr" }; } @Override public int firstDayOfTheWeek() { return 1; } @Override public String formatDay() { return "d"; } @Override public String formatHour12Minute() { return "h:mm a"; } @Override public String formatHour12MinuteSecond() { return "h:mm:ss a"; } @Override public String formatHour24Minute() { return "HH:mm"; } @Override public String formatHour24MinuteSecond() { return "HH:mm:ss"; } @Override public String formatMinuteSecond() { return "mm:ss"; } @Override public String formatMonthAbbrev() { return "LLL"; } @Override public String formatMonthAbbrevDay() { return "d. MMM"; } @Override public String formatMonthFull() { return "LLLL"; } @Override public String formatMonthFullDay() { return "MMMM d"; } @Override public String formatMonthFullWeekdayDay() { return "EEEE, d. MMMM"; } @Override public String formatMonthNumDay() { return "d. MMM"; } @Override public String formatYear() { return "y"; } @Override public String formatYearMonthAbbrev() { return "MMM y"; } @Override public String formatYearMonthAbbrevDay() { return "d. MMM y"; } @Override public String formatYearMonthFull() { return "y MMMM"; } @Override public String formatYearMonthFullDay() { return "d. MMMM y"; } @Override public String formatYearMonthNum() { return "y-MM"; } @Override public String formatYearMonthNumDay() { return "y-M-d"; } @Override public String formatYearMonthWeekdayDay() { return "EEE, d. MMM y"; } @Override public String formatYearQuarterFull() { return "y QQQQ"; } @Override public String formatYearQuarterShort() { return "y Q"; } @Override public String[] monthsFull() { return new String[] { "Jenner", "Hornig", "Mรคrze", "Abrille", "Meije", "Brรกฤet", "Heiwet", "ร–igลกte", "Herbลกtmรกnet", "Wรญmรกnet", "Wintermรกnet", "Chriลกtmรกnet" }; } @Override public String[] monthsFullStandalone() { return monthsFull(); } @Override public String[] monthsNarrow() { return new String[] { "J", "H", "M", "A", "M", "B", "H", "ร–", "H", "W", "W", "C" }; } @Override public String[] monthsNarrowStandalone() { return monthsNarrow(); } @Override public String[] monthsShort() { return new String[] { "Jen", "Hor", "Mรคr", "Abr", "Mei", "Brรก", "Hei", "ร–ig", "Her", "Wรญm", "Win", "Chr" }; } @Override public String[] monthsShortStandalone() { return monthsShort(); } @Override public String[] quartersFull() { return new String[] { "1. quartal", "2. quartal", "3. quartal", "4. quartal" }; } @Override public String[] quartersShort() { return new String[] { "Q1", "Q2", "Q3", "Q4" }; } @Override public String timeFormat() { return timeFormatMedium(); } @Override public String timeFormatFull() { return "HH:mm:ss zzzz"; } @Override public String timeFormatLong() { return "HH:mm:ss z"; } @Override public String timeFormatMedium() { return "HH:mm:ss"; } @Override public String timeFormatShort() { return "HH:mm"; } @Override public String[] weekdaysFull() { return new String[] { "Sunntag", "Mรคntag", "Ziลกtag", "Mittwuฤ", "Frรณntag", "Fritag", "Samลกtag" }; } @Override public String[] weekdaysFullStandalone() { return weekdaysFull(); } @Override public String[] weekdaysNarrow() { return new String[] { "S", "M", "Z", "M", "F", "F", "S" }; } @Override public String[] weekdaysNarrowStandalone() { return weekdaysNarrow(); } @Override public String[] weekdaysShort() { return new String[] { "Sun", "Mรคn", "Ziลก", "Mit", "Frรณ", "Fri", "Sam" }; } @Override public String[] weekdaysShortStandalone() { return weekdaysShort(); } @Override public int weekendEnd() { return 0; } @Override public int weekendStart() { return 6; } }
3e0ca9966db987098c0827e56c3553b95f8e53da
456
java
Java
src/main/java/com/jiangzhe/service/BookService.java
chvrches625/ssmbuild
36c5f2b541028611c280dec36c455668fd19b0bb
[ "MIT" ]
null
null
null
src/main/java/com/jiangzhe/service/BookService.java
chvrches625/ssmbuild
36c5f2b541028611c280dec36c455668fd19b0bb
[ "MIT" ]
1
2022-03-31T22:32:35.000Z
2022-03-31T22:32:35.000Z
src/main/java/com/jiangzhe/service/BookService.java
chvrches625/ssmbuild
36c5f2b541028611c280dec36c455668fd19b0bb
[ "MIT" ]
null
null
null
16.285714
49
0.684211
5,364
package com.jiangzhe.service; import com.jiangzhe.pojo.Books; import org.apache.ibatis.annotations.Param; import java.util.List; public interface BookService { //ๅขžๅŠ ไธ€ๆœฌไนฆ int addBook(Books books); //ๅˆ ้™คไธ€ๆœฌไนฆ int deleteBookById(int id); //ๆ›ดๆ–ฐไธ€ๆœฌไนฆ int updateBook(Books books); //ๆŸฅ่ฏขไธ€ๆœฌไนฆ Books queryBookById(int id); //ๆŸฅ่ฏขๅ…จ้ƒจ็š„ไนฆ List<Books> queryAllBooks(); //้€š่ฟ‡ไนฆๅๆŸฅ่ฏข List<Books> queryBookByName(String bookName); }
3e0caa5a1176ce6c175546101260a564d1bc0df4
389
java
Java
src/main/java/com/xbblog/ipchecker/vo/ResultInsideVo.java
xbblog95/ipchecker
cef0d6fb890a7737b74c117555777f3f4e471d4a
[ "MIT" ]
1
2019-09-16T17:12:32.000Z
2019-09-16T17:12:32.000Z
src/main/java/com/xbblog/ipchecker/vo/ResultInsideVo.java
xbblog95/ipchecker
cef0d6fb890a7737b74c117555777f3f4e471d4a
[ "MIT" ]
null
null
null
src/main/java/com/xbblog/ipchecker/vo/ResultInsideVo.java
xbblog95/ipchecker
cef0d6fb890a7737b74c117555777f3f4e471d4a
[ "MIT" ]
3
2019-06-16T03:28:14.000Z
2019-08-12T10:05:24.000Z
15.56
42
0.598972
5,365
package com.xbblog.ipchecker.vo; public class ResultInsideVo { private Boolean tcp; private long tcptime; public Boolean getTcp() { return tcp; } public void setTcp(Boolean tcp) { this.tcp = tcp; } public long getTcptime() { return tcptime; } public void setTcptime(long tcptime) { this.tcptime = tcptime; } }
3e0caa9f9addca8924f25eb4f1f25dd12ac2a2f7
552
java
Java
src/main/java/com/melg/schoolapp/model/Record.java
mloayzagahona/schoolapp
be1155623ab2c450701244e2c9654f8b5fe182a6
[ "MIT" ]
null
null
null
src/main/java/com/melg/schoolapp/model/Record.java
mloayzagahona/schoolapp
be1155623ab2c450701244e2c9654f8b5fe182a6
[ "MIT" ]
null
null
null
src/main/java/com/melg/schoolapp/model/Record.java
mloayzagahona/schoolapp
be1155623ab2c450701244e2c9654f8b5fe182a6
[ "MIT" ]
null
null
null
26.285714
62
0.813406
5,366
package com.melg.schoolapp.model; import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Table; import org.springframework.lang.NonNull; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor @NoArgsConstructor @Table("RECORDS") public class Record extends Base { @Id private Long recordId; @NonNull private Long semesterId; @NonNull private Long subjectId; @NonNull private Long studentId; @NonNull private String grade; }
3e0caae13df522c81c8e3691958f893764e931ab
1,707
java
Java
doc/libjitisi/sources/org/jitsi/impl/neomedia/codec/audio/alaw/DePacketizer.java
lhzheng880828/VOIPCall
a7ba25debd4bd2086bae2a48306d28c614ce0d4a
[ "Apache-2.0" ]
null
null
null
doc/libjitisi/sources/org/jitsi/impl/neomedia/codec/audio/alaw/DePacketizer.java
lhzheng880828/VOIPCall
a7ba25debd4bd2086bae2a48306d28c614ce0d4a
[ "Apache-2.0" ]
null
null
null
doc/libjitisi/sources/org/jitsi/impl/neomedia/codec/audio/alaw/DePacketizer.java
lhzheng880828/VOIPCall
a7ba25debd4bd2086bae2a48306d28c614ce0d4a
[ "Apache-2.0" ]
null
null
null
31.036364
135
0.624487
5,367
package org.jitsi.impl.neomedia.codec.audio.alaw; import com.sun.media.codec.audio.AudioCodec; import javax.media.Buffer; import javax.media.Format; import javax.media.format.AudioFormat; import net.sf.fmj.media.BasicPlugIn; public class DePacketizer extends AudioCodec { public DePacketizer() { this.inputFormats = new Format[]{new AudioFormat("ALAW/rtp")}; } public String getName() { return "ALAW DePacketizer"; } public Format[] getSupportedOutputFormats(Format in) { if (in == null) { return new Format[]{new AudioFormat(AudioFormat.ALAW)}; } else if (BasicPlugIn.matches(in, this.inputFormats) == null) { return new Format[1]; } else { if (in instanceof AudioFormat) { AudioFormat af = (AudioFormat) in; return new Format[]{new AudioFormat(AudioFormat.ALAW, af.getSampleRate(), af.getSampleSizeInBits(), af.getChannels())}; } return new Format[]{new AudioFormat(AudioFormat.ALAW)}; } } public void open() { } public void close() { } public int process(Buffer inputBuffer, Buffer outputBuffer) { if (!checkInputBuffer(inputBuffer)) { return 1; } if (isEOM(inputBuffer)) { propagateEOM(outputBuffer); return 0; } Object outData = outputBuffer.getData(); outputBuffer.setData(inputBuffer.getData()); inputBuffer.setData(outData); outputBuffer.setLength(inputBuffer.getLength()); outputBuffer.setFormat(this.outputFormat); outputBuffer.setOffset(inputBuffer.getOffset()); return 0; } }
3e0caae223fbf50f9da121d4f7f4bea25bc167d7
8,005
java
Java
java-demo/src/main/java/com/example/DataSourcePool/ConnectionWrap.java
huruiyi/Java201808
a9f00e6f129aace29a50db4ba2da1e736372fa94
[ "Apache-2.0" ]
1
2020-09-27T02:40:43.000Z
2020-09-27T02:40:43.000Z
java-demo/src/main/java/com/example/DataSourcePool/ConnectionWrap.java
huruiyi/Java201808
a9f00e6f129aace29a50db4ba2da1e736372fa94
[ "Apache-2.0" ]
8
2020-07-15T08:52:04.000Z
2022-01-22T09:42:48.000Z
java-demo/src/main/java/com/example/DataSourcePool/ConnectionWrap.java
huruiyi/spring-samples
ed729af789519d53e29b0596902b80c75d21c161
[ "Apache-2.0" ]
null
null
null
22.360335
107
0.745409
5,368
package com.example.DataSourcePool; import java.sql.Array; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Clob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.SQLClientInfoException; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Savepoint; import java.sql.Statement; import java.sql.Struct; import java.util.LinkedList; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; //้€‚้…ๅ™จๆจกๅผ public class ConnectionWrap implements Connection { private Connection connection; private LinkedList<Connection> poollist; public ConnectionWrap(Connection connection) { this.connection = connection; } public ConnectionWrap(Connection connection, LinkedList<Connection> poollist) { this.connection = connection; this.poollist = poollist; } @Override public Statement createStatement() throws SQLException { return connection.createStatement(); } @Override public PreparedStatement prepareStatement(String arg0) throws SQLException { return connection.prepareStatement(arg0); } @Override public PreparedStatement prepareStatement(String arg0, int arg1) throws SQLException { return connection.prepareStatement(arg0, arg1); } @Override public PreparedStatement prepareStatement(String arg0, int[] arg1) throws SQLException { return connection.prepareStatement(arg0, arg1); } @Override public PreparedStatement prepareStatement(String arg0, String[] arg1) throws SQLException { return connection.prepareStatement(arg0, arg1); } @Override public PreparedStatement prepareStatement(String arg0, int arg1, int arg2) throws SQLException { return connection.prepareStatement(arg0, arg1, arg2); } @Override public PreparedStatement prepareStatement(String arg0, int arg1, int arg2, int arg3) throws SQLException { return connection.prepareStatement(arg0, arg1, arg2, arg3); } @Override public <T> T unwrap(Class<T> arg0) throws SQLException { return connection.unwrap(arg0); } // ่‡ชๅทฑๅฎž็Žฐ @Override public void close() throws SQLException { System.out.println("before: " + this.poollist.size()); poollist.addLast(this); System.out.println("after: " + this.poollist.size()); } ///////////////////////////////////////////////////////////////////////// @Override public boolean isWrapperFor(Class<?> arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public void abort(Executor arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void clearWarnings() throws SQLException { // TODO Auto-generated method stub } @Override public void commit() throws SQLException { // TODO Auto-generated method stub } @Override public Array createArrayOf(String arg0, Object[] arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Blob createBlob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Clob createClob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public NClob createNClob() throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLXML createSQLXML() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Statement createStatement(int arg0, int arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Statement createStatement(int arg0, int arg1, int arg2) throws SQLException { // TODO Auto-generated method stub return null; } @Override public Struct createStruct(String arg0, Object[] arg1) throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean getAutoCommit() throws SQLException { // TODO Auto-generated method stub return false; } @Override public String getCatalog() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Properties getClientInfo() throws SQLException { // TODO Auto-generated method stub return null; } @Override public String getClientInfo(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getHoldability() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public DatabaseMetaData getMetaData() throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getNetworkTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public String getSchema() throws SQLException { // TODO Auto-generated method stub return null; } @Override public int getTransactionIsolation() throws SQLException { // TODO Auto-generated method stub return 0; } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { // TODO Auto-generated method stub return null; } @Override public SQLWarning getWarnings() throws SQLException { // TODO Auto-generated method stub return null; } @Override public boolean isClosed() throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isReadOnly() throws SQLException { // TODO Auto-generated method stub return false; } @Override public boolean isValid(int arg0) throws SQLException { // TODO Auto-generated method stub return false; } @Override public String nativeSQL(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String arg0, int arg1, int arg2) throws SQLException { // TODO Auto-generated method stub return null; } @Override public CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void releaseSavepoint(Savepoint arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void rollback() throws SQLException { // TODO Auto-generated method stub } @Override public void rollback(Savepoint arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setAutoCommit(boolean arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setCatalog(String arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setClientInfo(Properties arg0) throws SQLClientInfoException { // TODO Auto-generated method stub } @Override public void setClientInfo(String arg0, String arg1) throws SQLClientInfoException { // TODO Auto-generated method stub } @Override public void setHoldability(int arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setNetworkTimeout(Executor arg0, int arg1) throws SQLException { // TODO Auto-generated method stub } @Override public void setReadOnly(boolean arg0) throws SQLException { // TODO Auto-generated method stub } @Override public Savepoint setSavepoint() throws SQLException { // TODO Auto-generated method stub return null; } @Override public Savepoint setSavepoint(String arg0) throws SQLException { // TODO Auto-generated method stub return null; } @Override public void setSchema(String arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setTransactionIsolation(int arg0) throws SQLException { // TODO Auto-generated method stub } @Override public void setTypeMap(Map<String, Class<?>> arg0) throws SQLException { // TODO Auto-generated method stub } }
3e0cab1cfe08b8307e444b5285e6a7099778402c
817
java
Java
app/src/main/java/com/yatatsu/passiveviewsample/ui/base/Controller.java
yatatsu/PassiveViewSample
8828176b5a31c0704b4abe40daebf8a38cc2e44b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yatatsu/passiveviewsample/ui/base/Controller.java
yatatsu/PassiveViewSample
8828176b5a31c0704b4abe40daebf8a38cc2e44b
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/yatatsu/passiveviewsample/ui/base/Controller.java
yatatsu/PassiveViewSample
8828176b5a31c0704b4abe40daebf8a38cc2e44b
[ "Apache-2.0" ]
null
null
null
24.029412
64
0.669523
5,369
package com.yatatsu.passiveviewsample.ui.base; import rx.Subscription; import rx.subscriptions.CompositeSubscription; public abstract class Controller<T extends Screen> { private T screen; private CompositeSubscription compositeSubscription; public void registerScreen(T screen) { this.screen = screen; } protected T getScreen() { return screen; } protected void register(Subscription subscription) { if (compositeSubscription == null) { compositeSubscription = new CompositeSubscription(); } compositeSubscription.add(subscription); } protected void unSubscribe() { if (compositeSubscription != null) { compositeSubscription.unsubscribe(); compositeSubscription = null; } } }
3e0cab5581673361a6e978556d9a26c42fe64b1b
207
java
Java
Merchant/src/main/java/com/yilianmall/merchant/listener/NotifyComboOrderListListener.java
LJW123/YiLianMall
ea335a66cb4fd6417aa264a959847b094c90fb04
[ "MIT" ]
null
null
null
Merchant/src/main/java/com/yilianmall/merchant/listener/NotifyComboOrderListListener.java
LJW123/YiLianMall
ea335a66cb4fd6417aa264a959847b094c90fb04
[ "MIT" ]
null
null
null
Merchant/src/main/java/com/yilianmall/merchant/listener/NotifyComboOrderListListener.java
LJW123/YiLianMall
ea335a66cb4fd6417aa264a959847b094c90fb04
[ "MIT" ]
null
null
null
20.7
69
0.763285
5,370
package com.yilianmall.merchant.listener; /** * Created by on 2017/8/19 0019. */ public interface NotifyComboOrderListListener { public void notifyComboOrderListItem(int position,int newStatus); }
3e0caca2c01cd65c1ac8451c1e058acdead67c38
639
java
Java
src/main/java/com/hyd/ssdb/util/KeyValue.java
iedwin/hydrogen-ssdb
dafe1af217f15afe2a4a121d737bcc9061460b04
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hyd/ssdb/util/KeyValue.java
iedwin/hydrogen-ssdb
dafe1af217f15afe2a4a121d737bcc9061460b04
[ "Apache-2.0" ]
null
null
null
src/main/java/com/hyd/ssdb/util/KeyValue.java
iedwin/hydrogen-ssdb
dafe1af217f15afe2a4a121d737bcc9061460b04
[ "Apache-2.0" ]
1
2021-01-14T07:24:54.000Z
2021-01-14T07:24:54.000Z
15.585366
55
0.543036
5,371
package com.hyd.ssdb.util; /** * ้”ฎๅ€ผๅฏน * created at 15-12-3 * * @author Yiding */ public class KeyValue { private String key; private String value; public KeyValue(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "{" + this.key + "=" + this.value + "}"; } }
3e0cad055104298e27d8b81fd19dcef291708ae9
3,767
java
Java
app/src/androidTest/java/org/stormroboticsnj/PrivacyPolicyTest.java
2729StormRobotics/StormAppMaster2020
f6a392e7f23d0a67fcc83d0dd7752bdd18e7628b
[ "Apache-2.0" ]
null
null
null
app/src/androidTest/java/org/stormroboticsnj/PrivacyPolicyTest.java
2729StormRobotics/StormAppMaster2020
f6a392e7f23d0a67fcc83d0dd7752bdd18e7628b
[ "Apache-2.0" ]
102
2020-02-08T23:46:52.000Z
2022-02-24T03:02:56.000Z
app/src/androidTest/java/org/stormroboticsnj/PrivacyPolicyTest.java
2729StormRobotics/StormAppMaster2020
f6a392e7f23d0a67fcc83d0dd7752bdd18e7628b
[ "Apache-2.0" ]
1
2021-02-27T00:55:37.000Z
2021-02-27T00:55:37.000Z
41.395604
168
0.615609
5,372
package org.stormroboticsnj; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import androidx.test.espresso.ViewInteraction; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.click; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withClassName; import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; @LargeTest @RunWith(AndroidJUnit4.class) public class PrivacyPolicyTest { @Rule public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class); @Test public void privacyPolicyTest() { ViewInteraction appCompatImageButton = onView( allOf(withContentDescription("Open navigation drawer"), childAtPosition( allOf(withId(R.id.toolbar), childAtPosition( withClassName(is("com.google.android.material.appbar.AppBarLayout")), 0)), 1), isDisplayed())); appCompatImageButton.perform(click()); ViewInteraction navigationMenuItemView = onView( allOf(childAtPosition( allOf(withId(R.id.design_navigation_view), childAtPosition( withId(R.id.navigationview), 0)), 6), isDisplayed())); navigationMenuItemView.perform(click()); ViewInteraction textView = onView( allOf(withId(R.id.privacytext), withText("Privacy Policy available at https://docs.google.com/document/d/1qYCvt0eGiPle1d9VVWu7vAZr5h4CDdzS16_cOC7WbFw"), childAtPosition( childAtPosition( withId(R.id.nav_host_fragment), 0), 0), isDisplayed())); textView.check(matches(withText("Privacy Policy available at https://docs.google.com/document/d/1qYCvt0eGiPle1d9VVWu7vAZr5h4CDdzS16_cOC7WbFw"))); } private static Matcher<View> childAtPosition( final Matcher<View> parentMatcher, final int position) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("Child at position " + position + " in parent "); parentMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { ViewParent parent = view.getParent(); return parent instanceof ViewGroup && parentMatcher.matches(parent) && view.equals(((ViewGroup) parent).getChildAt(position)); } }; } }
3e0cad0ab0ea6604b58047be17aa1dd348b5907b
3,130
java
Java
java/dagger/model/Binding.java
humayuntanwar/dagger
ff16ee59d5f4097ae4a685ef23185b142df33270
[ "Apache-2.0" ]
1
2019-02-13T16:35:31.000Z
2019-02-13T16:35:31.000Z
java/dagger/model/Binding.java
humayuntanwar/dagger
ff16ee59d5f4097ae4a685ef23185b142df33270
[ "Apache-2.0" ]
null
null
null
java/dagger/model/Binding.java
humayuntanwar/dagger
ff16ee59d5f4097ae4a685ef23185b142df33270
[ "Apache-2.0" ]
1
2019-09-23T11:50:02.000Z
2019-09-23T11:50:02.000Z
40.649351
100
0.73099
5,373
/* * Copyright (C) 2017 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.model; import com.google.common.collect.ImmutableSet; import java.util.Optional; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; /** * The association between a {@link Key} and the way in which instances of the key are provided. * Includes any {@linkplain DependencyRequest dependencies} that are needed in order to provide the * instances. */ public interface Binding { /** The binding's key. */ Key key(); /** * The dependencies of this binding. The order of the dependencies corresponds to the order in * which they will be injected when the binding is requested. */ ImmutableSet<DependencyRequest> dependencies(); /** * The {@link Element} that declares this binding. Absent for {@linkplain BindingKind binding * kinds} that are not always declared by exactly one element. * * <p>For example, consider {@link BindingKind#MULTIBOUND_SET}. A component with many * {@code @IntoSet} bindings for the same key will have a synthetic binding that depends on all * contributions, but with no identifiying binding element. A {@code @Multibinds} method will also * contribute a synthetic binding, but since multiple {@code @Multibinds} methods can coexist in * the same component (and contribute to one single binding), it has no binding element. */ // TODO(ronshapiro): examine whether this wildcard+bound have any benefit. In the processor code, // we never actually refer to the overridden bindingElement methods directly in a way which needs // anything more than an Element. Removing the wildcard would allow for simpler user-written code // when the binding element is passed to a method. Optional<? extends Element> bindingElement(); /** * The {@link TypeElement} of the module which contributes this binding. Absent for bindings that * have no {@link #bindingElement() binding element}. */ Optional<TypeElement> contributingModule(); /** The scope of this binding if it has one. */ Optional<Scope> scope(); /** * Returns {@code true} if this binding may provide {@code null} instead of an instance of {@link * #key()}. Nullable bindings cannot be requested from {@linkplain DependencyRequest#isNullable() * non-nullable dependency requests}. */ boolean isNullable(); /** Returns {@code true} if this is a production binding, e.g. an {@code @Produces} method. */ boolean isProduction(); /** The kind of binding this instance represents. */ BindingKind kind(); }
3e0cad7fdc24c06ae1ff92df01b705bb4a043309
1,826
java
Java
Minecraft/build/tmp/recompileMc/sources/net/minecraft/item/ItemFireball.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
22
2021-01-10T20:58:45.000Z
2021-12-19T18:11:35.000Z
Minecraft/build/tmp/recompileMc/sources/net/minecraft/item/ItemFireball.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
3
2021-01-10T20:59:19.000Z
2021-01-13T14:00:58.000Z
Minecraft/build/tmp/recompileMc/sources/net/minecraft/item/ItemFireball.java
QinxiWang/Mincraft-Agent-Learn-to-Fight-Zombies-and-Slimes
019deb0b37674289d077fb69800ee97e5fdb47d1
[ "MIT" ]
4
2020-12-20T02:10:44.000Z
2022-01-25T19:38:53.000Z
32.035088
185
0.621577
5,374
package net.minecraft.item; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ItemFireball extends Item { public ItemFireball() { this.setCreativeTab(CreativeTabs.MISC); } /** * Called when a Block is right-clicked with this Item */ public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { if (worldIn.isRemote) { return EnumActionResult.SUCCESS; } else { pos = pos.offset(facing); ItemStack itemstack = player.getHeldItem(hand); if (!player.canPlayerEdit(pos, facing, itemstack)) { return EnumActionResult.FAIL; } else { if (worldIn.getBlockState(pos).getMaterial() == Material.AIR) { worldIn.playSound((EntityPlayer)null, pos, SoundEvents.ITEM_FIRECHARGE_USE, SoundCategory.BLOCKS, 1.0F, (itemRand.nextFloat() - itemRand.nextFloat()) * 0.2F + 1.0F); worldIn.setBlockState(pos, Blocks.FIRE.getDefaultState()); } if (!player.capabilities.isCreativeMode) { itemstack.shrink(1); } return EnumActionResult.SUCCESS; } } } }
3e0cad8035ce7a3ae687d53b290442fb7ad6331a
2,134
java
Java
runtime/model/src/test/java/io/syndesis/integration/model/ModelUnmarshalTest.java
oscerd/syndesis
c6609d60e386ad487ffc1508502a158a691f0a73
[ "Apache-2.0" ]
1
2017-11-16T10:21:15.000Z
2017-11-16T10:21:15.000Z
runtime/model/src/test/java/io/syndesis/integration/model/ModelUnmarshalTest.java
oscerd/syndesis
c6609d60e386ad487ffc1508502a158a691f0a73
[ "Apache-2.0" ]
1
2018-09-13T14:46:23.000Z
2018-09-13T14:46:23.000Z
runtime/model/src/test/java/io/syndesis/integration/model/ModelUnmarshalTest.java
oscerd/syndesis
c6609d60e386ad487ffc1508502a158a691f0a73
[ "Apache-2.0" ]
null
null
null
38.8
122
0.693065
5,375
/* * Copyright 2016 Red Hat, Inc. * <p> * Red Hat 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * */ package io.syndesis.integration.model; import java.io.InputStream; import java.util.List; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; public class ModelUnmarshalTest { private static final transient Logger LOG = LoggerFactory.getLogger(ModelUnmarshalTest.class); @Test public void testUnmarshal() throws Exception { try (InputStream is = ModelUnmarshalTest.class.getResourceAsStream("/syndesis.yml")) { SyndesisModel model = YamlHelpers.load(is); List<Flow> rules = model.getFlows(); assertThat(rules).isNotEmpty(); for (Flow rule : rules) { LOG.info("Loaded: " + rule); } Flow actualFlow1 = SyndesisAssertions.assertFlow(model, 0); Flow actualFlow2 = SyndesisAssertions.assertFlow(model, 1); assertThat(actualFlow1.getName()).describedAs("name").isEqualTo("thingy"); SyndesisAssertions.assertEndpointStep(actualFlow1, 0, "http://0.0.0.0:8080"); SyndesisAssertions.assertFunctionStep(actualFlow1, 1, "io.syndesis.integration.runtime.example.Main::cheese"); assertThat(actualFlow2.getName()).describedAs("name").isEqualTo("another"); SyndesisAssertions.assertEndpointStep(actualFlow2, 0, "http://0.0.0.0:8080"); SyndesisAssertions.assertEndpointStep(actualFlow2, 1, "activemq:whatnot"); } } }
3e0cae4705e5597eeb0ee2e6c93bcbf83ee9c97a
3,853
java
Java
app/src/main/java/james/crashersample/MainActivity.java
TheAndroidMaster/Crasher
d3bf374c783d503e04eeea8a09ba0a1498fdb0ee
[ "Apache-2.0" ]
19
2018-02-24T18:12:26.000Z
2018-11-01T22:17:46.000Z
app/src/main/java/james/crashersample/MainActivity.java
TheAndroidMaster/Crasher
d3bf374c783d503e04eeea8a09ba0a1498fdb0ee
[ "Apache-2.0" ]
5
2018-05-07T22:00:59.000Z
2018-06-22T20:23:39.000Z
app/src/main/java/james/crashersample/MainActivity.java
TheAndroidMaster/Crasher
d3bf374c783d503e04eeea8a09ba0a1498fdb0ee
[ "Apache-2.0" ]
6
2018-02-24T18:16:35.000Z
2018-07-18T08:09:10.000Z
35.703704
101
0.619295
5,376
package james.crashersample; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatButton; import android.support.v7.widget.SwitchCompat; import android.util.Log; import android.view.View; import android.widget.CompoundButton; import android.widget.TextView; import james.crasher.Crasher; public class MainActivity extends AppCompatActivity implements Crasher.OnCrashListener { private Crasher crasher; private SwitchCompat stackOverflowSwitch; private SwitchCompat crashActivitySwitch; private SwitchCompat backgroundSwitch; private AppCompatButton colorButton; private int color; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); crasher = new Crasher(this) .addListener(this) .setEmail("kenaa@example.com"); stackOverflowSwitch = findViewById(R.id.stackOverflow); crashActivitySwitch = findViewById(R.id.crashActivity); backgroundSwitch = findViewById(R.id.background); colorButton = findViewById(R.id.color); findViewById(R.id.nullPointer).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((TextView) null).setText("Hi!"); } }); stackOverflowSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { crasher.setForceStackOverflow(isChecked); } }); crashActivitySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { crasher.setCrashActivityEnabled(isChecked); } }); backgroundSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { crasher.setBackgroundCrash(b); } }); setColor(ContextCompat.getColor(this, R.color.colorPrimary)); colorButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { color++; switch (color % 5) { case 0: setColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary)); break; case 1: setColor(Color.parseColor("#009688")); break; case 2: setColor(Color.parseColor("#43A047")); break; case 3: setColor(Color.parseColor("#FF5722")); break; case 4: setColor(Color.parseColor("#F44336")); break; } } }); } private void setColor(int color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { colorButton.setBackgroundTintList(ColorStateList.valueOf(color)); } else colorButton.setTextColor(color); crasher.setColor(color); } @Override public void onCrash(Thread thread, Throwable throwable) { Log.d("MainActivity", "Exception thrown: " + throwable.getClass().getName()); } }
3e0caf0934e8a39898d7321cd901660b0ab4e0bf
483
java
Java
NBStudioCore/src/org/nbstudio/cachefilesystem/CacheURLHandler.java
gevorg95/NBStudio
ccaf7474c5e338313d15dac60adafb0670a61692
[ "MIT" ]
14
2015-02-08T15:36:21.000Z
2019-11-28T10:38:37.000Z
NBStudioCore/src/org/nbstudio/cachefilesystem/CacheURLHandler.java
gevorg95/NBStudio
ccaf7474c5e338313d15dac60adafb0670a61692
[ "MIT" ]
4
2015-06-30T06:38:52.000Z
2016-03-01T04:35:53.000Z
NBStudioCore/src/org/nbstudio/cachefilesystem/CacheURLHandler.java
gevorg95/NBStudio
ccaf7474c5e338313d15dac60adafb0670a61692
[ "MIT" ]
7
2015-02-24T02:35:02.000Z
2019-06-25T02:51:34.000Z
20.125
72
0.732919
5,377
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.nbstudio.cachefilesystem; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; /** * * @author daimor */ public class CacheURLHandler extends URLStreamHandler{ @Override protected URLConnection openConnection(URL url) throws IOException { return new CacheURLConnection(url); } }
3e0caf7a4657005973cd05da3fc735b0ac556922
1,397
java
Java
final/app/src/main/java/com/google/firebase/codelab/awesomedrawingquiz/service/AwesomeDrawingQuizInstanceIdService.java
Shiam004/Wallpaper-app-android
a57db58bb49161feb913b980c8b28a4e4a687860
[ "Apache-2.0" ]
5
2020-06-21T01:26:44.000Z
2021-10-08T19:11:26.000Z
final/app/src/main/java/com/google/firebase/codelab/awesomedrawingquiz/service/AwesomeDrawingQuizInstanceIdService.java
HilenSector/firebase-monetization-tips
f99dd92adb70719ebf19df989f77864859ddf497
[ "Apache-2.0" ]
3
2019-03-10T19:55:38.000Z
2020-07-18T14:40:08.000Z
final/app/src/main/java/com/google/firebase/codelab/awesomedrawingquiz/service/AwesomeDrawingQuizInstanceIdService.java
HilenSector/firebase-monetization-tips
f99dd92adb70719ebf19df989f77864859ddf497
[ "Apache-2.0" ]
8
2018-05-20T18:29:32.000Z
2020-10-24T03:22:51.000Z
36.763158
84
0.759485
5,378
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.codelab.awesomedrawingquiz.service; import com.google.firebase.iid.FirebaseInstanceIdService; public class AwesomeDrawingQuizInstanceIdService extends FirebaseInstanceIdService { }
3e0cb049dac6d7476acb24e62b11a0d24e60522f
9,042
java
Java
src/java/platform/com.ibm.streams.controller/src/main/java/com/ibm/streams/controller/crds/imports/ImportFactory.java
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
10
2021-02-19T20:19:24.000Z
2021-09-16T05:11:50.000Z
src/java/platform/com.ibm.streams.controller/src/main/java/com/ibm/streams/controller/crds/imports/ImportFactory.java
xguerin/openstreams
7000370b81a7f8778db283b2ba9f9ead984b7439
[ "Apache-2.0" ]
7
2021-02-20T01:17:12.000Z
2021-06-08T14:56:34.000Z
src/java/platform/com.ibm.streams.controller/src/main/java/com/ibm/streams/controller/crds/imports/ImportFactory.java
IBMStreams/OSStreams
c6287bd9ec4323f567d2faf59125baba8604e1db
[ "Apache-2.0" ]
4
2021-02-19T18:43:10.000Z
2022-02-23T14:18:16.000Z
35.458824
102
0.65616
5,379
/* * Copyright 2021 IBM Corporation * * 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.ibm.streams.controller.crds.imports; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_API_VERSION; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_APP_LABEL_KEY; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_APP_LABEL_VALUE; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_APP_NAME_ANNOTATION_KEY; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_APP_SCOPE_ANNOTATION_KEY; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_CRD_GROUP; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_CRD_VERSION; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_GENERATION_LABEL_KEY; import static com.ibm.streams.controller.crds.ICustomResourceCommons.STREAMS_JOB_LABEL_KEY; import com.ibm.streams.controller.crds.jobs.Job; import com.ibm.streams.controller.utils.ObjectUtils; import com.ibm.streams.instance.sam.model.InputPort; import com.ibm.streams.instance.sam.model.topology.ImportedStreams; import io.fabric8.kubernetes.api.model.DeletionPropagation; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.OwnerReference; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext; import io.fabric8.kubernetes.internal.KubernetesDeserializer; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import lombok.var; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ImportFactory { public static final String STREAMS_IMPORT_CRD_NAME = "streamsimports." + STREAMS_CRD_GROUP; private static final Logger LOGGER = LoggerFactory.getLogger(ImportFactory.class); private final KubernetesClient client; private final CustomResourceDefinitionContext context; public ImportFactory(KubernetesClient client) { /* * Save the client handle. */ this.client = client; /* * Pre-register our CRD signature with the embedded JSON deserializer. This is a required step. * * See: fabric8io/kubernetes-client#1099 */ KubernetesDeserializer.registerCustomKind(STREAMS_API_VERSION, "Import", Import.class); /* * Look for the Import CRD. */ this.context = client.customResourceDefinitions().list().getItems().stream() .filter(e -> e.getMetadata().getName().equals(STREAMS_IMPORT_CRD_NAME)) .findFirst() .map(CustomResourceDefinitionContext::fromCrd) .orElseThrow(RuntimeException::new); } public CustomResourceDefinitionContext getContext() { return context; } /* * Add/delete Import, called by the Job launcher and the Job state machine. */ public void addImport(Job job, BigInteger peId, InputPort op) { /* * Grab the imported stream. */ var is = op.getImportedStreams(); /* * Build spec. */ var spec = new ImportSpec(); spec.setJobId(job.getSpec().getId()); spec.setPeId(peId); spec.setPortId(op.getId()); spec.setPortIndex(op.getIndex()); spec.setStreams(is); /* * Create the import. */ addImport(job, job.getMetadata().getName() + "-" + peId + "-" + op.getId(), spec); } public void deleteImport(Import imp) { LOGGER.debug("DEL {}", imp.getMetadata().getName()); client .customResources(this.context, Import.class, ImportList.class, DoneableImport.class) .delete(imp); } public void deleteImports(Job job) { /* FIXME(regression) https://github.com/fabric8io/kubernetes-client/issues/2745 */ var list = client .customResources(this.context, Import.class, ImportList.class, DoneableImport.class) .inNamespace(job.getMetadata().getNamespace()) .withLabel(STREAMS_JOB_LABEL_KEY, job.getMetadata().getName()) .list(); client.resourceList(list).withPropagationPolicy(DeletionPropagation.BACKGROUND).delete(); } /* * Add Import, called by the import controller on deletion and the addImport above. */ void addImport(Job job, String name, ImportSpec spec) { /* * Build owner reference. */ var or = new OwnerReference(); or.setApiVersion(STREAMS_CRD_GROUP + '/' + STREAMS_CRD_VERSION); or.setKind("Job"); or.setName(job.getMetadata().getName()); or.setUid(job.getMetadata().getUid()); or.setController(true); or.setBlockOwnerDeletion(true); /* * Build the labels. */ var labels = new HashMap<String, String>(); labels.put(STREAMS_JOB_LABEL_KEY, job.getMetadata().getName()); labels.put(STREAMS_GENERATION_LABEL_KEY, job.getSpec().getGenerationId().toString()); labels.put(STREAMS_APP_LABEL_KEY, STREAMS_APP_LABEL_VALUE); /* * Build the annotations. */ var annotations = new HashMap<String, String>(); annotations.put( STREAMS_APP_NAME_ANNOTATION_KEY, job.getMetadata().getAnnotations().get(STREAMS_APP_NAME_ANNOTATION_KEY)); annotations.put( STREAMS_APP_SCOPE_ANNOTATION_KEY, job.getMetadata().getAnnotations().get(STREAMS_APP_SCOPE_ANNOTATION_KEY)); /* * Build the config map metadata. */ var meta = new ObjectMeta(); meta.setName(name); meta.setNamespace(job.getMetadata().getNamespace()); meta.setOwnerReferences(Collections.singletonList(or)); meta.setLabels(labels); meta.setAnnotations(annotations); /* * Build the config map. */ var imp = new Import(); imp.setMetadata(meta); imp.setSpec(spec); /* * Create the import. */ LOGGER.debug("ADD {}", imp.getMetadata().getName()); client .customResources(this.context, Import.class, ImportList.class, DoneableImport.class) .inNamespace(job.getMetadata().getNamespace()) .create(imp); } /* * Update Import, called by the import coordinator. */ void updateImport(Import imp, String filter) { /* * Duplicate the Import. */ ObjectUtils.deepCopy(imp, Import.class) .ifPresent( target -> { /* * Update the imported streams. */ target.getSpec().getStreams().setFilter(filter); /* * Patch the Import. */ LOGGER.debug("UPD {}", imp.getMetadata().getName()); client .customResources(context, Import.class, ImportList.class, DoneableImport.class) .inNamespace(imp.getMetadata().getNamespace()) .withName(imp.getMetadata().getName()) .patch(target); }); } void updateImport(Import imp, ImportedStreams streams) { /* * Duplicate the Import. */ ObjectUtils.deepCopy(imp, Import.class) .ifPresent( target -> { /* * Update the imported streams. */ target.getSpec().setStreams(streams); /* * Patch the Import. */ LOGGER.debug("UPD {}", imp.getMetadata().getName()); client .customResources(context, Import.class, ImportList.class, DoneableImport.class) .inNamespace(imp.getMetadata().getNamespace()) .withName(imp.getMetadata().getName()) .patch(target); }); } void updateImport(Job job, Import imp) { /* * Duplicate the Import. */ ObjectUtils.deepCopy(imp, Import.class) .ifPresent( target -> { /* * Update the generation ID. */ target .getMetadata() .getLabels() .put(STREAMS_GENERATION_LABEL_KEY, job.getSpec().getGenerationId().toString()); /* * Patch the Import. */ LOGGER.debug("UPD {}", imp.getMetadata().getName()); client .customResources(context, Import.class, ImportList.class, DoneableImport.class) .inNamespace(job.getMetadata().getNamespace()) .withName(imp.getMetadata().getName()) .patch(target); }); } }
3e0cb0899abb226871f3a5e5227ba6c4f9ae0735
6,789
java
Java
core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java
tx2/DependencyCheck
feb83c4a5b473dded7128ea07299500e93d9d8bd
[ "Apache-2.0" ]
3,931
2015-01-05T21:13:12.000Z
2022-03-31T17:35:31.000Z
core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java
Driste/DependencyCheck
acd23915a66fda8cdc0b4663fab7e1fa355fd94f
[ "Apache-2.0" ]
3,291
2015-01-01T17:00:31.000Z
2022-03-31T17:11:31.000Z
core/src/test/java/org/owasp/dependencycheck/analyzer/AutoconfAnalyzerTest.java
Driste/DependencyCheck
acd23915a66fda8cdc0b4663fab7e1fa355fd94f
[ "Apache-2.0" ]
1,080
2015-02-03T23:35:29.000Z
2022-03-31T15:44:02.000Z
40.278107
157
0.68929
5,380
/* * This file is part of dependency-check-core. * * 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. * * Copyright (c) 2015 Institute for Defense Analyses. All Rights Reserved. */ package org.owasp.dependencycheck.analyzer; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.dependency.Dependency; import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.owasp.dependencycheck.dependency.Confidence; import org.owasp.dependencycheck.dependency.Evidence; import org.owasp.dependencycheck.dependency.EvidenceType; /** * Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were * obtained from outside open source software projects. Links to those projects * are given below. * * @author Dale Visser * @see <a href="http://readable.sourceforge.net/">Readable Lisp S-expressions * Project</a> * @see <a href="https://gnu.org/software/binutils/">GNU Binutils</a> * @see <a href="https://gnu.org/software/ghostscript/">GNU Ghostscript</a> */ public class AutoconfAnalyzerTest extends BaseTest { /** * The analyzer to test. */ private AutoconfAnalyzer analyzer; /** * Correctly setup the analyzer for testing. * * @throws Exception thrown if there is a problem */ @Before @Override public void setUp() throws Exception { super.setUp(); analyzer = new AutoconfAnalyzer(); analyzer.initialize(getSettings()); analyzer.setFilesMatched(true); analyzer.prepare(null); } /** * Cleanup the analyzer's temp files, etc. * * @throws Exception thrown if there is a problem */ @After @Override public void tearDown() throws Exception { analyzer.close(); analyzer = null; super.tearDown(); } /** * Test whether expected evidence is gathered from Ghostscript's configure. * * @throws AnalysisException is thrown when an exception occurs. */ @Test public void testAnalyzeConfigureAC1() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile( this, "autoconf/ghostscript/configure.ac")); analyzer.analyze(result, null); //TODO fix these assertTrue(result.contains(EvidenceType.VENDOR, new Evidence("configure.ac", "Bug report address", "lyhxr@example.com", Confidence.HIGH))); assertTrue(result.contains(EvidenceType.PRODUCT, new Evidence("configure.ac", "Package", "gnu-ghostscript", Confidence.HIGHEST))); assertTrue(result.contains(EvidenceType.VERSION, new Evidence("configure.ac", "Package Version", "8.62.0", Confidence.HIGHEST))); } /** * Test whether expected evidence is gathered from Readable's configure.ac. * * @throws AnalysisException is thrown when an exception occurs. */ @Test public void testAnalyzeConfigureAC2() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile( this, "autoconf/readable-code/configure.ac")); analyzer.analyze(result, null); assertTrue(result.contains(EvidenceType.VENDOR, new Evidence("configure.ac", "Bug report address", "hzdkv@example.com", Confidence.HIGH))); assertTrue(result.contains(EvidenceType.PRODUCT, new Evidence("configure.ac", "Package", "readable", Confidence.HIGHEST))); assertTrue(result.contains(EvidenceType.VERSION, new Evidence("configure.ac", "Package Version", "1.0.7", Confidence.HIGHEST))); assertTrue(result.contains(EvidenceType.VENDOR, new Evidence("configure.ac", "URL", "http://readable.sourceforge.net/", Confidence.HIGH))); } /** * Test whether expected evidence is gathered from GNU Binutil's configure. * * @throws AnalysisException is thrown when an exception occurs. */ @Test public void testAnalyzeConfigureScript() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile( this, "autoconf/binutils/configure")); analyzer.analyze(result, null); assertTrue(result.contains(EvidenceType.PRODUCT, new Evidence("configure", "NAME", "binutils", Confidence.HIGHEST))); assertTrue(result.contains(EvidenceType.VERSION, new Evidence("configure", "VERSION", "2.25.51", Confidence.HIGHEST))); } /** * Test whether expected evidence is gathered from GNU Ghostscript's * configure. * * @throws AnalysisException is thrown when an exception occurs. */ @Test public void testAnalyzeReadableConfigureScript() throws AnalysisException { final Dependency result = new Dependency(BaseTest.getResourceAsFile( this, "autoconf/readable-code/configure")); analyzer.analyze(result, null); assertTrue(result.contains(EvidenceType.VENDOR, new Evidence("configure", "BUGREPORT", "hzdkv@example.com", Confidence.HIGH))); assertTrue(result.contains(EvidenceType.PRODUCT, new Evidence("configure", "NAME", "readable", Confidence.HIGHEST))); assertTrue(result.contains(EvidenceType.VERSION, new Evidence("configure", "VERSION", "1.0.7", Confidence.HIGHEST))); assertTrue(result.contains(EvidenceType.VENDOR, new Evidence("configure", "URL", "http://readable.sourceforge.net/", Confidence.HIGH))); } /** * Test of getName method, of {@link AutoconfAnalyzer}. */ @Test public void testGetName() { assertEquals("Analyzer name wrong.", "Autoconf Analyzer", analyzer.getName()); } /** * Test of {@link AutoconfAnalyzer#accept(File)}. */ @Test public void testSupportsFileExtension() { assertTrue("Should support \"ac\" extension.", analyzer.accept(new File("configure.ac"))); assertTrue("Should support \"in\" extension.", analyzer.accept(new File("configure.in"))); assertTrue("Should support \"configure\" extension.", analyzer.accept(new File("configure"))); } }
3e0cb1615597d1c5d6ee1543d056453ec870208c
703
java
Java
src/main/java/com/johnfnash/learn/executor/fork_join/exception/Main.java
JohnFNash/ConcurrencyInPractice
9f2ccabe9eddd4acc6774df4fa586315208e7ed8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/johnfnash/learn/executor/fork_join/exception/Main.java
JohnFNash/ConcurrencyInPractice
9f2ccabe9eddd4acc6774df4fa586315208e7ed8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/johnfnash/learn/executor/fork_join/exception/Main.java
JohnFNash/ConcurrencyInPractice
9f2ccabe9eddd4acc6774df4fa586315208e7ed8
[ "Apache-2.0" ]
null
null
null
25.107143
58
0.668563
5,382
package com.johnfnash.learn.executor.fork_join.exception; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { int array[] = new int[100]; Task task = new Task(array,0,100); ForkJoinPool pool = new ForkJoinPool(); pool.execute(task); try { pool.awaitTermination(1, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } if (task.isCompletedAbnormally()) { System.out.printf("Main: An exception has ocurred\n"); System.out.printf("Main: %s\n",task.getException()); } System.out.printf("Main: Result: %d", task.join()); } }
3e0cb1ef923bf507d3f9b94240d79913fe6113dd
1,535
java
Java
ProjetoFabrica/src/projetofabrica/ProjetoFabrica.java
MarcioAntusa/PadroesDeProjeto-Java-
6ba476cc4561e082cc75beebf514a28e0a5ecf73
[ "MIT" ]
null
null
null
ProjetoFabrica/src/projetofabrica/ProjetoFabrica.java
MarcioAntusa/PadroesDeProjeto-Java-
6ba476cc4561e082cc75beebf514a28e0a5ecf73
[ "MIT" ]
null
null
null
ProjetoFabrica/src/projetofabrica/ProjetoFabrica.java
MarcioAntusa/PadroesDeProjeto-Java-
6ba476cc4561e082cc75beebf514a28e0a5ecf73
[ "MIT" ]
null
null
null
31.979167
79
0.545277
5,383
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package projetofabrica; import javax.swing.JOptionPane; import modelos.*; import fabrica.FabricaProdutos; /** * * @author M */ public class ProjetoFabrica { /** * @param args the command line arguments */ private static void imprimirDados(Produto objeto){ String saida = "Descriรงรฃo:\n\n" + "Tipo de Produto: " + objeto.getTipoProduto() + "\n" + "Codigo: " + objeto.getCodigo() + "\n" + "Preรงo: R$ " + objeto.getPrecoVenda() + "\n\n" + objeto.descricao(); JOptionPane.showMessageDialog(null, saida); } public static void main(String[] args) { // TODO code application logic here boolean controle = true; Object[] opcoes = {"LIVRO", "CDMUSICA", "NOTEBOOK", "CELULAR"}; Object tipoDoProduto; Produto obj = null; do{ tipoDoProduto = JOptionPane.showInputDialog(null, "Deseja finalizar o programa?", "Finalizaรงรฃo", JOptionPane.PLAIN_MESSAGE, null,opcoes,"LIVRO"); obj = FabricaProdutos.getProduto(tipoDoProduto.toString()); imprimirDados(obj); }while(controle); } }
3e0cb212c0b040cc3ff91185b376e8d3594a6a80
3,249
java
Java
Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/util/VTAbstractProgramCorrelatorFactory.java
bdcht/ghidra
9e732318148cd11edeb4862afd23d56418551812
[ "Apache-2.0" ]
17
2022-01-15T03:52:37.000Z
2022-03-30T18:12:17.000Z
Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/util/VTAbstractProgramCorrelatorFactory.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
9
2022-01-15T03:58:02.000Z
2022-02-21T10:22:49.000Z
Ghidra/Features/VersionTracking/src/main/java/ghidra/feature/vt/api/util/VTAbstractProgramCorrelatorFactory.java
BStudent/ghidra
0cdc722921cef61b7ca1b7236bdc21079fd4c03e
[ "Apache-2.0" ]
3
2019-12-02T13:36:50.000Z
2019-12-04T05:40:12.000Z
36.505618
97
0.787935
5,384
/* ### * IP: GHIDRA * * 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 ghidra.feature.vt.api.util; import ghidra.feature.vt.api.main.*; import ghidra.framework.plugintool.ServiceProvider; import ghidra.program.model.address.AddressSetView; import ghidra.program.model.listing.Program; public abstract class VTAbstractProgramCorrelatorFactory implements VTProgramCorrelatorFactory { private final VTProgramCorrelatorAddressRestrictionPreference addressRestrictionPreference; protected VTAbstractProgramCorrelatorFactory( VTProgramCorrelatorAddressRestrictionPreference addressRestrictionPreference) { this.addressRestrictionPreference = addressRestrictionPreference; } protected VTAbstractProgramCorrelatorFactory() { this(VTProgramCorrelatorAddressRestrictionPreference.PREFER_RESTRICTING_ACCEPTED_MATCHES); } /** * Returns the name of the correlator for display to the user in the GUI. * @return the name of the correlator */ @Override public abstract String getName(); /** * Returns the description of the correlator for display to the user in the GUI. * @return the description of the correlator */ @Override public abstract String getDescription(); @Override public String toString() { return getName() + ": " + getDescription(); } @Override public VTProgramCorrelatorAddressRestrictionPreference getAddressRestrictionPreference() { return addressRestrictionPreference; } /** * Returns an options action that contains a list of all supported options for the algorithm and * their default values. Override if you need to provide other than the * @return an options action that contains a list of all supported options for the algorithm and * their default values. */ @Override public VTOptions createDefaultOptions() { return new VTOptions(getName()); } @Override public final VTProgramCorrelator createCorrelator(ServiceProvider serviceProvider, Program sourceProgram, AddressSetView sourceAddressSet, Program destinationProgram, AddressSetView destinationAddressSet, VTOptions options) { return doCreateCorrelator(serviceProvider, sourceProgram, sourceAddressSet, destinationProgram, destinationAddressSet, options == null ? createDefaultOptions() : (VTOptions) options.copy()); } /** * This method is added to the interface to enforce the fact that we want options passed into * this method to be copies so that changes during correlation do not spoil the options * of others. */ protected abstract VTProgramCorrelator doCreateCorrelator(ServiceProvider serviceProvider, Program sourceProgram, AddressSetView sourceAddressSet, Program destinationProgram, AddressSetView destinationAddressSet, VTOptions options); }
3e0cb260c029610c1dcf9a4e7a2b0736dbb81aba
1,654
java
Java
app/src/main/java/com/example/android/miwok/MainActivity.java
BilbySwig/Miwok
a24d4edc290bef2c1520128e09864d9549c34fc0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/MainActivity.java
BilbySwig/Miwok
a24d4edc290bef2c1520128e09864d9549c34fc0
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/MainActivity.java
BilbySwig/Miwok
a24d4edc290bef2c1520128e09864d9549c34fc0
[ "Apache-2.0" ]
null
null
null
33.08
83
0.71705
5,385
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.miwok; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content of the activity to use the activity_main.xml layout file setContentView(R.layout.activity_main); } public void openNumbersList(View view){ Intent i=new Intent(this,NumbersActivity.class); startActivity(i); } public void openFamList(View view){ Intent i=new Intent(this,FamilyActivity.class); startActivity(i); } public void openColorsList(View view){ Intent i=new Intent(this,ColorsActivity.class); startActivity(i); } public void openPhrasesList(View view){ Intent i=new Intent(this,PhrasesActivity.class); startActivity(i); } }
3e0cb38259b97da0e6a57a80eab9ff6ad27a1895
3,014
java
Java
src/main/java/org/jahap/sreport/ratesDataSource.java
citeaux/JAHAP
9c2274fdf8fe5f52e1236e86ed51c567eb0cbf95
[ "MIT" ]
null
null
null
src/main/java/org/jahap/sreport/ratesDataSource.java
citeaux/JAHAP
9c2274fdf8fe5f52e1236e86ed51c567eb0cbf95
[ "MIT" ]
null
null
null
src/main/java/org/jahap/sreport/ratesDataSource.java
citeaux/JAHAP
9c2274fdf8fe5f52e1236e86ed51c567eb0cbf95
[ "MIT" ]
null
null
null
32.06383
110
0.701062
5,386
/* * The MIT License * * Copyright 2014 Sebastian Russ <citeaux at https://github.com/citeaux/JAHAP>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jahap.sreport; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.List; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRField; import org.jahap.business.base.Hotelbean; import org.jahap.entities.base.Rates; /** * * @author russ */ public class ratesDataSource implements JRDataSource{ private List<Rates>ratesSource; private Hotelbean hbean; private DecimalFormat DecFormatter; private SimpleDateFormat DFormat; public ratesDataSource(List<Rates>ratesSource) { hbean= new Hotelbean(); DecFormatter= new DecimalFormat(hbean.getHotelNumberformat()); DFormat= new SimpleDateFormat(hbean.getHoteldateformat()); this.ratesSource=ratesSource; } private int counter=-1; private HashMap<String,Integer> fieldNumber= new HashMap<String, Integer>(); public boolean next() throws JRException { if(counter<ratesSource.size()-1){ counter++; return true; } return false; } public Object getFieldValue(JRField jrf) throws JRException { if(jrf.getName().equals("name"))return ratesSource.get(counter).getName(); else if(jrf.getName().equals("price"))return DecFormatter.format(ratesSource.get(counter).getPrice()); else if(jrf.getName().equals("revaccount"))return ratesSource.get(counter).getRevaccount(); else if(jrf.getName().equals("code"))return ratesSource.get(counter).getCode(); return ""; } /* public static JRDataSource getDataSource(){ return new addressDataSource(); } */ }
3e0cb3c1cfa5b261ce5c2c234bc32bc2c5f437a1
11,984
java
Java
3DModeling-Sample/cameratakelib/src/main/java/com/huawei/cameratakelib/utils/FileUtil.java
FStranieri/hms-3d-modeling-demo
700887a0f9517855e1d4aba8225e326c079c77fc
[ "Apache-2.0" ]
40
2021-07-15T07:28:47.000Z
2022-03-23T03:02:16.000Z
3DModeling-Sample/cameratakelib/src/main/java/com/huawei/cameratakelib/utils/FileUtil.java
zeedevio/hms-3d-modeling-demo
47756046c359a7cb78ee2e06ec87d6e356a85b3a
[ "Apache-2.0" ]
11
2021-08-03T06:42:38.000Z
2022-01-14T11:40:44.000Z
3DModeling-Sample/cameratakelib/src/main/java/com/huawei/cameratakelib/utils/FileUtil.java
zeedevio/hms-3d-modeling-demo
47756046c359a7cb78ee2e06ec87d6e356a85b3a
[ "Apache-2.0" ]
17
2021-07-16T01:17:44.000Z
2022-03-06T13:39:08.000Z
35.666667
133
0.537884
5,387
package com.huawei.cameratakelib.utils; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Rect; import android.media.Image; import android.opengl.GLES20; import android.os.Environment; import android.os.StatFs; import android.text.TextUtils; import android.util.Log; import com.huawei.hms.magicresource.util.Constants; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.IntBuffer; import top.zibin.luban.CompressionPredicate; import top.zibin.luban.Luban; import top.zibin.luban.OnCompressListener; public class FileUtil { /** * ่ฎก็ฎ—Sdcard็š„ๅ‰ฉไฝ™ๅคงๅฐ * * @return MB */ public static long getAvailableSize() { //sdๅกๅคงๅฐ็›ธๅ…ณๅ˜้‡ StatFs statFs; File file = Environment.getExternalStorageDirectory(); statFs = new StatFs(file.getPath()); //่Žทๅพ—SdcardไธŠๆฏไธชblock็š„size long blockSize = statFs.getBlockSize(); //่Žทๅ–ๅฏไพ›็จ‹ๅบไฝฟ็”จ็š„Blockๆ•ฐ้‡ long blockavailable = statFs.getAvailableBlocks(); //่ฎก็ฎ—ๆ ‡ๅ‡†ๅคงๅฐไฝฟ็”จ๏ผš1024๏ผŒๅฝ“็„ถไฝฟ็”จ1000ไนŸๅฏไปฅ long blockavailableTotal = blockSize * blockavailable / 1024 / 1024; return blockavailableTotal; } /** * SDCard ๆ€ปๅฎน้‡ๅคงๅฐ * * @return MB */ public static long getTotalSize() { StatFs statFs; File file = Environment.getExternalStorageDirectory(); statFs = new StatFs(file.getPath()); //่Žทๅพ—sdcardไธŠ block็š„ๆ€ปๆ•ฐ long blockCount = statFs.getBlockCount(); //่Žทๅพ—sdcardไธŠๆฏไธชblock ็š„ๅคงๅฐ long blockSize = statFs.getBlockSize(); //่ฎก็ฎ—ๆ ‡ๅ‡†ๅคงๅฐไฝฟ็”จ๏ผš1024๏ผŒๅฝ“็„ถไฝฟ็”จ1000ไนŸๅฏไปฅ long bookTotalSize = blockCount * blockSize / 1024 / 1024; return bookTotalSize; } /** * ไฟๅญ˜bitmapๅˆฐๆœฌๅœฐ * * @param bitmap * @return */ public static File saveBitmap(Context context, Bitmap bitmap, String createTime, Integer index) { String savePath = new Constants(context).getCaptureMaterialImageFile() + createTime + "/"; // String savePath = "/data/data/com.huawei.hms.modeling/files/3DMagic" + createTime + "/"; // String savePath = "/sdcard/3DMagic/3DMagic" + createTime + "/"; File filePic; try { filePic = new File(savePath + index + ".jpg"); if (!filePic.exists()) { if (!filePic.getParentFile().exists()) { filePic.getParentFile().mkdirs(); } filePic.createNewFile(); } FileOutputStream fos = new FileOutputStream(filePic); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); LogUtil.d("saveBitmap: 2return"); return null; } LogUtil.d("saveBitmap: " + filePic.getAbsolutePath()); return filePic; } public static void saveBitmap(Bitmap bitmap, String fileName) { try { File filePic = new File(fileName); if (!filePic.exists()) { if (!filePic.getParentFile().exists()) { filePic.getParentFile().mkdirs(); } // filePic.createNewFile(); } FileOutputStream fos = new FileOutputStream(filePic); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (IOException ioe) { throw new RuntimeException("Unable to create output file ", ioe); } } public static Bitmap rotateBitmap(Bitmap bmp) { Matrix matrix = new Matrix(); matrix.postRotate(-90); return Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true); } /** * Image ่ฝฌ Bitmap * @param image * @return */ public static Bitmap image2Bitmap(Image image) { int mHeight = image.getHeight(); int mWidth = image.getWidth(); int pixelData[] = new int[mWidth * mHeight]; IntBuffer buf = IntBuffer.wrap(pixelData); buf.position(0); GLES20.glReadPixels(0, 0, mWidth, mHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buf); int bitmapData[] = new int[pixelData.length]; for (int i = 0; i < mHeight; i++) { for (int j = 0; j < mWidth; j++) { int p = pixelData[i * mWidth + j]; int b = (p & 0x00ff0000) >> 16; int r = (p & 0x000000ff) << 16; int ga = p & 0xff00ff00; bitmapData[(mHeight - i - 1) * mWidth + j] = ga | r | b; } } return Bitmap.createBitmap(bitmapData, mWidth, mHeight, Bitmap.Config.ARGB_8888); } /** * ๅŽ‹็ผฉๅ›พ็‰‡ * * @param image * @return */ public static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); /** ่ดจ้‡ๅŽ‹็ผฉๆ–นๆณ•๏ผŒ่ฟ™้‡Œ100่กจ็คบไธๅŽ‹็ผฉ๏ผŒๆŠŠๅŽ‹็ผฉๅŽ็š„ๆ•ฐๆฎๅญ˜ๆ”พๅˆฐbaosไธญ*/ image.compress(Bitmap.CompressFormat.JPEG, 100, baos); /** ๆŠŠๅŽ‹็ผฉๅŽ็š„ๆ•ฐๆฎbaosๅญ˜ๆ”พๅˆฐByteArrayInputStreamไธญ*/ ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); /** ๆŠŠByteArrayInputStreamๆ•ฐๆฎ็”Ÿๆˆๅ›พ็‰‡*/ Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); return bitmap; } /** * ๆ–‡ไปถๅคนๅˆ ้™ค * */ public static void deleteFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; deleteFile(f); } file.delete();//ๅฆ‚่ฆไฟ็•™ๆ–‡ไปถๅคน๏ผŒๅชๅˆ ้™คๆ–‡ไปถ๏ผŒ่ฏทๆณจ้‡Š่ฟ™่กŒ } else if (file.exists()) { file.delete(); } } /** * ๅŽ‹็ผฉๅ›พ็‰‡ๆ–‡ไปถ * */ public static void compressRgbPic(Context context,String createTime ,int index ,final File picFile, OnCompressListener listener){ // String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) // .toString() // + File.separator; String savePath = "/sdcard/3DMagic/3DMagic/Compression/" + createTime + "/"+createTime+"/"; File dir = new File(savePath); if (!dir.exists()) { if(!dir.mkdirs()) { return; } } Luban.with(context) .load(picFile.getPath()) .ignoreBy(100) .setTargetDir(savePath) .filter(new CompressionPredicate() { @Override public boolean apply(String path) { return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")); } }) .setCompressListener(listener).launch(); } private static final int COLOR_FormatI420 = 1; private static final int COLOR_FormatNV21 = 2; private static boolean isImageFormatSupported(Image image) { int format = image.getFormat(); switch (format) { case ImageFormat.YUV_420_888: case ImageFormat.NV21: case ImageFormat.YV12: return true; } return false; } public static byte[] getDataFromImage(Image image, int colorFormat) { if (colorFormat != COLOR_FormatI420 && colorFormat != COLOR_FormatNV21) { throw new IllegalArgumentException("only support COLOR_FormatI420 " + "and COLOR_FormatNV21"); } if (!isImageFormatSupported(image)) { throw new RuntimeException("can't convert Image to byte array, format " + image.getFormat()); } Rect crop = image.getCropRect(); int format = image.getFormat(); int width = crop.width(); int height = crop.height(); Image.Plane[] planes = image.getPlanes(); byte[] data = new byte[width * height * ImageFormat.getBitsPerPixel(format) / 8]; byte[] rowData = new byte[planes[0].getRowStride()]; // if (VERBOSE) Log.v(TAG, "get data from " + planes.length + " planes"); int channelOffset = 0; int outputStride = 1; for (int i = 0; i < planes.length; i++) { switch (i) { case 0: channelOffset = 0; outputStride = 1; break; case 1: if (colorFormat == COLOR_FormatI420) { channelOffset = width * height; outputStride = 1; } else if (colorFormat == COLOR_FormatNV21) { channelOffset = width * height + 1; outputStride = 2; } break; case 2: if (colorFormat == COLOR_FormatI420) { channelOffset = (int) (width * height * 1.25); outputStride = 1; } else if (colorFormat == COLOR_FormatNV21) { channelOffset = width * height; outputStride = 2; } break; } ByteBuffer buffer = planes[i].getBuffer(); int rowStride = planes[i].getRowStride(); int pixelStride = planes[i].getPixelStride(); // if (VERBOSE) { // Log.v(TAG, "pixelStride " + pixelStride); // Log.v(TAG, "rowStride " + rowStride); // Log.v(TAG, "width " + width); // Log.v(TAG, "height " + height); // Log.v(TAG, "buffer size " + buffer.remaining()); // } int shift = (i == 0) ? 0 : 1; int w = width >> shift; int h = height >> shift; buffer.position(rowStride * (crop.top >> shift) + pixelStride * (crop.left >> shift)); for (int row = 0; row < h; row++) { int length; if (pixelStride == 1 && outputStride == 1) { length = w; buffer.get(data, channelOffset, length); channelOffset += length; } else { length = (w - 1) * pixelStride + 1; buffer.get(rowData, 0, length); for (int col = 0; col < w; col++) { data[channelOffset] = rowData[col * pixelStride]; channelOffset += outputStride; } } if (row < h - 1) { buffer.position(buffer.position() + rowStride - length); } } // if (VERBOSE) Log.v(TAG, "Finished reading data from plane " + i); } return data; } public static File saveRgbBitmap(Context context, Bitmap bitmap, String createTime, Integer index) { String savePath = "/sdcard/3DMagic/3DMagic/Compression/" + createTime + "/"; File filePic; try { filePic = new File(savePath + index + ".jpg"); if (!filePic.exists()) { if (!filePic.getParentFile().exists()) { filePic.getParentFile().mkdirs(); } filePic.createNewFile(); } FileOutputStream fos = new FileOutputStream(filePic); bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos); fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); LogUtil.d("saveBitmap: 2return"); return null; } LogUtil.d("saveBitmap: " + filePic.getAbsolutePath()); return filePic; } }
3e0cb490cdf73c0167030138aaa078b68ac715b4
3,328
java
Java
app/controllers/HomeController.java
KavinduKDWanasekara/Football_Premier_League_Management_System
97eaca6854e5b8215427c672fc9e2c7ee59a24c3
[ "MIT" ]
null
null
null
app/controllers/HomeController.java
KavinduKDWanasekara/Football_Premier_League_Management_System
97eaca6854e5b8215427c672fc9e2c7ee59a24c3
[ "MIT" ]
null
null
null
app/controllers/HomeController.java
KavinduKDWanasekara/Football_Premier_League_Management_System
97eaca6854e5b8215427c672fc9e2c7ee59a24c3
[ "MIT" ]
null
null
null
39.152941
142
0.694712
5,388
package controllers; import com.fasterxml.jackson.databind.JsonNode; import entities.Date; import entities.Match; import play.libs.Json; import play.mvc.*; import services.PremierLeagueManager; import utilities.utils; import java.io.IOException; import java.util.ArrayList; import java.util.Random; public class HomeController extends Controller { PremierLeagueManager premierLeagueManager = new PremierLeagueManager(); // public HomeController() throws IOException, ClassNotFoundException { // } // public Result appSummary() { // JsonNode jsonNode = Json.toJson(new AppSummary("Java Play Angular Seed")); // return ok(jsonNode).as("application/json"); // } // // public Result postTest() { // JsonNode jsonNode = Json.toJson(new AppSummary("Post Request Test => Data Sending Success")); // return ok(jsonNode).as("application/json"); // } public void readData() { try { premierLeagueManager.readClubStatics("ClubStatics.txt"); premierLeagueManager.readMatchStatics("MatchStatics.txt"); } catch (ClassNotFoundException | IOException error) { System.out.println("Not found"); } } public Result clubData() { PremierLeagueManager.footballClubList.clear(); System.out.println("jddjd"+PremierLeagueManager.footballClubList); readData(); JsonNode premierLeagueData = utils.methodX((ArrayList) PremierLeagueManager.footballClubList); System.out.println("---------------------------------"); System.out.println(PremierLeagueManager.footballClubList); // System.out.println(premierLeagueData.toString()); return ok(premierLeagueData); } public Result matchData() { PremierLeagueManager.matchList.clear(); readData(); JsonNode premierLeagueData = utils.methodX((ArrayList) PremierLeagueManager.matchList); System.out.println("---------------------------------"); System.out.println(PremierLeagueManager.matchList); // System.out.println(premierLeagueData.toString()); return ok(premierLeagueData); } public Result genMatch() throws IOException, ClassNotFoundException { Random randClub=new Random(); String team01=premierLeagueManager.footballClubList.get(randClub.nextInt(premierLeagueManager.footballClubList.size())).getClubName(); String team02 ; // do while for to avoid the generating same name for the team 2 do { team02 = premierLeagueManager.footballClubList.get(randClub.nextInt(premierLeagueManager.footballClubList.size())).getClubName(); }while (team01.equals(team02)); Random randNum=new Random(); Date date=new Date(randNum.nextInt(31),randNum.nextInt(12),2021); int team01GoalCount=randNum.nextInt(30); int team02GoalCount=randNum.nextInt(30); Match randMatch=new Match(team01, team02,team01GoalCount,team02GoalCount,date); premierLeagueManager.addAPlayedMatch(randMatch); premierLeagueManager.writeMatchStatics("MatchStatics.txt"); premierLeagueManager.writeClubStatics("ClubStatics.txt"); JsonNode premierLeagueData = utils.methodX((ArrayList) PremierLeagueManager.matchList); return ok(premierLeagueData).as("application/json"); } }
3e0cb4e8642f07c35a853d14432cc0560ea099ec
12,878
java
Java
src/main/java/org/broadinstitute/hellbender/utils/python/StreamingPythonScriptExecutor.java
raomohan89/GATK
068b7fdd6d983cf0b7611b03bd0028d85de61bc2
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/broadinstitute/hellbender/utils/python/StreamingPythonScriptExecutor.java
raomohan89/GATK
068b7fdd6d983cf0b7611b03bd0028d85de61bc2
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/broadinstitute/hellbender/utils/python/StreamingPythonScriptExecutor.java
raomohan89/GATK
068b7fdd6d983cf0b7611b03bd0028d85de61bc2
[ "BSD-3-Clause" ]
null
null
null
45.829181
132
0.699876
5,389
package org.broadinstitute.hellbender.utils.python; import com.google.common.annotations.VisibleForTesting; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.broadinstitute.hellbender.utils.Utils; import org.broadinstitute.hellbender.utils.runtime.*; import org.broadinstitute.hellbender.exceptions.UserException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeoutException; import java.util.function.Function; import java.util.stream.Collectors; /** * Python executor used to interact with a keep-alive Python process. The lifecycle of an executor is typically: * * - construct the executor * - start the remote process ({@link #start}) and synchronize on the prompt ({@link #getAccumulatedOutput()} * - create a fifo {@link #getFIFOForWrite} * - execute asynchronous Python code {@link #sendAsynchronousCommand} to open the fifo for reading * - execute local java code to open the fifo for writing * - synchronize on the prompt resulting from the python code opening the fifo {@link #getAccumulatedOutput} * - send/receive input one or more times (write/flush to the fifo)/synchronize on the prompt ({@link #getAccumulatedOutput) output * - close the fifo locally * - terminate the executor {@link #terminate} * * Guidelines for writing GATK tools that use Python interactively: * * - Program correctness should not rely on consumption of anything written by Python to stdout/stderr other than * the use the prompt for synchronization via {@link #getAccumulatedOutput}. All data should be transferred through * a FIFO or file. * - Always synchronize after starting the Python process (through {@link #start}, followed by * {@link #getAccumulatedOutput}). * - Python code should write errors to stderr. * - The FIFO should always be flushed before executing Python code that reads from it. Failure to do so can result * in the Python process being blocked. * - Prefer single line commands that run a script, vs. multi-line Python code embedded in Java * - Always terminated with newlines (otherwise Python will block) * - Terminate commands with a newline. * - Try not to be chatty (maximize use of the fifo buffer by writing to it in batches before reading from Python) * * NOTE: Python implementations are unreliable about honoring standard I/O stream redirection. Its not safe to * try to synchronize based on anything written to standard I/O streams, since Python sometimes prints the * prompt to stdout, and sometimes to stderr: * * https://bugs.python.org/issue17620 * https://bugs.python.org/issue1927 */ public class StreamingPythonScriptExecutor extends PythonExecutorBase { private static final Logger logger = LogManager.getLogger(StreamingPythonScriptExecutor.class); private static final String NL = System.lineSeparator(); private final List<String> curatedCommandLineArgs = new ArrayList<>(); private StreamingProcessController spController; private ProcessSettings processSettings; final public static String PYTHON_PROMPT = ">>> "; /** * The start method must be called to actually start the remote executable. * * @param ensureExecutableExists throw if the python executable cannot be located */ public StreamingPythonScriptExecutor(boolean ensureExecutableExists) { this(PythonExecutableName.PYTHON, ensureExecutableExists); } /** * The start method must be called to actually start the remote executable. * * @param pythonExecutableName name of the python executable to start * @param ensureExecutableExists throw if the python executable cannot be found */ public StreamingPythonScriptExecutor(final PythonExecutableName pythonExecutableName, final boolean ensureExecutableExists) { super(pythonExecutableName, ensureExecutableExists); } /** * Start the Python process. * * @param pythonProcessArgs args to be passed to the python process * @return true if the process is successfully started */ public boolean start(final List<String> pythonProcessArgs) { return start(pythonProcessArgs, false); } /** * Start the Python process. * * @param pythonProcessArgs args to be passed to the python process * @param enableJournaling true to enable Journaling, which records all interprocess IO to a file. This is * expensive and should only be used for debugging purposes. * @return true if the process is successfully started */ public boolean start(final List<String> pythonProcessArgs, final boolean enableJournaling) { final List<String> args = new ArrayList<>(); args.add(externalScriptExecutableName); args.add("-u"); args.add("-i"); if (pythonProcessArgs != null) { args.addAll(pythonProcessArgs); } curatedCommandLineArgs.addAll(args); final InputStreamSettings isSettings = new InputStreamSettings(); final OutputStreamSettings stdOutSettings = new OutputStreamSettings(); stdOutSettings.setBufferSize(-1); final OutputStreamSettings stdErrSettings = new OutputStreamSettings(); stdErrSettings.setBufferSize(-1); processSettings = new ProcessSettings( args.toArray(new String[args.size()]), false, // redirect error null, // directory null, // env isSettings, stdOutSettings, stdErrSettings ); spController = new StreamingProcessController(processSettings, PYTHON_PROMPT, enableJournaling); return spController.start(); } /** * Send a command to Python, and wait for a response prompt, returning all accumulated output * since the last call to either <link #sendSynchronousCommand/> or <line #getAccumulatedOutput/> * This is a blocking call, and should be used for commands that execute quickly and synchronously. * If no output is received from the remote process during the timeout period, an exception will be thrown. * * The caller is required to terminate commands with a newline. The executor doesn't do this * automatically since doing so would alter the number of prompts issued by the remote process. * * @param line data to be sent to the remote process * @return ProcessOutput * @throws UserException if a timeout occurs */ public ProcessOutput sendSynchronousCommand(final String line) { if (!line.endsWith(NL)) { throw new IllegalArgumentException( "Python commands must be newline-terminated in order to be executed. " + "Indented Python code blocks must be terminated with additional newlines"); } spController.writeProcessInput(line); return getAccumulatedOutput(); } /** * Send a command to the remote process without waiting for a response. This method should only * be used for responses that will block the remote process. * * NOTE: Before executing further synchronous statements after calling this method, getAccumulatedOutput * should be called to enforce a synchronization point. * * The caller is required to terminate commands with a newline. The executor doesn't do this * automatically since it can alter the number of prompts, and thus synchronization points, issued * by the remote process. * * @param line data to send to the remote process */ public void sendAsynchronousCommand(final String line) { if (!line.endsWith(NL)) { throw new IllegalArgumentException("Python commands must be newline-terminated"); } spController.writeProcessInput(line); } /** * See if any output is currently available. This is non-blocking, and can be used to determine if a blocking * call can be made; it is always safe to call getAccumulatedOutput if isOutputAvailable is true. * @return true if data is available from the remote process. */ public boolean isOutputAvailable() { return spController.isOutputAvailable(); } /** * Return all data accumulated since the last call to {@link #getAccumulatedOutput} (either directly, or * indirectly through {@link #sendSynchronousCommand}, collected until an output prompt is detected. * * Note that the output returned is somewhat non-deterministic, in that the only guaranty is that a prompt * was detected on either stdout or stderr. It is possible for the remote process to produce the prompt on * one stream (stderr or stdout), and additional output on the other; this method may detect the prompt before * detecting the additional output on the other stream. Such output will be retained, and returned as part of * the payload the next time output is retrieved. * * For this reason, program correctness should not rely on consuming data written by Python to standard streams. * * This should only be used for short, synchronous commands that produce output quickly. If no data has been * sent from the process, this call blocks waiting for data, or the timeout (default 5 seconds) to be reached. * * Longer-running, blocking commands can be executed using {@link #sendAsynchronousCommand}, in combination * with {@link #isOutputAvailable}. * * @return ProcessOutput containing all accumulated output from stdout/stderr * @throws UserException if a timeout occurs waiting for output * @throws PythonScriptExecutorException if a traceback is detected in the output */ public ProcessOutput getAccumulatedOutput() { try { final ProcessOutput po = spController.getProcessOutputByPrompt(); final StreamOutput stdErr = po.getStderr(); if (stdErr != null) { final String stdErrText = stdErr.getBufferString(); if (stdErrText != null && stdErrText.contains("Traceback")) { throw new PythonScriptExecutorException("Traceback detected: " + stdErrText); } } return po; } catch (TimeoutException e) { throw new UserException("A timeout ocurred waiting for output from the remote Python command.", e); } } /** * Terminate the remote process, closing the fifo if any. */ public void terminate() { spController.terminate(); } /** * Obtain a temporary FIFO to be used to transfer data to Python. The FIFO is only valid for the * lifetime of the executor; it is destroyed when the executor is terminated. * * NOTE: Since opening a FIFO for write blocks until it is opened for read, the caller is responsible * for ensuring that a Python command to open the FIFO has been executed (asynchronously) before executing * code to open it for write. For this reason, the opening of the FIFO is left to the caller. * * @return */ public File getFIFOForWrite() { return spController.createFIFO(); } /** * Return a {@link AsynchronousStreamWriterService} to be used to write to an output stream, typically on a FIFO, * on a background thread. * @param streamWriter stream to which items should be written. * @param itemSerializer function that converts an item of type {@code T} to a {@code ByteArrayOutputStream} for serialization * @param <T> Type of items to be written to the stream. * @return {@link AsynchronousStreamWriterService} */ public <T> AsynchronousStreamWriterService<T> getAsynchronousStreamWriterService( final OutputStream streamWriter, final Function<T, ByteArrayOutputStream> itemSerializer) { Utils.nonNull(streamWriter); Utils.nonNull(itemSerializer); return spController.getAsynchronousStreamWriterService(streamWriter, itemSerializer); } /** * Return a (not necessarily executable) string representing the current command line for this executor * for error reporting purposes. * @return A string representing the command line used for this executor. */ public String getApproximateCommandLine() { return curatedCommandLineArgs.stream().collect(Collectors.joining(" ")); } /** * Get the Process object associated with this executor. For testing only. * * @return */ @VisibleForTesting protected Process getProcess() { return spController.getProcess(); } }
3e0cb51b2805de78dd6495731b506ce01b21ada4
2,047
java
Java
spring-cloud-starter-stream-processor-httpclient/src/main/java/org/springframework/cloud/stream/app/httpclient/processor/HttpclientProcessorConfiguration.java
spring-operator/httpclient
4e457133589c3899da8ac380f58e8bf86e23545d
[ "Apache-2.0" ]
null
null
null
spring-cloud-starter-stream-processor-httpclient/src/main/java/org/springframework/cloud/stream/app/httpclient/processor/HttpclientProcessorConfiguration.java
spring-operator/httpclient
4e457133589c3899da8ac380f58e8bf86e23545d
[ "Apache-2.0" ]
null
null
null
spring-cloud-starter-stream-processor-httpclient/src/main/java/org/springframework/cloud/stream/app/httpclient/processor/HttpclientProcessorConfiguration.java
spring-operator/httpclient
4e457133589c3899da8ac380f58e8bf86e23545d
[ "Apache-2.0" ]
null
null
null
34.694915
79
0.787005
5,390
/* * Copyright 2015-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.stream.app.httpclient.processor; import java.util.function.Function; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Processor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.integration.dsl.IntegrationFlow; import org.springframework.integration.dsl.IntegrationFlows; import org.springframework.messaging.Message; /** * A processor app that makes requests to an HTTP resource and emits the * response body as a message payload. This processor can be combined, e.g., * with a time source module to periodically poll results from a HTTP resource. * * @author Waldemar Hummer * @author Mark Fisher * @author Gary Russell * @author Christian Tzolov * @author David Turanski */ @Configuration @Import(HttpclientProcessorFunctionConfiguration.class) @EnableBinding(Processor.class) public class HttpclientProcessorConfiguration { @Autowired private Function<Message<?>, Object> httpRequest; @Bean IntegrationFlow httpClientflow(Processor processor) { return IntegrationFlows .from(processor.input()) .transform(Message.class, httpRequest::apply) .channel(processor.output()).get(); } }
3e0cb53cbbf6134cd5b5461700b35b1fdac43b01
963
java
Java
src/main/java/cn/hd/enums/InspectionYear.java
lidonghui-github/mySSC
56cb1eee7c22ab5534f76e5c024487626dab3ca5
[ "Apache-2.0" ]
2
2019-10-05T00:36:25.000Z
2019-10-05T00:36:27.000Z
src/main/java/cn/hd/enums/InspectionYear.java
lidonghui-github/mySSC
56cb1eee7c22ab5534f76e5c024487626dab3ca5
[ "Apache-2.0" ]
3
2021-12-10T01:22:53.000Z
2021-12-14T21:33:50.000Z
src/main/java/cn/hd/enums/InspectionYear.java
lidonghui-github/mySSC
56cb1eee7c22ab5534f76e5c024487626dab3ca5
[ "Apache-2.0" ]
null
null
null
20.489362
58
0.604361
5,391
package cn.hd.enums; import java.util.HashMap; import java.util.Map; /** * @Description๏ผš.ๆ˜ฏๅฆๆถ‰ๅ†œ */ public enum InspectionYear { ้žๆถ‰ๅ†œ("1","้žๆถ‰ๅ†œ"),//NOT_AGRI ๅŸŽๅธ‚ไผไธš็ป„็ป‡ๆถ‰ๅ†œ("2","ๅŸŽๅธ‚ไผไธš/็ป„็ป‡ๆถ‰ๅ†œ"),//CTBUS_ORG_AGRI ๅ†œๆ‘ไผไธš็ป„็ป‡ๆถ‰ๅ†œ("3","ๅ†œๆ‘ไผไธš/็ป„็ป‡ๆถ‰ๅ†œ");//RUBUS_ORG_AGRI public static InspectionYear getByCode(String code) { return map.get(code); } private static Map<String, InspectionYear> map; static { map = new HashMap<String, InspectionYear>(); for (InspectionYear e : InspectionYear.values()) { map.put(e.getCode(), e); } } public boolean equals(String code) { return this.code.equals(code); } public String getCode() { return code; } public String getName() { return name; } private final String code; private final String name; private InspectionYear(String code, String name) { this.code = code; this.name = name; } }
3e0cb5432d5a7ee9c818b9e34983e38d4048d11e
14,686
java
Java
src/main/java/org/orekit/estimation/measurements/modifiers/BistaticRangeRateTroposphericDelayModifier.java
mfkiwl/Orekit
d01619f6673d72c329cfe9e38ee091ba6b9e748e
[ "Apache-2.0" ]
null
null
null
src/main/java/org/orekit/estimation/measurements/modifiers/BistaticRangeRateTroposphericDelayModifier.java
mfkiwl/Orekit
d01619f6673d72c329cfe9e38ee091ba6b9e748e
[ "Apache-2.0" ]
null
null
null
src/main/java/org/orekit/estimation/measurements/modifiers/BistaticRangeRateTroposphericDelayModifier.java
mfkiwl/Orekit
d01619f6673d72c329cfe9e38ee091ba6b9e748e
[ "Apache-2.0" ]
null
null
null
47.221865
117
0.620863
5,392
/* Copyright 2002-2022 CS GROUP * Licensed to CS GROUP (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.estimation.measurements.modifiers; import java.util.Arrays; import java.util.List; import org.hipparchus.CalculusFieldElement; import org.hipparchus.Field; import org.hipparchus.analysis.differentiation.Gradient; import org.hipparchus.geometry.euclidean.threed.FieldVector3D; import org.hipparchus.geometry.euclidean.threed.Vector3D; import org.orekit.attitudes.InertialProvider; import org.orekit.estimation.measurements.BistaticRangeRate; import org.orekit.estimation.measurements.EstimatedMeasurement; import org.orekit.estimation.measurements.EstimationModifier; import org.orekit.estimation.measurements.GroundStation; import org.orekit.models.earth.troposphere.DiscreteTroposphericModel; import org.orekit.propagation.FieldSpacecraftState; import org.orekit.propagation.SpacecraftState; import org.orekit.utils.Differentiation; import org.orekit.utils.ParameterDriver; import org.orekit.utils.ParameterFunction; /** Class modifying theoretical bistatic range-rate measurements with tropospheric delay. * <p> * The effect of tropospheric correction on the bistatic range-rate is directly computed * through the computation of the tropospheric delay difference with respect to time. * </p><p> * Tropospheric delay is not frequency dependent for signals up to 15 GHz. * </p> * @author Pascal Parraud * @since 11.2 */ public class BistaticRangeRateTroposphericDelayModifier implements EstimationModifier<BistaticRangeRate> { /** Tropospheric delay model. */ private final DiscreteTroposphericModel tropoModel; /** Constructor. * * @param model Tropospheric delay model appropriate for the current range-rate measurement method. */ public BistaticRangeRateTroposphericDelayModifier(final DiscreteTroposphericModel model) { tropoModel = model; } /** Compute the measurement error due to Troposphere. * @param station station * @param state spacecraft state * @return the measurement error due to Troposphere */ public double rangeRateErrorTroposphericModel(final GroundStation station, final SpacecraftState state) { // The effect of tropospheric correction on the range rate is // computed using finite differences. final double dt = 10; // s // spacecraft position and elevation as seen from the ground station final Vector3D position = state.getPVCoordinates().getPosition(); // elevation final double elevation1 = station.getBaseFrame().getElevation(position, state.getFrame(), state.getDate()); // only consider measures above the horizon if (elevation1 > 0) { // tropospheric delay in meters final double d1 = tropoModel.pathDelay(elevation1, station.getBaseFrame().getPoint(), tropoModel.getParameters(), state.getDate()); // propagate spacecraft state forward by dt final SpacecraftState state2 = state.shiftedBy(dt); // spacecraft position and elevation as seen from the ground station final Vector3D position2 = state2.getPVCoordinates().getPosition(); // elevation final double elevation2 = station.getBaseFrame().getElevation(position2, state2.getFrame(), state2.getDate()); // tropospheric delay dt after final double d2 = tropoModel.pathDelay(elevation2, station.getBaseFrame().getPoint(), tropoModel.getParameters(), state2.getDate()); // delay in meters per second return (d2 - d1) / dt; } return 0; } /** Compute the measurement error due to Troposphere. * @param <T> type of the element * @param station station * @param state spacecraft state * @param parameters tropospheric model parameters * @return the measurement error due to Troposphere */ public <T extends CalculusFieldElement<T>> T rangeRateErrorTroposphericModel(final GroundStation station, final FieldSpacecraftState<T> state, final T[] parameters) { // Field final Field<T> field = state.getDate().getField(); final T zero = field.getZero(); // The effect of tropospheric correction on the range rate is // computed using finite differences. final double dt = 10; // s // spacecraft position and elevation as seen from the ground station final FieldVector3D<T> position = state.getPVCoordinates().getPosition(); final T elevation1 = station.getBaseFrame().getElevation(position, state.getFrame(), state.getDate()); // only consider measures above the horizon if (elevation1.getReal() > 0) { // tropospheric delay in meters final T d1 = tropoModel.pathDelay(elevation1, station.getBaseFrame().getPoint(field), parameters, state.getDate()); // propagate spacecraft state forward by dt final FieldSpacecraftState<T> state2 = state.shiftedBy(dt); // spacecraft position and elevation as seen from the ground station final FieldVector3D<T> position2 = state2.getPVCoordinates().getPosition(); // elevation final T elevation2 = station.getBaseFrame().getElevation(position2, state2.getFrame(), state2.getDate()); // tropospheric delay dt after final T d2 = tropoModel.pathDelay(elevation2, station.getBaseFrame().getPoint(field), parameters, state2.getDate()); // delay in meters per second return (d2.subtract(d1)).divide(dt); } return zero; } /** Compute the Jacobian of the delay term wrt state using * automatic differentiation. * * @param derivatives tropospheric delay derivatives * * @return Jacobian of the delay wrt state */ private double[][] rangeRateErrorJacobianState(final double[] derivatives) { final double[][] finiteDifferencesJacobian = new double[1][6]; System.arraycopy(derivatives, 0, finiteDifferencesJacobian[0], 0, 6); return finiteDifferencesJacobian; } /** Compute the derivative of the delay term wrt parameters. * * @param station ground station * @param driver driver for the station offset parameter * @param state spacecraft state * @return derivative of the delay wrt station offset parameter */ private double rangeRateErrorParameterDerivative(final GroundStation station, final ParameterDriver driver, final SpacecraftState state) { final ParameterFunction rangeRateError = new ParameterFunction() { /** {@inheritDoc} */ @Override public double value(final ParameterDriver parameterDriver) { return rangeRateErrorTroposphericModel(station, state); } }; final ParameterFunction rangeRateErrorDerivative = Differentiation.differentiate(rangeRateError, 3, 10.0 * driver.getScale()); return rangeRateErrorDerivative.value(driver); } /** Compute the derivative of the delay term wrt parameters using * automatic differentiation. * * @param derivatives tropospheric delay derivatives * @param freeStateParameters dimension of the state. * @return derivative of the delay wrt tropospheric model parameters */ private double[] rangeRateErrorParameterDerivative(final double[] derivatives, final int freeStateParameters) { // 0 ... freeStateParameters - 1 -> derivatives of the delay wrt state // freeStateParameters ... n -> derivatives of the delay wrt tropospheric parameters final int dim = derivatives.length - freeStateParameters; final double[] rangeRateError = new double[dim]; for (int i = 0; i < dim; i++) { rangeRateError[i] = derivatives[freeStateParameters + i]; } return rangeRateError; } /** {@inheritDoc} */ @Override public List<ParameterDriver> getParametersDrivers() { return tropoModel.getParametersDrivers(); } /** {@inheritDoc} */ @Override public void modify(final EstimatedMeasurement<BistaticRangeRate> estimated) { final BistaticRangeRate measurement = estimated.getObservedMeasurement(); final GroundStation emitter = measurement.getEmitterStation(); final GroundStation receiver = measurement.getReceiverStation(); final SpacecraftState state = estimated.getStates()[0]; final double[] oldValue = estimated.getEstimatedValue(); // update estimated derivatives with Jacobian of the measure wrt state final TroposphericGradientConverter converter = new TroposphericGradientConverter(state, 6, new InertialProvider(state.getFrame())); final FieldSpacecraftState<Gradient> gState = converter.getState(tropoModel); final Gradient[] gParameters = converter.getParameters(gState, tropoModel); final Gradient delayUp = rangeRateErrorTroposphericModel(emitter, gState, gParameters); final double[] derivativesUp = delayUp.getGradient(); final Gradient delayDown = rangeRateErrorTroposphericModel(receiver, gState, gParameters); final double[] derivativesDown = delayDown.getGradient(); final double[][] djacUp = rangeRateErrorJacobianState(derivativesUp); final double[][] djacDown = rangeRateErrorJacobianState(derivativesDown); final double[][] stateDerivatives = estimated.getStateDerivatives(0); for (int irow = 0; irow < stateDerivatives.length; ++irow) { for (int jcol = 0; jcol < stateDerivatives[0].length; ++jcol) { stateDerivatives[irow][jcol] += djacUp[irow][jcol]; stateDerivatives[irow][jcol] += djacDown[irow][jcol]; } } estimated.setStateDerivatives(0, stateDerivatives); int index = 0; for (final ParameterDriver driver : getParametersDrivers()) { if (driver.isSelected()) { // update estimated derivatives with derivative of the modification wrt tropospheric parameters double parameterDerivative = estimated.getParameterDerivatives(driver)[0]; final double[] dDelayUpdP = rangeRateErrorParameterDerivative(derivativesUp, converter.getFreeStateParameters()); parameterDerivative += dDelayUpdP[index]; final double[] dDelayDowndP = rangeRateErrorParameterDerivative(derivativesDown, converter.getFreeStateParameters()); parameterDerivative += dDelayDowndP[index]; estimated.setParameterDerivatives(driver, parameterDerivative); index++; } } for (final ParameterDriver driver : Arrays.asList(emitter.getEastOffsetDriver(), emitter.getNorthOffsetDriver(), emitter.getZenithOffsetDriver())) { if (driver.isSelected()) { // update estimated derivatives with derivative of the modification wrt station parameters double parameterDerivative = estimated.getParameterDerivatives(driver)[0]; parameterDerivative += rangeRateErrorParameterDerivative(emitter, driver, state); estimated.setParameterDerivatives(driver, parameterDerivative); } } for (final ParameterDriver driver : Arrays.asList(receiver.getClockOffsetDriver(), receiver.getEastOffsetDriver(), receiver.getNorthOffsetDriver(), receiver.getZenithOffsetDriver())) { if (driver.isSelected()) { // update estimated derivatives with derivative of the modification wrt station parameters double parameterDerivative = estimated.getParameterDerivatives(driver)[0]; parameterDerivative += rangeRateErrorParameterDerivative(receiver, driver, state); estimated.setParameterDerivatives(driver, parameterDerivative); } } // update estimated value taking into account the tropospheric delay. // The tropospheric delay is directly added to the measurement. final double[] newValue = oldValue.clone(); newValue[0] += delayUp.getValue(); newValue[0] += delayDown.getValue(); estimated.setEstimatedValue(newValue); } }
3e0cb63a37c56df3a02a072ae5373987c5c2f1a1
3,455
java
Java
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/URLResource.java
githabibi/TwelveMonkeys
0809fbfba55e6a5b8c1cf31c9f30177bfc820995
[ "BSD-3-Clause" ]
1,353
2015-01-07T07:24:42.000Z
2022-03-29T08:48:27.000Z
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/URLResource.java
githabibi/TwelveMonkeys
0809fbfba55e6a5b8c1cf31c9f30177bfc820995
[ "BSD-3-Clause" ]
564
2015-01-01T08:38:41.000Z
2022-03-14T07:02:35.000Z
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/URLResource.java
githabibi/TwelveMonkeys
0809fbfba55e6a5b8c1cf31c9f30177bfc820995
[ "BSD-3-Clause" ]
267
2015-01-13T06:14:57.000Z
2022-03-30T14:31:25.000Z
38.433333
152
0.685169
5,393
/* * Copyright (c) 2008, Harald Kuhr * 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 "TwelveMonkeys" nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.twelvemonkeys.util; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; /** * URLResource class description. * * @author <a href="mailto:nnheo@example.com">Harald Kuhr</a> * @author last modified by $Author: haku $ * @version $Id: //depot/branches/personal/haraldk/twelvemonkeys/release-2/twelvemonkeys-core/src/main/java/com/twelvemonkeys/util/URLResource.java#1 $ */ final class URLResource extends AbstractResource { // NOTE: For the time being, we rely on the URL class (and helpers) to do // some smart caching and reuse of connections... // TODO: Change the implementation if this is a problem private long lastModified = -1; /** * Creates a {@code URLResource}. * * @param pResourceId the resource id * @param pURL the URL resource */ public URLResource(Object pResourceId, URL pURL) { super(pResourceId, pURL); } private URL getURL() { return (URL) wrappedResource; } public URL asURL() { return getURL(); } public InputStream asStream() throws IOException { URLConnection connection = getURL().openConnection(); connection.setAllowUserInteraction(false); connection.setUseCaches(true); return connection.getInputStream(); } public long lastModified() { try { URLConnection connection = getURL().openConnection(); connection.setAllowUserInteraction(false); connection.setUseCaches(true); connection.setIfModifiedSince(lastModified); lastModified = connection.getLastModified(); } catch (IOException ignore) { } return lastModified; } }
3e0cb6679d88115af8f3ffe648d6fff908702cd3
2,379
java
Java
src/main/java/com/chouyarn/string_33/StringBM.java
chouyarn/algo
35d2f56981d7033c7e65ea52c35fad8afa4ea2f0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/chouyarn/string_33/StringBM.java
chouyarn/algo
35d2f56981d7033c7e65ea52c35fad8afa4ea2f0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/chouyarn/string_33/StringBM.java
chouyarn/algo
35d2f56981d7033c7e65ea52c35fad8afa4ea2f0
[ "Apache-2.0" ]
null
null
null
27.034091
74
0.39008
5,394
package com.chouyarn.string_33; /** * Created by chouyarn of BI on 2019/3/11 */ public class StringBM { private static final int SIZE = 256; private void generateBC(char[] b,int m,int[] bc){ for (int i = 0;i<SIZE;++i){ bc[i] = -1; } for (int i = 0;i< m;++i){ int ascii = (int)b[i];//่ฎก็ฎ—b[i]็š„ASCIIๅ€ผ bc[ascii] = i; } } public int bm(char[] a,int n,char[] b,int m){ int[] bc = new int[SIZE];//่ฎฐๅฝ•ๆจกๅผไธฒไธญๆฏไธชๅญ—็ฌฆๆœ€ๅŽๅ‡บ็Žฐ็š„ไฝ็ฝฎ generateBC(b,m,bc);//ๆž„ๅปบๅๅญ—็ฌฆๅ“ˆๅธŒ่กจ int i = 0; while (i <= n-m){ int j; for (j = m -1;j>=0;--j){ if (a[i+j] != b[j]) break; } if (j < 0){ return i; } i = i+(j-bc[(int)a[i+j]]); } return -1; } //bๆ˜ฏๆจกๅผไธฒ๏ผŒm่กจ็คบ้•ฟๅบฆ private void generateGS(char[] b,int m,int[] suffix,boolean[] prefix){ for (int i = 0;i<m;++i){ suffix[i] = -1; prefix[i] = false; } for (int i = 0;i<m-1;++i){ int j = i; int k = 0;//ๅ…ฌๅ…ฑๅŽ็ผ€ๅญไธฒ้•ฟๅบฆ while (j >= 0 && b[j] == b[m-1-k]){//ไธŽb[0,m-1]ๆฑ‚ๅ…ฌๅ…ฑๅŽ็ผ€ๅญไธฒ --j; ++k; suffix[k] = j+1;//j+1 ่กจ็คบๅ…ฌๅ…ฑๅŽ็ผ€ๅญไธฒๅœจ b[0, i] ไธญ็š„่ตทๅง‹ไธ‹ๆ ‡ } if(j == -1) prefix[k] = true; } } //a,b่กจ็คบไธปไธฒๅ’Œๆจกๅผไธฒ๏ผ›n,m่กจ็คบไธปไธฒๅ’Œๆจกๅผไธฒ็š„้•ฟๅบฆ public int bmFinal(char[] a,int n,char[] b,int m){ int[] bc=new int[SIZE]; generateBC(b,m,bc); int[] suffix = new int[m]; boolean[] prefix = new boolean[m]; generateGS(b,m,suffix,prefix); int i = 0; while (i <= n - m){ int j; for (j = m-1;j>=0;--j){ if (a[i+j] != b[j]) break; } if (j < 0){ return i; } int x = j - bc[(int)a[i+j]]; int y = 0; if (j < m-1){ y = moveByGS(j,m,suffix,prefix); } i = i + Math.max(x,y); } return -1; } private int moveByGS(int j,int m,int[] suffix,boolean[] prefix){ int k = m -1-j; if (suffix[k] != -1) return j - suffix[k] +1; for (int r = j+2;r<= m-1;++r){ if (prefix[m-r] == true){ return r; } } return m; } }
3e0cb6ade9ae600e1c9ce20b9c9437f34b37c7ea
8,478
java
Java
TaskUnifier/TaskUnifierGui/src/main/java/com/leclercb/taskunifier/gui/components/tasks/table/highlighters/TaskTooltipHighlighter.java
geoff604/taskunifier-geoff
b754ffcdfb28f545a731a1673ecdffb5c342bbfb
[ "BSD-3-Clause" ]
1
2016-07-17T21:44:31.000Z
2016-07-17T21:44:31.000Z
TaskUnifier/TaskUnifierGui/src/main/java/com/leclercb/taskunifier/gui/components/tasks/table/highlighters/TaskTooltipHighlighter.java
geoff604/taskunifier-geoff
b754ffcdfb28f545a731a1673ecdffb5c342bbfb
[ "BSD-3-Clause" ]
null
null
null
TaskUnifier/TaskUnifierGui/src/main/java/com/leclercb/taskunifier/gui/components/tasks/table/highlighters/TaskTooltipHighlighter.java
geoff604/taskunifier-geoff
b754ffcdfb28f545a731a1673ecdffb5c342bbfb
[ "BSD-3-Clause" ]
null
null
null
30.606498
140
0.726233
5,395
/* * TaskUnifier * Copyright (c) 2013, Benjamin Leclerc * 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 TaskUnifier or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.leclercb.taskunifier.gui.components.tasks.table.highlighters; import java.awt.Component; import java.util.Calendar; import javax.swing.JComponent; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.ToolTipHighlighter; import com.leclercb.commons.api.utils.DateUtils; import com.leclercb.commons.api.utils.EqualsUtils; import com.leclercb.taskunifier.api.models.Task; import com.leclercb.taskunifier.api.models.Timer; import com.leclercb.taskunifier.gui.api.accessor.PropertyAccessor; import com.leclercb.taskunifier.gui.commons.values.StringValuePercentage; import com.leclercb.taskunifier.gui.commons.values.StringValueTime; import com.leclercb.taskunifier.gui.commons.values.StringValueTimer; import com.leclercb.taskunifier.gui.components.tasks.TaskColumnList; import com.leclercb.taskunifier.gui.translations.Translations; public class TaskTooltipHighlighter extends ToolTipHighlighter { public TaskTooltipHighlighter() { super(new TaskTooltipHighlightPredicate()); } @SuppressWarnings("unchecked") @Override protected Component doHighlight(Component renderer, ComponentAdapter adapter) { PropertyAccessor<Task> column = (PropertyAccessor<Task>) adapter.getColumnIdentifierAt(adapter.convertColumnIndexToModel(adapter.column)); if (EqualsUtils.equals( column, TaskColumnList.getInstance().get(TaskColumnList.PROGRESS))) return this.doHighlightProgress(renderer, adapter); if (EqualsUtils.equals( column, TaskColumnList.getInstance().get(TaskColumnList.LENGTH))) return this.doHighlightLength(renderer, adapter); if (EqualsUtils.equals( column, TaskColumnList.getInstance().get(TaskColumnList.TIMER))) return this.doHighlightTimer(renderer, adapter); if (EqualsUtils.equals( column, TaskColumnList.getInstance().get(TaskColumnList.START_DATE))) return this.doHighlightDate(renderer, adapter, column); if (EqualsUtils.equals( column, TaskColumnList.getInstance().get(TaskColumnList.DUE_DATE))) return this.doHighlightDate(renderer, adapter, column); return this.doHighlightString(renderer, adapter, column); } protected Component doHighlightString( Component renderer, ComponentAdapter adapter, PropertyAccessor<Task> column) { Object value = adapter.getFilteredValueAt( adapter.row, adapter.getColumnIndex(TaskColumnList.getInstance().get( TaskColumnList.MODEL))); if (value == null || !(value instanceof Task)) return renderer; final Task task = (Task) value; String toolTip = column.getPropertyAsString(task); if (toolTip != null && toolTip.trim().length() != 0) ((JComponent) renderer).setToolTipText(toolTip.trim()); return renderer; } protected Component doHighlightProgress( Component renderer, ComponentAdapter adapter) { Object value = adapter.getFilteredValueAt( adapter.row, adapter.getColumnIndex(TaskColumnList.getInstance().get( TaskColumnList.MODEL))); if (value == null || !(value instanceof Task)) return renderer; final Task task = (Task) value; int nbChildren = 0; double progress = 0; for (Task child : task.getAllChildren()) { if (!child.getModelStatus().isEndUserStatus()) continue; nbChildren++; if (child.isCompleted()) progress += 1; else progress += child.getProgress(); } String tooltip = null; if (nbChildren > 0) tooltip = String.format( "%1s (%2s: %3s)", StringValuePercentage.INSTANCE.getString(task.getProgress()), Translations.getString("general.subtasks"), StringValuePercentage.INSTANCE.getString(progress / nbChildren)); else tooltip = StringValuePercentage.INSTANCE.getString(task.getProgress()); ((JComponent) renderer).setToolTipText(tooltip); return renderer; } protected Component doHighlightLength( Component renderer, ComponentAdapter adapter) { Object value = adapter.getFilteredValueAt( adapter.row, adapter.getColumnIndex(TaskColumnList.getInstance().get( TaskColumnList.MODEL))); if (value == null || !(value instanceof Task)) return renderer; final Task task = (Task) value; boolean atLeastOneChild = false; int length = task.getLength(); for (Task child : task.getAllChildren()) { if (!child.getModelStatus().isEndUserStatus()) continue; if (child.isCompleted()) continue; atLeastOneChild = true; length += child.getLength(); } String tooltip = null; if (atLeastOneChild) tooltip = String.format( "%1s (%2s: %3s)", StringValueTime.INSTANCE.getString(task.getLength()), Translations.getString("general.total"), StringValueTime.INSTANCE.getString(length)); else tooltip = StringValueTime.INSTANCE.getString(task.getLength()); ((JComponent) renderer).setToolTipText(tooltip); return renderer; } protected Component doHighlightTimer( Component renderer, ComponentAdapter adapter) { Object value = adapter.getFilteredValueAt( adapter.row, adapter.getColumnIndex(TaskColumnList.getInstance().get( TaskColumnList.MODEL))); if (value == null || !(value instanceof Task)) return renderer; final Task task = (Task) value; boolean hasChildren = false; long timer = task.getTimer().getTimerValue(); for (Task child : task.getAllChildren()) { if (!child.getModelStatus().isEndUserStatus()) continue; if (child.isCompleted()) continue; hasChildren = true; timer += child.getTimer().getTimerValue(); } String tooltip = null; if (hasChildren) tooltip = String.format( "%1s (%2s: %3s)", StringValueTimer.INSTANCE.getString(task.getTimer()), Translations.getString("general.total"), StringValueTimer.INSTANCE.getString(new Timer(timer))); else tooltip = StringValueTimer.INSTANCE.getString(task.getTimer()); ((JComponent) renderer).setToolTipText(tooltip); return renderer; } protected Component doHighlightDate( Component renderer, ComponentAdapter adapter, PropertyAccessor<Task> column) { Object value = adapter.getFilteredValueAt( adapter.row, adapter.getColumnIndex(TaskColumnList.getInstance().get( TaskColumnList.MODEL))); if (value == null || !(value instanceof Task)) return renderer; final Task task = (Task) value; value = column.getProperty(task); if (value == null || !(value instanceof Calendar)) return renderer; String toolTip = column.getPropertyAsString(task); toolTip = String.format("%1s (%2s)", toolTip, Translations.getString( "date.x_days", Math.abs((int) DateUtils.getDiffInDays( (Calendar) value, Calendar.getInstance(), false)))); ((JComponent) renderer).setToolTipText(toolTip); return renderer; } }
3e0cb7c67169dab41fe94cf92829705771ecf14e
355
java
Java
ui/base-ui/src/main/java/org/hypothesis/interfaces/ExportScorePresenter.java
poweredonhypothesis/hypothesis
973ead7e9d53f098eaad6cf6aef4602d710ef200
[ "Apache-2.0" ]
null
null
null
ui/base-ui/src/main/java/org/hypothesis/interfaces/ExportScorePresenter.java
poweredonhypothesis/hypothesis
973ead7e9d53f098eaad6cf6aef4602d710ef200
[ "Apache-2.0" ]
11
2015-03-17T16:37:32.000Z
2017-04-24T06:56:52.000Z
ui/base-ui/src/main/java/org/hypothesis/interfaces/ExportScorePresenter.java
tilioteo/hypothesis
a50150a2e31738970f42dc140f97ccf585b4f3a2
[ "Apache-2.0" ]
null
null
null
16.136364
62
0.664789
5,396
/** * Apache Licence Version 2.0 * Please read the LICENCE file */ package org.hypothesis.interfaces; import com.vaadin.ui.Component; /** * @author Kamil Morong, Tilioteo Ltd * * Hypothesis * */ public interface ExportScorePresenter extends ViewPresenter { Component buildHeader(); Component buildContent(); }
3e0cb85a6e72b180d2bc4d9da42aca11e5b01e06
9,039
java
Java
controller/src/test/java/org/dswarm/controller/resources/resource/test/utils/ResourcesResourceTestUtils.java
dswarm/dswarm
339ef9a660ac53ff8f6064e14ce84af5b6477f01
[ "Apache-2.0" ]
47
2015-05-20T13:30:37.000Z
2021-04-29T06:53:15.000Z
controller/src/test/java/org/dswarm/controller/resources/resource/test/utils/ResourcesResourceTestUtils.java
dswarm/dswarm
339ef9a660ac53ff8f6064e14ce84af5b6477f01
[ "Apache-2.0" ]
139
2015-01-06T13:33:58.000Z
2017-12-18T09:57:43.000Z
controller/src/test/java/org/dswarm/controller/resources/resource/test/utils/ResourcesResourceTestUtils.java
dswarm/dswarm
339ef9a660ac53ff8f6064e14ce84af5b6477f01
[ "Apache-2.0" ]
16
2015-06-17T10:47:48.000Z
2021-06-22T15:35:44.000Z
42.42723
140
0.800266
5,397
/** * Copyright (C) 2013 โ€“ 2017 SLUB Dresden & Avantgarde Labs GmbH (<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. */ package org.dswarm.controller.resources.resource.test.utils; import java.io.File; import java.net.URL; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.google.common.io.Resources; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart; import org.junit.Assert; import org.dswarm.controller.resources.test.utils.ExtendedBasicDMPResourceTestUtils; import org.dswarm.persistence.model.resource.Configuration; import org.dswarm.persistence.model.resource.Resource; import org.dswarm.persistence.model.resource.proxy.ProxyResource; import org.dswarm.persistence.service.resource.ResourceService; import org.dswarm.persistence.service.resource.test.utils.ResourceServiceTestUtils; public class ResourcesResourceTestUtils extends ExtendedBasicDMPResourceTestUtils<ResourceServiceTestUtils, ResourceService, ProxyResource, Resource> { private final ConfigurationsResourceTestUtils configurationsResourceTestUtils; public ResourcesResourceTestUtils() { super("resources", Resource.class, ResourceService.class, ResourceServiceTestUtils.class); configurationsResourceTestUtils = new ConfigurationsResourceTestUtils(); } @Override public Resource createObject(final String objectJSONString, final Resource expectedObject) throws Exception { Assert.assertNotNull("resource JSON string shouldn't be null", objectJSONString); final Resource resourceFromJSON = objectMapper.readValue(objectJSONString, Resource.class); Assert.assertNotNull("resource from JSON shouldn't be null", resourceFromJSON); Assert.assertNotNull("name of resource from JSON shouldn't be null", resourceFromJSON.getName()); final URL fileURL = Resources.getResource(resourceFromJSON.getName()); final FormDataMultiPart form = new FormDataMultiPart(); form.field("name", resourceFromJSON.getName()); form.field("filename", resourceFromJSON.getName()); form.field("description", resourceFromJSON.getDescription()); form.bodyPart(new StreamDataBodyPart("file", fileURL.openStream(), resourceFromJSON.getName(), MediaType.MULTIPART_FORM_DATA_TYPE)); final Response response = target().request(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA)); Assert.assertEquals("201 CREATED was expected", 201, response.getStatus()); final String responseResourceString = response.readEntity(String.class); Assert.assertNotNull("resource shouldn't be null", responseResourceString); Resource responseResource = objectMapper.readValue(responseResourceString, Resource.class); if (resourceFromJSON.getConfigurations() != null && !resourceFromJSON.getConfigurations().isEmpty()) { // add configuration final Configuration configurationFromJSON = resourceFromJSON.getConfigurations().iterator().next(); final String configurationJSON = objectMapper.writeValueAsString(configurationFromJSON); final Response response2 = target(String.valueOf(responseResource.getUuid()), "/configurations").request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(configurationJSON)); Assert.assertEquals("201 CREATED was expected", 201, response2.getStatus()); final String responseConfigurationJSON = response2.readEntity(String.class); Assert.assertNotNull("response configuration JSON shouldn't be null", responseConfigurationJSON); final Configuration responseConfiguration = objectMapper.readValue(responseConfigurationJSON, Configuration.class); Assert.assertNotNull("response configuration shouldn't be null", responseConfiguration); configurationsResourceTestUtils.compareObjects(configurationFromJSON, responseConfiguration); // retrieve resource (with configuration) final Response response3 = target(String.valueOf(responseResource.getUuid())).request().accept(MediaType.APPLICATION_JSON_TYPE) .get(Response.class); Assert.assertEquals("200 OK was expected", 200, response3.getStatus()); final String responseResource2String = response3.readEntity(String.class); Assert.assertNotNull("response resource JSON string shouldn't be null", responseResource2String); responseResource = objectMapper.readValue(responseResource2String, Resource.class); } persistenceServiceTestUtils.compareObjects(expectedObject, responseResource); return responseResource; } public Resource uploadResource(final File resourceFile, final Resource expectedResource) throws Exception { final FormDataMultiPart form = new FormDataMultiPart(); // SR FIXME: why do we set this to hard coded values here? This leads to test failures if expectedResource does not // contain the same name values, i.e. when generating test data, one has to know that values in expectedResource must be // set to these hard coded values. form.field("name", resourceFile.getName()); form.field("filename", resourceFile.getName()); final String description; if (expectedResource != null && expectedResource.getDescription() != null) { description = expectedResource.getDescription(); } else { description = "this is a description"; } form.field("description", description); if(expectedResource != null && expectedResource.getUuid() != null) { form.field("uuid", expectedResource.getUuid()); } form.bodyPart(new FileDataBodyPart("file", resourceFile, MediaType.MULTIPART_FORM_DATA_TYPE)); final Response response = target().request(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA)); Assert.assertEquals("201 CREATED was expected", 201, response.getStatus()); final String responseResourceString = response.readEntity(String.class); Assert.assertNotNull("resource shouldn't be null", responseResourceString); final Resource responseResource = objectMapper.readValue(responseResourceString, Resource.class); persistenceServiceTestUtils.compareObjects(expectedResource, responseResource); return responseResource; } public Configuration addResourceConfiguration(final Resource resource, final String configurationJSON) throws Exception { final Response response = target(String.valueOf(resource.getUuid()), "/configurations").request(MediaType.APPLICATION_JSON_TYPE) .accept(MediaType.APPLICATION_JSON_TYPE).post(Entity.json(configurationJSON)); final String responseConfigurationJSON = response.readEntity(String.class); Assert.assertEquals("201 CREATED was expected", 201, response.getStatus()); Assert.assertNotNull("response configuration JSON shouldn't be null", responseConfigurationJSON); final Configuration responseConfiguration = objectMapper.readValue(responseConfigurationJSON, Configuration.class); Assert.assertNotNull("response configuration shouldn't be null", responseConfiguration); final Configuration configuration = objectMapper.readValue(configurationJSON, Configuration.class); configurationsResourceTestUtils.compareObjects(configuration, responseConfiguration); resource.addConfiguration(responseConfiguration); return responseConfiguration; } public String updateResource(final File resourceFile, final Resource expectedResource, final String uuid) throws Exception { final FormDataMultiPart form = new FormDataMultiPart(); form.field("name", expectedResource.getName()); form.field("description", expectedResource.getDescription()); form.bodyPart(new FileDataBodyPart("file", resourceFile, MediaType.MULTIPART_FORM_DATA_TYPE)); final Response response = target(String.valueOf(uuid)).request(MediaType.MULTIPART_FORM_DATA_TYPE).accept(MediaType.APPLICATION_JSON_TYPE) .put(Entity.entity(form, MediaType.MULTIPART_FORM_DATA)); Assert.assertEquals("200 OK was expected", 200, response.getStatus()); final String responseResourceString = response.readEntity(String.class); Assert.assertNotNull("resource shouldn't be null", responseResourceString); final Resource responseResource = objectMapper.readValue(responseResourceString, Resource.class); getPersistenceServiceTestUtils().compareObjects(expectedResource, responseResource); return responseResourceString; } }
3e0cb902b6107635bb192ccc1dc6ffe84030dbdb
511
java
Java
src/main/java/ch/solesol/pidataviewer/ScreenController.java
solesol-ch/rpi-data-viewer
fff6580052f6d7438636aaa5cf06360d83a273c0
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/solesol/pidataviewer/ScreenController.java
solesol-ch/rpi-data-viewer
fff6580052f6d7438636aaa5cf06360d83a273c0
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/solesol/pidataviewer/ScreenController.java
solesol-ch/rpi-data-viewer
fff6580052f6d7438636aaa5cf06360d83a273c0
[ "Apache-2.0" ]
null
null
null
20.44
60
0.735812
5,398
package ch.solesol.pidataviewer; import ch.solesol.pidataviewer.api.objects.DataModel; import javafx.scene.input.TouchEvent; import java.util.function.Function; public abstract class ScreenController { protected DataModel model; public Function<TouchEvent, Boolean> switchScreenAction; public void setDataModel(DataModel m){ model = m; } public abstract void refreshData(); public boolean switchScreen(TouchEvent e) { return switchScreenAction.apply(e); } }
3e0cb9864a70dc7a6cbca49e16073df18bebf557
119
java
Java
src/edu/psu/compbio/seqcode/gse/utils/io/parsing/textfiles/NDFHandler.java
shaunmahony/multigps-archive
08a3b0324025c629c8de5c2a5a2c0d56d5bf4574
[ "MIT" ]
2
2017-02-16T01:39:10.000Z
2017-10-27T08:01:33.000Z
src/edu/psu/compbio/seqcode/gse/utils/io/parsing/textfiles/NDFHandler.java
shaunmahony/multigps-archive
08a3b0324025c629c8de5c2a5a2c0d56d5bf4574
[ "MIT" ]
null
null
null
src/edu/psu/compbio/seqcode/gse/utils/io/parsing/textfiles/NDFHandler.java
shaunmahony/multigps-archive
08a3b0324025c629c8de5c2a5a2c0d56d5bf4574
[ "MIT" ]
null
null
null
29.75
63
0.831933
5,399
package edu.psu.compbio.seqcode.gse.utils.io.parsing.textfiles; public class NDFHandler extends RowsColumnsHandler {}
3e0cb99aadcd8519a6d50408f16e0ccca7914b3d
3,777
java
Java
src/main/java/com/xxkm/core/util/Pager.java
gitofwyx/xxkm_management
9182434c500660107840e297125fda861afa91d8
[ "MIT" ]
null
null
null
src/main/java/com/xxkm/core/util/Pager.java
gitofwyx/xxkm_management
9182434c500660107840e297125fda861afa91d8
[ "MIT" ]
1
2021-07-05T06:09:03.000Z
2021-07-05T06:09:03.000Z
src/main/java/com/xxkm/core/util/Pager.java
gitofwyx/xxkm_management
9182434c500660107840e297125fda861afa91d8
[ "MIT" ]
null
null
null
24.057325
124
0.516548
5,400
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.xxkm.core.util; import java.util.ArrayList; import java.util.List; /** * ๅˆ†้กตๅŽ็š„ๆ•ฐๆฎ็ป“ๆžœ * * @author Administrator */ public class Pager { private int pageSize = 10;//ๆฏ้กตๆ˜พ็คบ่ฎฐๅฝ•ๆ•ฐ private List<?> items;//ๅญ˜ๆ”พ็ป“ๆžœ้›† private int totalCount; //ๆ€ป่ฎฐๅฝ•ๆ•ฐ private int totalPage;//ๆ€ป้กตๆ•ฐ private int currentPage;//ๅฝ“ๅ‰้กต public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = (pageSize == 0) ? 10 : pageSize; } public List<?> getItems() { return items; } /* *ๅˆ†้กต็ป“ๆžœ */ @SuppressWarnings({ "rawtypes", "unchecked" }) public List<?> doPagination() { if (items == null) { throw new NullPointerException("ๆœชไผ ๅ…ฅๅฟ…้กป็š„Listๅฏน่ฑก."); } List temp = new ArrayList(); for (int i = this.getStart(); i < this.getEnd(); i++) { temp.add(items.get(i)); } return temp; } public void setItems(List<?> items) { this.items = items; } public int getTotalCount() { return totalCount; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = (currentPage == 0) ? 1 : currentPage; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getTotalPage() { if (this.pageSize == 0) { this.totalPage =0; } else if (totalCount % this.pageSize == 0) { this.totalPage = totalCount / this.pageSize; } else { this.totalPage = totalCount / this.pageSize + 1; } return this.totalPage; } /* *ๅˆ†้กต่ตทๅง‹ไฝ็ฝฎ */ public int getStart() { if (currentPage > getTotalPage()) { currentPage = 1; } return (currentPage - 1) * pageSize; } /* *ๅˆ†้กต็ป“ๆŸไฝ็ฝฎ */ public int getEnd(){ if (this.getCurrentPage() >= this.getTotalPage()) { return this.getTotalCount(); } else{ return (this.getCurrentPage()) * this.getPageSize(); } } /** * ๅˆ†้กตๅฏผ่ˆช * * @return */ public String getPagerStr() { StringBuilder sb = new StringBuilder(); int pageCount = getTotalPage();//ๆ€ป้กตๆ•ฐ int a_total = 10; //ๅˆ†้กตๆกไธญๆœ‰ๅคšๅฐ‘ไธช่ถ…้“พๆŽฅ sb.append("ๅ…ฑ" + totalCount + "ๆกๆ•ฐๆฎ ้กตๆฌก" + currentPage + "/" + pageCount + "้กต"); //ๅฎž้™…ๅบ”็”จไธญไฟฎๆ”นไธŠ้ข็ฌฌไธ‰ไธชๅ‚ๆ•ฐๅณๅฏ int a_padding = (int) Math.ceil(a_total / 2); //ไธญ้—ด็š„้‚ฃไธช่ถ…้“พๆŽฅ่ท็ฆป่พน็ผ˜้“พๆŽฅ็š„้—ด้š”a็š„ไธชๆ•ฐ ไพ‹ๅฆ‚๏ผšๅ…ฑ11ไธชๅˆ†้กต ้‚ฃไนˆ่ฟ™ไธชๅฐฑๆ˜ฏ5 if (pageCount - currentPage <= a_padding && currentPage > a_padding + 1) { a_padding = a_total - (pageCount - currentPage); } int start = currentPage - a_padding, end = start + a_total; if (currentPage - 1 > 0) { sb.append("<a href=?page=1>้ฆ–้กต</a>"); sb.append("<a href=?page=" + (currentPage - 1) + ">ไธŠไธ€้กต</a>"); } for (int i = start; i <= end; i++) { if (i <= 0) { end += Math.abs(i); i = 1; } sb.append(" <a href=?page=" + i + " " + (i == currentPage ? "style=\"color:red;\"" : "") + "> " + i + " </a> "); if (i == pageCount) { break; } } if (currentPage - pageCount < 0) { sb.append("<a href=?page=" + (currentPage + 1) + ">ไธ‹ไธ€้กต</a>"); sb.append("<a href=?page=" + pageCount + ">ๅฐพ้กต</a>"); } return sb.toString(); } }
3e0cbae229253b4a5cad7d5d9c1a4d6b09fb4a16
3,777
java
Java
src/com/clarkparsia/sbol/editor/dialog/UserInfoTab.java
clarkparsia/sbol
5b489816b567001191d8510290a44e410c95edb3
[ "Apache-2.0" ]
5
2015-06-25T00:39:45.000Z
2020-08-14T13:58:50.000Z
src/com/clarkparsia/sbol/editor/dialog/UserInfoTab.java
clarkparsia/sbol
5b489816b567001191d8510290a44e410c95edb3
[ "Apache-2.0" ]
null
null
null
src/com/clarkparsia/sbol/editor/dialog/UserInfoTab.java
clarkparsia/sbol
5b489816b567001191d8510290a44e410c95edb3
[ "Apache-2.0" ]
4
2015-10-29T20:29:56.000Z
2020-04-14T03:13:12.000Z
32.282051
104
0.740005
5,401
/* * Copyright (c) 2012 - 2015, Clark & Parsia, LLC. <http://www.clarkparsia.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.clarkparsia.sbol.editor.dialog; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; import org.openrdf.model.URI; import com.clarkparsia.sbol.editor.Images; import com.clarkparsia.sbol.editor.SBOLEditorPreferences; import com.clarkparsia.sbol.editor.dialog.PreferencesDialog.PreferencesTab; import com.clarkparsia.swing.FormBuilder; import com.clarkparsia.versioning.Infos; import com.clarkparsia.versioning.PersonInfo; import com.clarkparsia.versioning.sparql.Terms; import com.google.common.base.Strings; public enum UserInfoTab implements PreferencesTab { INSTANCE; private JTextField name; private JTextField email; private JTextField uri; @Override public String getTitle() { return "User"; } @Override public String getDescription() { return "User information added to designs"; } @Override public Icon getIcon() { return new ImageIcon(Images.getActionImage("user.gif")); } @Override public Component getComponent() { PersonInfo info = SBOLEditorPreferences.INSTANCE.getUserInfo(); FormBuilder builder = new FormBuilder(); name = builder.addTextField("Full name", info == null ? null : info.getName()); email = builder.addTextField("Email", info == null || info.getEmail() == null ? null : info.getEmail() .getLocalName()); uri = builder.addTextField("URI [Optional]", info == null ? null : info.getURI().stringValue()); JPanel formPanel = builder.build(); JButton deleteInfo = new JButton("Delete user info"); deleteInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SBOLEditorPreferences.INSTANCE.saveUserInfo(null); name.setText(null); email.setText(null); uri.setText(null); } }); deleteInfo.setAlignmentX(Component.RIGHT_ALIGNMENT); deleteInfo.setEnabled(info != null); Box buttonPanel = Box.createHorizontalBox(); buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPanel.add(Box.createHorizontalGlue()); buttonPanel.add(deleteInfo); JPanel p = new JPanel(new BorderLayout()); p.add(formPanel, BorderLayout.NORTH); p.add(buttonPanel, BorderLayout.SOUTH); return p; } @Override public void save() { boolean noURI = Strings.isNullOrEmpty(uri.getText()); boolean noName = Strings.isNullOrEmpty(name.getText()); boolean noEmail = Strings.isNullOrEmpty(email.getText()); if (!(noURI && noName && noEmail)) { URI personURI = noURI ? Terms.unique("Person") : Terms.uri(uri.getText()); String personName = noName ? null : name.getText(); URI personEmail = noEmail ? null : Terms.uri("mailto:" + email.getText()); PersonInfo info = Infos.forPerson(personURI, personName, personEmail); SBOLEditorPreferences.INSTANCE.saveUserInfo(info); } } @Override public boolean requiresRestart() { return false; } }
3e0cbb122dee3100d8b16c3bf53c78adb370fa5e
2,222
java
Java
ta4j-core/src/main/java/yang/yu/core/analysis/criteria/RewardRiskRatioCriterion.java
dayatang/ta4j
b6dfbd1437bbc78969adab452b77219b447b6dc5
[ "MIT" ]
null
null
null
ta4j-core/src/main/java/yang/yu/core/analysis/criteria/RewardRiskRatioCriterion.java
dayatang/ta4j
b6dfbd1437bbc78969adab452b77219b447b6dc5
[ "MIT" ]
null
null
null
ta4j-core/src/main/java/yang/yu/core/analysis/criteria/RewardRiskRatioCriterion.java
dayatang/ta4j
b6dfbd1437bbc78969adab452b77219b447b6dc5
[ "MIT" ]
null
null
null
40.4
116
0.756076
5,402
/** * The MIT License (MIT) * * Copyright (c) 2014-2017 Marc de Verdelhan, 2017-2019 Ta4j Organization & respective * authors (see AUTHORS) * * 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 yang.yu.core.analysis.criteria; import yang.yu.core.*; /** * Reward risk ratio criterion. * * (i.e. the {@link TotalProfitCriterion total profit} over the * {@link MaximumDrawdownCriterion maximum drawdown}. */ public class RewardRiskRatioCriterion extends AbstractAnalysisCriterion { private AnalysisCriterion totalProfit = new TotalProfitCriterion(); private AnalysisCriterion maxDrawdown = new MaximumDrawdownCriterion(); @Override public Num calculate(BarSeries series, TradingRecord tradingRecord) { return totalProfit.calculate(series, tradingRecord).dividedBy(maxDrawdown.calculate(series, tradingRecord)); } @Override public boolean betterThan(Num criterionValue1, Num criterionValue2) { return criterionValue1.isGreaterThan(criterionValue2); } @Override public Num calculate(BarSeries series, Trade trade) { return totalProfit.calculate(series, trade).dividedBy(maxDrawdown.calculate(series, trade)); } }
3e0cbc519ddd328f159202dbf9dccad3f98e8597
9,984
java
Java
plugins/mps-build/languages/build.mps.tests/source_gen/jetbrains/mps/build/mps/tests/behavior/BuildAspect_MpsTestModules__BehaviorDescriptor.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
plugins/mps-build/languages/build.mps.tests/source_gen/jetbrains/mps/build/mps/tests/behavior/BuildAspect_MpsTestModules__BehaviorDescriptor.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
plugins/mps-build/languages/build.mps.tests/source_gen/jetbrains/mps/build/mps/tests/behavior/BuildAspect_MpsTestModules__BehaviorDescriptor.java
trespasserw/MPS
dbc5c76496e8ccef46dd420eefcd5089b1bc234b
[ "Apache-2.0" ]
null
null
null
59.784431
393
0.78766
5,403
package jetbrains.mps.build.mps.tests.behavior; /*Generated by MPS */ import jetbrains.mps.core.aspects.behaviour.BaseBHDescriptor; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.core.aspects.behaviour.api.SMethod; import jetbrains.mps.core.aspects.behaviour.SMethodBuilder; import jetbrains.mps.core.aspects.behaviour.SJavaCompoundTypeImpl; import jetbrains.mps.core.aspects.behaviour.AccessPrivileges; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.build.util.VisibleArtifacts; import jetbrains.mps.build.util.RequiredDependenciesBuilder; import jetbrains.mps.scope.Scope; import java.util.List; import java.util.Arrays; import org.jetbrains.annotations.NotNull; import jetbrains.mps.internal.collections.runtime.ListSequence; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import jetbrains.mps.internal.collections.runtime.ITranslator2; import jetbrains.mps.build.mps.util.MPSModulesClosure; import jetbrains.mps.build.mps.util.ModulePlugins; import jetbrains.mps.internal.collections.runtime.ISelector; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SConceptOperations; import jetbrains.mps.lang.core.behavior.ScopeProvider__BehaviorDescriptor; import jetbrains.mps.core.aspects.behaviour.api.SConstructor; import org.jetbrains.annotations.Nullable; import jetbrains.mps.core.aspects.behaviour.api.BHMethodNotFoundException; import org.jetbrains.mps.openapi.language.SContainmentLink; import org.jetbrains.mps.openapi.language.SReferenceLink; import org.jetbrains.mps.openapi.language.SConcept; public final class BuildAspect_MpsTestModules__BehaviorDescriptor extends BaseBHDescriptor { private static final SAbstractConcept CONCEPT = MetaAdapterFactory.getConcept(0x3600cb0a44dd4a5bL, 0x996822924406419eL, 0x3f496e80bd8ef36dL, "jetbrains.mps.build.mps.tests.structure.BuildAspect_MpsTestModules"); public static final SMethod<Boolean> hasModule_id3X9rC2XzJdP = new SMethodBuilder<Boolean>(new SJavaCompoundTypeImpl(Boolean.TYPE)).name("hasModule").modifiers(0, AccessPrivileges.PUBLIC).concept(CONCEPT).id("3X9rC2XzJdP").build(SMethodBuilder.createJavaParameter((Class<SNode>) ((Class) Object.class), "")); public static final SMethod<Void> fetchDependencies_id57YmpYyL8F1 = new SMethodBuilder<Void>(new SJavaCompoundTypeImpl(Void.class)).name("fetchDependencies").modifiers(8, AccessPrivileges.PUBLIC).concept(CONCEPT).id("57YmpYyL8F1").build(SMethodBuilder.createJavaParameter(VisibleArtifacts.class, ""), SMethodBuilder.createJavaParameter(RequiredDependenciesBuilder.class, "")); public static final SMethod<Scope> getScope_id52_Geb4QDV$ = new SMethodBuilder<Scope>(new SJavaCompoundTypeImpl(Scope.class)).name("getScope").modifiers(8, AccessPrivileges.PUBLIC).concept(CONCEPT).id("52_Geb4QDV$").build(SMethodBuilder.createJavaParameter((Class<SAbstractConcept>) ((Class) Object.class), ""), SMethodBuilder.createJavaParameter((Class<SNode>) ((Class) Object.class), "")); private static final List<SMethod<?>> BH_METHODS = Arrays.<SMethod<?>>asList(hasModule_id3X9rC2XzJdP, fetchDependencies_id57YmpYyL8F1, getScope_id52_Geb4QDV$); private static void ___init___(@NotNull SNode __thisNode__) { } /*package*/ static boolean hasModule_id3X9rC2XzJdP(@NotNull SNode __thisNode__, final SNode module) { return ListSequence.fromList(SLinkOperations.getChildren(__thisNode__, LINKS.modules$V7vE)).findFirst(new IWhereFilter<SNode>() { public boolean accept(SNode it) { return (boolean) BuildMps_TestModules_Content__BehaviorDescriptor.contains_id3X9rC2XzJi8.invoke(it, module); } }) != null; } /*package*/ static void fetchDependencies_id57YmpYyL8F1(@NotNull SNode __thisNode__, VisibleArtifacts artifacts, RequiredDependenciesBuilder builder) { SNode project = artifacts.getProject(); Iterable<SNode> originalModules = ListSequence.fromList(SLinkOperations.getChildren(__thisNode__, LINKS.modules$V7vE)).translate(new ITranslator2<SNode, SNode>() { public Iterable<SNode> translate(SNode it) { return (Iterable<SNode>) BuildMps_TestModules_Content__BehaviorDescriptor.getModules_id3X9rC2XzJij.invoke(it); } }); MPSModulesClosure designtimeClosure = new MPSModulesClosure(originalModules, new MPSModulesClosure.ModuleDependenciesOptions().setTrackDevkits()).designtimeClosure(); // fetch required plugins ModulePlugins plugins = new ModulePlugins(project); List<SNode> additionalPlugins = ListSequence.fromList(SLinkOperations.getChildren(SLinkOperations.getTarget(__thisNode__, LINKS.options$gctq), LINKS.requiredPlugins$eyJB)).select(new ISelector<SNode, SNode>() { public SNode select(SNode it) { return SLinkOperations.getTarget(it, LINKS.plugin$qDpN); } }).toListSequence(); plugins.collect(designtimeClosure.getAllModules(), additionalPlugins); for (SNode plugin : Sequence.fromIterable(plugins.getDependency())) { SNode pluginArtifact = SNodeOperations.as(artifacts.findArtifact(plugin), CONCEPTS.BuildLayout_Node$Rb); if (pluginArtifact != null) { builder.add(pluginArtifact); } } // fetch modules Iterable<SNode> modules = Sequence.fromIterable(designtimeClosure.getAllModules()).union(Sequence.fromIterable(originalModules)); for (SNode m : Sequence.fromIterable(modules)) { SNode artifact; VisibleArtifacts currentArtifacts = artifacts; artifact = SNodeOperations.as(currentArtifacts.findArtifact(m), CONCEPTS.BuildLayout_Node$Rb); if (artifact != null) { builder.add(artifact); } } } /*package*/ static Scope getScope_id52_Geb4QDV$(@NotNull SNode __thisNode__, SAbstractConcept kind, SNode child) { if (SConceptOperations.isSubConceptOf(SNodeOperations.asSConcept(kind), CONCEPTS.BuildMps_AbstractModule$FZ) || SConceptOperations.isSubConceptOf(SNodeOperations.asSConcept(kind), CONCEPTS.BuildMps_Group$Jc)) { SNode project = SNodeOperations.cast(SNodeOperations.getContainingRoot(__thisNode__), CONCEPTS.BuildProject$ae); if (project != null) { return ScopeProvider__BehaviorDescriptor.getScope_id52_Geb4QFgX.invoke(project, kind, LINKS.parts$mGDj, ((int) 0)); } } return null; } /*package*/ BuildAspect_MpsTestModules__BehaviorDescriptor() { } @Override protected void initNode(@NotNull SNode node, @NotNull SConstructor constructor, @Nullable Object[] parameters) { ___init___(node); } @Override protected <T> T invokeSpecial0(@NotNull SNode node, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { case 0: return (T) ((Boolean) hasModule_id3X9rC2XzJdP(node, (SNode) parameters[0])); case 1: fetchDependencies_id57YmpYyL8F1(node, (VisibleArtifacts) parameters[0], (RequiredDependenciesBuilder) parameters[1]); return null; case 2: return (T) ((Scope) getScope_id52_Geb4QDV$(node, (SAbstractConcept) parameters[0], (SNode) parameters[1])); default: throw new BHMethodNotFoundException(this, method); } } @Override protected <T> T invokeSpecial0(@NotNull SAbstractConcept concept, @NotNull SMethod<T> method, @Nullable Object[] parameters) { int methodIndex = BH_METHODS.indexOf(method); if (methodIndex < 0) { throw new BHMethodNotFoundException(this, method); } switch (methodIndex) { default: throw new BHMethodNotFoundException(this, method); } } @NotNull @Override public List<SMethod<?>> getDeclaredMethods() { return BH_METHODS; } @NotNull @Override public SAbstractConcept getConcept() { return CONCEPT; } private static final class LINKS { /*package*/ static final SContainmentLink modules$V7vE = MetaAdapterFactory.getContainmentLink(0x3600cb0a44dd4a5bL, 0x996822924406419eL, 0x3f496e80bd8ef36dL, 0x3f496e80bd8ef370L, "modules"); /*package*/ static final SContainmentLink options$gctq = MetaAdapterFactory.getContainmentLink(0x3600cb0a44dd4a5bL, 0x996822924406419eL, 0x3f496e80bd8ef36dL, 0x5b81705cdfb31570L, "options"); /*package*/ static final SContainmentLink requiredPlugins$eyJB = MetaAdapterFactory.getContainmentLink(0x3600cb0a44dd4a5bL, 0x996822924406419eL, 0x5b81705cdfb314e0L, 0x5b81705cdf7bc31bL, "requiredPlugins"); /*package*/ static final SReferenceLink plugin$qDpN = MetaAdapterFactory.getReferenceLink(0x3600cb0a44dd4a5bL, 0x996822924406419eL, 0x5b81705cdf7bc318L, 0x5b81705cdf7bc319L, "plugin"); /*package*/ static final SContainmentLink parts$mGDj = MetaAdapterFactory.getContainmentLink(0x798100da4f0a421aL, 0xb99171f8c50ce5d2L, 0x4df58c6f18f84a13L, 0x668c6cfbafacf6f2L, "parts"); } private static final class CONCEPTS { /*package*/ static final SConcept BuildLayout_Node$Rb = MetaAdapterFactory.getConcept(0x798100da4f0a421aL, 0xb99171f8c50ce5d2L, 0x668c6cfbafac4c85L, "jetbrains.mps.build.structure.BuildLayout_Node"); /*package*/ static final SConcept BuildMps_Group$Jc = MetaAdapterFactory.getConcept(0xcf935df46994e9cL, 0xa132fa109541cba3L, 0x14d3fb6fb843ebddL, "jetbrains.mps.build.mps.structure.BuildMps_Group"); /*package*/ static final SConcept BuildMps_AbstractModule$FZ = MetaAdapterFactory.getConcept(0xcf935df46994e9cL, 0xa132fa109541cba3L, 0x4780308f5d333ebL, "jetbrains.mps.build.mps.structure.BuildMps_AbstractModule"); /*package*/ static final SConcept BuildProject$ae = MetaAdapterFactory.getConcept(0x798100da4f0a421aL, 0xb99171f8c50ce5d2L, 0x4df58c6f18f84a13L, "jetbrains.mps.build.structure.BuildProject"); } }
3e0cbd8474dd78f6ba9a86a0c4a630013f2e51f7
5,586
java
Java
src/main/java/com/xinyuow/frame/common/config/WebMvcConfiguration.java
xinyuow/xinyuow-frame
6cc1ef765b5a945f53d2dfa2fbc4613378e9e8c4
[ "Apache-2.0" ]
null
null
null
src/main/java/com/xinyuow/frame/common/config/WebMvcConfiguration.java
xinyuow/xinyuow-frame
6cc1ef765b5a945f53d2dfa2fbc4613378e9e8c4
[ "Apache-2.0" ]
1
2022-03-07T07:33:59.000Z
2022-03-29T09:30:49.000Z
src/main/java/com/xinyuow/frame/common/config/WebMvcConfiguration.java
xinyuow/xinyuow-frame
6cc1ef765b5a945f53d2dfa2fbc4613378e9e8c4
[ "Apache-2.0" ]
null
null
null
43.302326
110
0.730039
5,404
package com.xinyuow.frame.common.config; import com.alibaba.fastjson.PropertyNamingStrategy; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.ToStringSerializer; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.ByteArrayHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; /** * MVC้…็ฝฎ * * @author mxy * @date 2020/11/12 */ @Configuration public class WebMvcConfiguration implements WebMvcConfigurer { /** * ่ทจๅŸŸ่ฎพ็ฝฎ - ่ฟ‡ๆปคๅ™จๆ–นๅผๅ…ˆไบŽๆ‹ฆๆˆชๅ™จ็”Ÿๆ•ˆ * ๅ…่ฎธๆ‰€ๆœ‰็š„ๅŸŸ * ๅ…่ฎธๆ‰€ๆœ‰็š„่ฏทๆฑ‚ๅคด * ๅ…่ฎธๆ‰€ๆœ‰็š„ๆ–นๆณ• */ @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); return new CorsFilter(configSource); } /** * ้…็ฝฎ่‡ชๅฎšไน‰้™ๆ€ๆ–‡ไปถ่ฎฟ้—ฎ่ต„ๆบๆ˜ ๅฐ„ * addResourceHandler() ๆ˜ฏๅฏนๅค–ๆšด้œฒ็š„่ฎฟ้—ฎ่ทฏๅพ„ * addResourceLocations() ๆ˜ฏๆ–‡ไปถๆ”พ็ฝฎ็š„่ทฏๅพ„ */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // ้™ๆ€่ต„ๆบๆ‹ฆๆˆช registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); // ๆ”พ่กŒswagger็›ธๅ…ณ่ต„ๆบ registry.addResourceHandler("/swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/", "/static", "/public"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } /** * ้…็ฝฎๆถˆๆฏ่ฝฌๆขๅ™จ * ไฝฟ็”จAliๅผ€ๆบ็š„FastJsonๆ›ฟๆข้ป˜่ฎค็š„Jackson * * @param converters ๆถˆๆฏ่ฝฌๆขๅ™จ้›†ๅˆ */ @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { // ๅ…ˆ็งป้™ค้ป˜่ฎค็š„Jackson่ฝฌๆขๅ™จ converters.removeIf(converter -> converter instanceof MappingJackson2HttpMessageConverter); // ้œ€่ฆๅฎšไน‰ไธ€ไธชconvert่ฝฌๆขๆถˆๆฏ็š„ๅฏน่ฑก FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter(); StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter(); // ๆทปๅŠ fastJson็š„้…็ฝฎไฟกๆฏ๏ผŒๆฏ”ๅฆ‚๏ผšๆ˜ฏๅฆ่ฆๆ ผๅผๅŒ–่ฟ”ๅ›ž็š„jsonๆ•ฐๆฎ FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat, // ็ป“ๆžœๆ ผๅผๅŒ– // SerializerFeature.WriteMapNullValue, // ่พ“ๅ‡บ็ฉบๅ€ผๅญ—ๆฎต SerializerFeature.WriteNullStringAsEmpty, // Stringๅฆ‚ๆžœไธบnull๏ผŒ่พ“ๅ‡บไธบ""๏ผŒ่€Œไธๆ˜ฏnull SerializerFeature.DisableCircularReferenceDetect, // ๆถˆ้™คๅฏนๅŒไธ€ๅฏน่ฑกๅพช็Žฏๅผ•็”จ็š„้—ฎ้ข˜ SerializerFeature.WriteNullListAsEmpty, // List้›†ๅˆๅฆ‚ๆžœไธบnull๏ผŒ่พ“ๅ‡บไธบ[]๏ผŒ่€Œไธๆ˜ฏnull // SerializerFeature.BrowserCompatible, // ๅฐ†ไธญๆ–‡้ƒฝไผšๅบๅˆ—ๅŒ–ไธบ[\u0000]ๆ ผๅผ๏ผŒๅญ—่Š‚ๆ•ฐ่™ฝ็„ถไผšๅคšไธ€ไบ›๏ผŒไฝ†ๆ˜ฏ่ƒฝๅ…ผๅฎนIE 6 SerializerFeature.WriteDateUseDateFormat); // ๅ…จๅฑ€ไฟฎๆ”นๆ—ฅๆœŸๆ ผๅผ // ่ฎพ็ฝฎ็ผ–็  fastJsonConfig.setCharset(StandardCharsets.UTF_8); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); // ่ฎพ็ฝฎๆ•ฐๅญ—่ฝฌๅŒ–้—ฎ้ข˜ SerializeConfig serializeConfig = SerializeConfig.globalInstance; serializeConfig.put(BigInteger.class, ToStringSerializer.instance); serializeConfig.put(Long.class, ToStringSerializer.instance); serializeConfig.put(Long.TYPE, ToStringSerializer.instance); serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.CamelCase); serializeConfig.put(LocalDateTime.class, new AppLocalDateTimeSerializer("yyyy-MM-dd HH:mm:ss")); fastJsonConfig.setSerializeConfig(serializeConfig); // ๅค„็†ไธญๆ–‡ไนฑ็ ้—ฎ้ข˜ List<MediaType> fastMediaTypes = new ArrayList<>(); fastMediaTypes.add(MediaType.APPLICATION_JSON); fastMediaTypes.add(MediaType.TEXT_PLAIN); fastMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED); fastMediaTypes.add(MediaType.TEXT_HTML); fastMediaTypes.add(MediaType.MULTIPART_FORM_DATA); // ๅœจconvertไธญๆทปๅŠ ้…็ฝฎไฟกๆฏ fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes); fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig); // ๅฐ†convertๆทปๅŠ ๅˆฐconvertersๅฝ“ไธญ converters.add(0, fastJsonHttpMessageConverter); converters.add(0, stringHttpMessageConverter); converters.add(0, byteArrayHttpMessageConverter); } }
3e0cbf9fc93cacbd4ef9d228a278e00c5768854d
88,998
java
Java
src/main/java/signingToday/client/api/ServicesApi.java
signingtoday/signingtoday-sdk-java
1a6c6ff16a3483e66b69e78fefdfd5abd4891684
[ "MIT" ]
null
null
null
src/main/java/signingToday/client/api/ServicesApi.java
signingtoday/signingtoday-sdk-java
1a6c6ff16a3483e66b69e78fefdfd5abd4891684
[ "MIT" ]
null
null
null
src/main/java/signingToday/client/api/ServicesApi.java
signingtoday/signingtoday-sdk-java
1a6c6ff16a3483e66b69e78fefdfd5abd4891684
[ "MIT" ]
null
null
null
52.975
542
0.665476
5,405
/* * Signing Today Web * *Signing Today* is the perfect Digital Signature Gateway. Whenever in Your workflow You need to add one or more Digital Signatures to Your document, *Signing Today* is the right choice. You prepare Your documents, *Signing Today* takes care of all the rest: send invitations (`signature tickets`) to signers, collects their signatures, send You back the signed document. Integrating *Signing Today* in Your existing applications is very easy. Just follow these API specifications and get inspired by the many examples presented hereafter. * * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package signingToday.client.api; import signingToday.client.ApiCallback; import signingToday.client.ApiClient; import signingToday.client.ApiException; import signingToday.client.ApiResponse; import signingToday.client.Configuration; import signingToday.client.Pair; import signingToday.client.ProgressRequestBody; import signingToday.client.ProgressResponseBody; import com.google.gson.reflect.TypeToken; import java.io.IOException; import signingToday.client.model.ErrorResponse; import java.io.File; import signingToday.client.model.InlineObject; import signingToday.client.model.InlineObject4; import signingToday.client.model.InlineResponse200; import signingToday.client.model.ServiceFailureResponse; import java.util.UUID; import signingToday.client.model.User; import signingToday.client.model.UserSyncReport; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ServicesApi { private ApiClient localVarApiClient; public ServicesApi() { this(Configuration.getDefaultApiClient()); } public ServicesApi(ApiClient apiClient) { this.localVarApiClient = apiClient; } public ApiClient getApiClient() { return localVarApiClient; } public void setApiClient(ApiClient apiClient) { this.localVarApiClient = apiClient; } /** * Build call for authChangePasswordPost * @param passwordToken The password token issued to change password (required) * @param body New password associated to the account (BCrypt) (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authChangePasswordPostCall(String passwordToken, String body, final ApiCallback _callback) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/auth/changePassword"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (passwordToken != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("passwordToken", passwordToken)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "text/plain" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authChangePasswordPostValidateBeforeCall(String passwordToken, String body, final ApiCallback _callback) throws ApiException { // verify the required parameter 'passwordToken' is set if (passwordToken == null) { throw new ApiException("Missing the required parameter 'passwordToken' when calling authChangePasswordPost(Async)"); } // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling authChangePasswordPost(Async)"); } okhttp3.Call localVarCall = authChangePasswordPostCall(passwordToken, body, _callback); return localVarCall; } /** * Consume a token to change the password * This API allows to change the password by consuming a token. * @param passwordToken The password token issued to change password (required) * @param body New password associated to the account (BCrypt) (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void authChangePasswordPost(String passwordToken, String body) throws ApiException { authChangePasswordPostWithHttpInfo(passwordToken, body); } /** * Consume a token to change the password * This API allows to change the password by consuming a token. * @param passwordToken The password token issued to change password (required) * @param body New password associated to the account (BCrypt) (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> authChangePasswordPostWithHttpInfo(String passwordToken, String body) throws ApiException { okhttp3.Call localVarCall = authChangePasswordPostValidateBeforeCall(passwordToken, body, null); return localVarApiClient.execute(localVarCall); } /** * Consume a token to change the password (asynchronously) * This API allows to change the password by consuming a token. * @param passwordToken The password token issued to change password (required) * @param body New password associated to the account (BCrypt) (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authChangePasswordPostAsync(String passwordToken, String body, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = authChangePasswordPostValidateBeforeCall(passwordToken, body, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for authPasswordLostGet * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordLostGetCall(String username, String domain, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/auth/passwordLost"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (username != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("username", username)); } if (domain != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("domain", domain)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authPasswordLostGetValidateBeforeCall(String username, String domain, final ApiCallback _callback) throws ApiException { // verify the required parameter 'username' is set if (username == null) { throw new ApiException("Missing the required parameter 'username' when calling authPasswordLostGet(Async)"); } // verify the required parameter 'domain' is set if (domain == null) { throw new ApiException("Missing the required parameter 'domain' when calling authPasswordLostGet(Async)"); } okhttp3.Call localVarCall = authPasswordLostGetCall(username, domain, _callback); return localVarCall; } /** * Request to recover own password * This API requests to recover the own password. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void authPasswordLostGet(String username, String domain) throws ApiException { authPasswordLostGetWithHttpInfo(username, domain); } /** * Request to recover own password * This API requests to recover the own password. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> authPasswordLostGetWithHttpInfo(String username, String domain) throws ApiException { okhttp3.Call localVarCall = authPasswordLostGetValidateBeforeCall(username, domain, null); return localVarApiClient.execute(localVarCall); } /** * Request to recover own password (asynchronously) * This API requests to recover the own password. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordLostGetAsync(String username, String domain, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = authPasswordLostGetValidateBeforeCall(username, domain, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for authPasswordResetGet * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordResetGetCall(String username, String domain, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/auth/passwordReset"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (username != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("username", username)); } if (domain != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("domain", domain)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authPasswordResetGetValidateBeforeCall(String username, String domain, final ApiCallback _callback) throws ApiException { // verify the required parameter 'username' is set if (username == null) { throw new ApiException("Missing the required parameter 'username' when calling authPasswordResetGet(Async)"); } // verify the required parameter 'domain' is set if (domain == null) { throw new ApiException("Missing the required parameter 'domain' when calling authPasswordResetGet(Async)"); } okhttp3.Call localVarCall = authPasswordResetGetCall(username, domain, _callback); return localVarCall; } /** * Reset a user password with superuser * This API allows to reset the password of a user. This is possible when the request is performed with a superuser. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void authPasswordResetGet(String username, String domain) throws ApiException { authPasswordResetGetWithHttpInfo(username, domain); } /** * Reset a user password with superuser * This API allows to reset the password of a user. This is possible when the request is performed with a superuser. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> authPasswordResetGetWithHttpInfo(String username, String domain) throws ApiException { okhttp3.Call localVarCall = authPasswordResetGetValidateBeforeCall(username, domain, null); return localVarApiClient.execute(localVarCall); } /** * Reset a user password with superuser (asynchronously) * This API allows to reset the password of a user. This is possible when the request is performed with a superuser. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordResetGetAsync(String username, String domain, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = authPasswordResetGetValidateBeforeCall(username, domain, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for authPasswordResetPost * @param inlineObject4 (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordResetPostCall(InlineObject4 inlineObject4, final ApiCallback _callback) throws ApiException { Object localVarPostBody = inlineObject4; // create path and map variables String localVarPath = "/auth/passwordReset"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authPasswordResetPostValidateBeforeCall(InlineObject4 inlineObject4, final ApiCallback _callback) throws ApiException { // verify the required parameter 'inlineObject4' is set if (inlineObject4 == null) { throw new ApiException("Missing the required parameter 'inlineObject4' when calling authPasswordResetPost(Async)"); } okhttp3.Call localVarCall = authPasswordResetPostCall(inlineObject4, _callback); return localVarCall; } /** * Reset your own password * This API allows to reset your own password knowing the previous one with a logged user. * @param inlineObject4 (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void authPasswordResetPost(InlineObject4 inlineObject4) throws ApiException { authPasswordResetPostWithHttpInfo(inlineObject4); } /** * Reset your own password * This API allows to reset your own password knowing the previous one with a logged user. * @param inlineObject4 (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> authPasswordResetPostWithHttpInfo(InlineObject4 inlineObject4) throws ApiException { okhttp3.Call localVarCall = authPasswordResetPostValidateBeforeCall(inlineObject4, null); return localVarApiClient.execute(localVarCall); } /** * Reset your own password (asynchronously) * This API allows to reset your own password knowing the previous one with a logged user. * @param inlineObject4 (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordResetPostAsync(InlineObject4 inlineObject4, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = authPasswordResetPostValidateBeforeCall(inlineObject4, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for authPasswordTokenGet * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> A password token associated to the logged user. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordTokenGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/auth/passwordToken"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authPasswordTokenGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = authPasswordTokenGetCall(_callback); return localVarCall; } /** * Get token to change password * This API allows to get a password token to use in order to change a password. * @return List&lt;Object&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> A password token associated to the logged user. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public List<Object> authPasswordTokenGet() throws ApiException { ApiResponse<List<Object>> localVarResp = authPasswordTokenGetWithHttpInfo(); return localVarResp.getData(); } /** * Get token to change password * This API allows to get a password token to use in order to change a password. * @return ApiResponse&lt;List&lt;Object&gt;&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> A password token associated to the logged user. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<List<Object>> authPasswordTokenGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = authPasswordTokenGetValidateBeforeCall(null); Type localVarReturnType = new TypeToken<List<Object>>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get token to change password (asynchronously) * This API allows to get a password token to use in order to change a password. * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> A password token associated to the logged user. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authPasswordTokenGetAsync(final ApiCallback<List<Object>> _callback) throws ApiException { okhttp3.Call localVarCall = authPasswordTokenGetValidateBeforeCall(_callback); Type localVarReturnType = new TypeToken<List<Object>>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for authSamlPost * @param domain SAML domain (required) * @param idToken1 The BASE64-encoded SAML Reply in JSON (required) * @param idToken2 The Hex-encoded HMAC-SHA256 of the decoded IDToken1 (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 303 </td><td> Redirect to frontend page with new auth token (Post/Redirect/Get design pattern). </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authSamlPostCall(String domain, String idToken1, String idToken2, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/auth/saml"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); if (domain != null) { localVarFormParams.put("domain", domain); } if (idToken1 != null) { localVarFormParams.put("IDToken1", idToken1); } if (idToken2 != null) { localVarFormParams.put("IDToken2", idToken2); } final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "application/x-www-form-urlencoded" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authSamlPostValidateBeforeCall(String domain, String idToken1, String idToken2, final ApiCallback _callback) throws ApiException { // verify the required parameter 'domain' is set if (domain == null) { throw new ApiException("Missing the required parameter 'domain' when calling authSamlPost(Async)"); } // verify the required parameter 'idToken1' is set if (idToken1 == null) { throw new ApiException("Missing the required parameter 'idToken1' when calling authSamlPost(Async)"); } // verify the required parameter 'idToken2' is set if (idToken2 == null) { throw new ApiException("Missing the required parameter 'idToken2' when calling authSamlPost(Async)"); } okhttp3.Call localVarCall = authSamlPostCall(domain, idToken1, idToken2, _callback); return localVarCall; } /** * Register or Update a SAML user * This API allows to register or Update a SAML user. * @param domain SAML domain (required) * @param idToken1 The BASE64-encoded SAML Reply in JSON (required) * @param idToken2 The Hex-encoded HMAC-SHA256 of the decoded IDToken1 (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 303 </td><td> Redirect to frontend page with new auth token (Post/Redirect/Get design pattern). </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void authSamlPost(String domain, String idToken1, String idToken2) throws ApiException { authSamlPostWithHttpInfo(domain, idToken1, idToken2); } /** * Register or Update a SAML user * This API allows to register or Update a SAML user. * @param domain SAML domain (required) * @param idToken1 The BASE64-encoded SAML Reply in JSON (required) * @param idToken2 The Hex-encoded HMAC-SHA256 of the decoded IDToken1 (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 303 </td><td> Redirect to frontend page with new auth token (Post/Redirect/Get design pattern). </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> authSamlPostWithHttpInfo(String domain, String idToken1, String idToken2) throws ApiException { okhttp3.Call localVarCall = authSamlPostValidateBeforeCall(domain, idToken1, idToken2, null); return localVarApiClient.execute(localVarCall); } /** * Register or Update a SAML user (asynchronously) * This API allows to register or Update a SAML user. * @param domain SAML domain (required) * @param idToken1 The BASE64-encoded SAML Reply in JSON (required) * @param idToken2 The Hex-encoded HMAC-SHA256 of the decoded IDToken1 (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 303 </td><td> Redirect to frontend page with new auth token (Post/Redirect/Get design pattern). </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authSamlPostAsync(String domain, String idToken1, String idToken2, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = authSamlPostValidateBeforeCall(domain, idToken1, idToken2, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for authUser * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Return current logged in user </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authUserCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/auth/user"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call authUserValidateBeforeCall(final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = authUserCall(_callback); return localVarCall; } /** * Return the current logged in user * This API allows to retrieve the current logged in user. * @return User * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Return current logged in user </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public User authUser() throws ApiException { ApiResponse<User> localVarResp = authUserWithHttpInfo(); return localVarResp.getData(); } /** * Return the current logged in user * This API allows to retrieve the current logged in user. * @return ApiResponse&lt;User&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Return current logged in user </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<User> authUserWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = authUserValidateBeforeCall(null); Type localVarReturnType = new TypeToken<User>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Return the current logged in user (asynchronously) * This API allows to retrieve the current logged in user. * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Return current logged in user </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call authUserAsync(final ApiCallback<User> _callback) throws ApiException { okhttp3.Call localVarCall = authUserValidateBeforeCall(_callback); Type localVarReturnType = new TypeToken<User>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for configurationGet * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OK </td><td> - </td></tr> </table> */ public okhttp3.Call configurationGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/service/configuration"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call configurationGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = configurationGetCall(_callback); return localVarCall; } /** * Retrieve the App configuration * This API allows to get the public configuration associated to the application. * @return Map&lt;String, Object&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OK </td><td> - </td></tr> </table> */ public Map<String, Object> configurationGet() throws ApiException { ApiResponse<Map<String, Object>> localVarResp = configurationGetWithHttpInfo(); return localVarResp.getData(); } /** * Retrieve the App configuration * This API allows to get the public configuration associated to the application. * @return ApiResponse&lt;Map&lt;String, Object&gt;&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OK </td><td> - </td></tr> </table> */ public ApiResponse<Map<String, Object>> configurationGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = configurationGetValidateBeforeCall(null); Type localVarReturnType = new TypeToken<Map<String, Object>>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Retrieve the App configuration (asynchronously) * This API allows to get the public configuration associated to the application. * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OK </td><td> - </td></tr> </table> */ public okhttp3.Call configurationGetAsync(final ApiCallback<Map<String, Object>> _callback) throws ApiException { okhttp3.Call localVarCall = configurationGetValidateBeforeCall(_callback); Type localVarReturnType = new TypeToken<Map<String, Object>>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for logoutUser * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call logoutUserCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/auth/logout"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call logoutUserValidateBeforeCall(final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = logoutUserCall(_callback); return localVarCall; } /** * Log out current user terminating the session * This API allows to Log out current user. * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void logoutUser() throws ApiException { logoutUserWithHttpInfo(); } /** * Log out current user terminating the session * This API allows to Log out current user. * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> logoutUserWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = logoutUserValidateBeforeCall(null); return localVarApiClient.execute(localVarCall); } /** * Log out current user terminating the session (asynchronously) * This API allows to Log out current user. * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call logoutUserAsync(final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = logoutUserValidateBeforeCall(_callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for oauthTokenPost * @param username The username in the form _username_@_domain_ where *domain* is the organization the user belongs to (optional) * @param password This is the actual password of the user (optional) * @param grantType A parameter that indicates the type of the grant in order to perform the basic authentication (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OAuth Access Token </td><td> - </td></tr> </table> */ public okhttp3.Call oauthTokenPostCall(String username, String password, String grantType, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/oauth/token"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); if (username != null) { localVarFormParams.put("username", username); } if (password != null) { localVarFormParams.put("password", password); } if (grantType != null) { localVarFormParams.put("grant_type", grantType); } final String[] localVarAccepts = { "application/json" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "multipart/form-data" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "Basic" }; return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call oauthTokenPostValidateBeforeCall(String username, String password, String grantType, final ApiCallback _callback) throws ApiException { okhttp3.Call localVarCall = oauthTokenPostCall(username, password, grantType, _callback); return localVarCall; } /** * Get the bearer token * This API allows to get the token needed to access other APIs through the OAuth2 authentication. * @param username The username in the form _username_@_domain_ where *domain* is the organization the user belongs to (optional) * @param password This is the actual password of the user (optional) * @param grantType A parameter that indicates the type of the grant in order to perform the basic authentication (optional) * @return InlineResponse200 * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OAuth Access Token </td><td> - </td></tr> </table> */ public InlineResponse200 oauthTokenPost(String username, String password, String grantType) throws ApiException { ApiResponse<InlineResponse200> localVarResp = oauthTokenPostWithHttpInfo(username, password, grantType); return localVarResp.getData(); } /** * Get the bearer token * This API allows to get the token needed to access other APIs through the OAuth2 authentication. * @param username The username in the form _username_@_domain_ where *domain* is the organization the user belongs to (optional) * @param password This is the actual password of the user (optional) * @param grantType A parameter that indicates the type of the grant in order to perform the basic authentication (optional) * @return ApiResponse&lt;InlineResponse200&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OAuth Access Token </td><td> - </td></tr> </table> */ public ApiResponse<InlineResponse200> oauthTokenPostWithHttpInfo(String username, String password, String grantType) throws ApiException { okhttp3.Call localVarCall = oauthTokenPostValidateBeforeCall(username, password, grantType, null); Type localVarReturnType = new TypeToken<InlineResponse200>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get the bearer token (asynchronously) * This API allows to get the token needed to access other APIs through the OAuth2 authentication. * @param username The username in the form _username_@_domain_ where *domain* is the organization the user belongs to (optional) * @param password This is the actual password of the user (optional) * @param grantType A parameter that indicates the type of the grant in order to perform the basic authentication (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> OAuth Access Token </td><td> - </td></tr> </table> */ public okhttp3.Call oauthTokenPostAsync(String username, String password, String grantType, final ApiCallback<InlineResponse200> _callback) throws ApiException { okhttp3.Call localVarCall = oauthTokenPostValidateBeforeCall(username, password, grantType, _callback); Type localVarReturnType = new TypeToken<InlineResponse200>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for pdfResourceIdThumbsGet * @param id The value of _the unique id_ (required) * @param page The page to retrieve (required) * @param width The output image width (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The output is a raw string. The thumbnails of the page requested for the PDF resource. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call pdfResourceIdThumbsGetCall(UUID id, Integer page, Integer width, final ApiCallback _callback) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/pdfResource/{id}/thumbs" .replaceAll("\\{" + "id" + "\\}", localVarApiClient.escapeString(id.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } if (width != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("width", width)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "image/jpeg", "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call pdfResourceIdThumbsGetValidateBeforeCall(UUID id, Integer page, Integer width, final ApiCallback _callback) throws ApiException { // verify the required parameter 'id' is set if (id == null) { throw new ApiException("Missing the required parameter 'id' when calling pdfResourceIdThumbsGet(Async)"); } // verify the required parameter 'page' is set if (page == null) { throw new ApiException("Missing the required parameter 'page' when calling pdfResourceIdThumbsGet(Async)"); } okhttp3.Call localVarCall = pdfResourceIdThumbsGetCall(id, page, width, _callback); return localVarCall; } /** * Retrieve a Resource (of service) * This API allows to extract thumbnails from a PDF Resource. * @param id The value of _the unique id_ (required) * @param page The page to retrieve (required) * @param width The output image width (optional) * @return File * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The output is a raw string. The thumbnails of the page requested for the PDF resource. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public File pdfResourceIdThumbsGet(UUID id, Integer page, Integer width) throws ApiException { ApiResponse<File> localVarResp = pdfResourceIdThumbsGetWithHttpInfo(id, page, width); return localVarResp.getData(); } /** * Retrieve a Resource (of service) * This API allows to extract thumbnails from a PDF Resource. * @param id The value of _the unique id_ (required) * @param page The page to retrieve (required) * @param width The output image width (optional) * @return ApiResponse&lt;File&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The output is a raw string. The thumbnails of the page requested for the PDF resource. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<File> pdfResourceIdThumbsGetWithHttpInfo(UUID id, Integer page, Integer width) throws ApiException { okhttp3.Call localVarCall = pdfResourceIdThumbsGetValidateBeforeCall(id, page, width, null); Type localVarReturnType = new TypeToken<File>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Retrieve a Resource (of service) (asynchronously) * This API allows to extract thumbnails from a PDF Resource. * @param id The value of _the unique id_ (required) * @param page The page to retrieve (required) * @param width The output image width (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> The output is a raw string. The thumbnails of the page requested for the PDF resource. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 404 </td><td> The resource was not found. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call pdfResourceIdThumbsGetAsync(UUID id, Integer page, Integer width, final ApiCallback<File> _callback) throws ApiException { okhttp3.Call localVarCall = pdfResourceIdThumbsGetValidateBeforeCall(id, page, width, _callback); Type localVarReturnType = new TypeToken<File>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for serviceChangePasswordPost * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param body New password associated to the account (BCrypt) (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call serviceChangePasswordPostCall(String username, String domain, String body, final ApiCallback _callback) throws ApiException { Object localVarPostBody = body; // create path and map variables String localVarPath = "/service/changePassword"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); if (username != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("username", username)); } if (domain != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("domain", domain)); } Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "text/plain" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call serviceChangePasswordPostValidateBeforeCall(String username, String domain, String body, final ApiCallback _callback) throws ApiException { // verify the required parameter 'username' is set if (username == null) { throw new ApiException("Missing the required parameter 'username' when calling serviceChangePasswordPost(Async)"); } // verify the required parameter 'domain' is set if (domain == null) { throw new ApiException("Missing the required parameter 'domain' when calling serviceChangePasswordPost(Async)"); } // verify the required parameter 'body' is set if (body == null) { throw new ApiException("Missing the required parameter 'body' when calling serviceChangePasswordPost(Async)"); } okhttp3.Call localVarCall = serviceChangePasswordPostCall(username, domain, body, _callback); return localVarCall; } /** * Change the password of a service user * This API allows to change the password of a **service user**. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param body New password associated to the account (BCrypt) (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public void serviceChangePasswordPost(String username, String domain, String body) throws ApiException { serviceChangePasswordPostWithHttpInfo(username, domain, body); } /** * Change the password of a service user * This API allows to change the password of a **service user**. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param body New password associated to the account (BCrypt) (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<Void> serviceChangePasswordPostWithHttpInfo(String username, String domain, String body) throws ApiException { okhttp3.Call localVarCall = serviceChangePasswordPostValidateBeforeCall(username, domain, body, null); return localVarApiClient.execute(localVarCall); } /** * Change the password of a service user (asynchronously) * This API allows to change the password of a **service user**. * @param username Username associated to the account (required) * @param domain Domain associated to the account (required) * @param body New password associated to the account (BCrypt) (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 204 </td><td> The request has been satisfyied. No output. </td><td> - </td></tr> <tr><td> 409 </td><td> Cannot satisfy the request because the resource is in an illegal status. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call serviceChangePasswordPostAsync(String username, String domain, String body, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = serviceChangePasswordPostValidateBeforeCall(username, domain, body, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for serviceUsersSyncPost * @param inlineObject User Accounts (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Report of last sync. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call serviceUsersSyncPostCall(List<InlineObject> inlineObject, final ApiCallback _callback) throws ApiException { Object localVarPostBody = inlineObject; // create path and map variables String localVarPath = "/service/users/sync"; List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = { "application/json", "*/*" }; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = { "application/json" }; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); String[] localVarAuthNames = new String[] { "OAuth2" }; return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call serviceUsersSyncPostValidateBeforeCall(List<InlineObject> inlineObject, final ApiCallback _callback) throws ApiException { // verify the required parameter 'inlineObject' is set if (inlineObject == null) { throw new ApiException("Missing the required parameter 'inlineObject' when calling serviceUsersSyncPost(Async)"); } okhttp3.Call localVarCall = serviceUsersSyncPostCall(inlineObject, _callback); return localVarCall; } /** * Sync user accounts * This API allows to sync user accounts. * @param inlineObject User Accounts (required) * @return UserSyncReport * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Report of last sync. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public UserSyncReport serviceUsersSyncPost(List<InlineObject> inlineObject) throws ApiException { ApiResponse<UserSyncReport> localVarResp = serviceUsersSyncPostWithHttpInfo(inlineObject); return localVarResp.getData(); } /** * Sync user accounts * This API allows to sync user accounts. * @param inlineObject User Accounts (required) * @return ApiResponse&lt;UserSyncReport&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Report of last sync. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public ApiResponse<UserSyncReport> serviceUsersSyncPostWithHttpInfo(List<InlineObject> inlineObject) throws ApiException { okhttp3.Call localVarCall = serviceUsersSyncPostValidateBeforeCall(inlineObject, null); Type localVarReturnType = new TypeToken<UserSyncReport>(){}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Sync user accounts (asynchronously) * This API allows to sync user accounts. * @param inlineObject User Accounts (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details <table summary="Response Details" border="1"> <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> <tr><td> 200 </td><td> Report of last sync. </td><td> - </td></tr> <tr><td> 400 </td><td> Result of a client passing incorrect or invalid data. </td><td> - </td></tr> <tr><td> 401 </td><td> User authentication was not effective (e.g. not provided, invalid or expired). </td><td> - </td></tr> <tr><td> 403 </td><td> User is not allowed to perform the request. </td><td> - </td></tr> <tr><td> 500 </td><td> Internal failure of the service. </td><td> - </td></tr> </table> */ public okhttp3.Call serviceUsersSyncPostAsync(List<InlineObject> inlineObject, final ApiCallback<UserSyncReport> _callback) throws ApiException { okhttp3.Call localVarCall = serviceUsersSyncPostValidateBeforeCall(inlineObject, _callback); Type localVarReturnType = new TypeToken<UserSyncReport>(){}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } }
3e0cbfc9d28564273920f5772fca2b73955909a8
17,018
java
Java
java/src/test/java/com/ibm/watson/data/client/tests/ModelsTest.java
jgeraigery/watson-data-api-clients
7c88b7928ee8e42f0873dad76583d3f00f6c35b9
[ "Apache-2.0" ]
1
2020-12-10T13:04:10.000Z
2020-12-10T13:04:10.000Z
java/src/test/java/com/ibm/watson/data/client/tests/ModelsTest.java
IBM/watson-data-api-clients
6e123d6794424a84be214a9c874a56225e02449b
[ "Apache-2.0" ]
104
2020-10-27T16:04:59.000Z
2022-03-31T18:04:31.000Z
java/src/test/java/com/ibm/watson/data/client/tests/ModelsTest.java
jgeraigery/watson-data-api-clients
7c88b7928ee8e42f0873dad76583d3f00f6c35b9
[ "Apache-2.0" ]
5
2020-07-21T17:41:21.000Z
2021-11-15T22:22:55.000Z
45.260638
202
0.679163
5,406
/* * Copyright 2020 IBM Corp. 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.ibm.watson.data.client.tests; import com.fasterxml.jackson.core.type.TypeReference; import com.ibm.watson.data.client.api.ModelsApi; import com.ibm.watson.data.client.mocks.AbstractExpectations; import com.ibm.watson.data.client.mocks.MockConstants; import com.ibm.watson.data.client.model.*; import com.ibm.watson.data.client.model.enums.*; import org.mockserver.client.MockServerClient; import org.springframework.core.io.buffer.DataBuffer; import org.testng.annotations.Test; import reactor.core.publisher.Mono; import java.io.File; import java.nio.file.Path; import java.time.LocalDate; import java.time.Month; import java.util.*; import static com.ibm.watson.data.client.mocks.MockConstants.*; import static org.testng.Assert.*; /** * Test the Space API endpoints. */ public class ModelsTest extends AbstractExpectations { private final ModelsApi api = new ModelsApi(MockConstants.getApiClient()); public ModelsTest() { super(ModelsApi.BASE_API, "model"); } private final String attachmentId = "4d898eb8-ac1f-4486-b535-b531d358672e"; private final String modelEndpoint = "/" + MODEL_GUID; private final LocalDate version = LocalDate.of(2020, Month.DECEMBER, 22); private final Map<String, List<String>> listParams = new HashMap<>(); private final Map<String, List<String>> downloadParams1 = new HashMap<>(); private final Map<String, List<String>> downloadParams2 = new HashMap<>(); private final Map<String, List<String>> createParams = new HashMap<>(); private final Map<String, List<String>> uploadParams = new HashMap<>(); private void setupParams() { List<String> v = new ArrayList<>(); v.add(version.toString()); listParams.put("version", v); downloadParams1.put("version", v); downloadParams2.put("version", v); createParams.put("version", v); uploadParams.put("version", v); List<String> s = new ArrayList<>(); s.add(SPACE_GUID); listParams.put("space_id", s); downloadParams1.put("space_id", s); List<String> c = new ArrayList<>(); c.add("native"); uploadParams.put("content_format", c); } @Override public void init(MockServerClient client) { setupParams(); setupTest(client, "GET", "", listParams, "list"); setupTest(client, "GET", modelEndpoint, listParams, "get"); setupTest(client, "GET", modelEndpoint + "/content", listParams, "listAttachments"); setupTest(client, "POST", "", createParams, "create", 201); setupTest(client, "POST", modelEndpoint + "/revisions", createParams, "createRevision", 201); setupTest(client, "GET", modelEndpoint + "/revisions", listParams, "listRevisions"); setupTest(client, "PATCH", modelEndpoint, createParams, "update"); client .when(withRequest("GET", getBaseUrl() + modelEndpoint + "/content/" + attachmentId, getArea(), "download1").withQueryStringParameters(downloadParams1)) .respond(withResponse(getResourceFileContents(getArea() + File.separator + "download1" + File.separator + attachmentId + ".tgz")).withHeader("Content-Type", "application/octet-stream")); client .when(withRequest("GET", getBaseUrl() + modelEndpoint + "/download", getArea(), "download2").withQueryStringParameters(downloadParams2)) .respond(withResponse(getResourceFileContents(getArea() + File.separator + "download2" + File.separator + MODEL_GUID + ".tgz")).withHeader("Content-Type", "application/octet-stream")); // Note that for the upload we will test any TAR rather than a specific one, as the // MockServer is not yet easily capable of handling multi-part form requests with files client .when(withRequest("PUT", getBaseUrl() + modelEndpoint + "/content", getArea(), "upload").withQueryStringParameters(uploadParams)) .respond(withResponse(getArea(), "upload").withStatusCode(201)); setupTest(client, "DELETE", modelEndpoint + "/content/" + attachmentId, createParams, "deleteContent", 204); setupTest(client, "DELETE", modelEndpoint, createParams, "delete", 204); } @Test public void testCreate() { ModelEntityRequest body = readRequestFromFile("create", new TypeReference<ModelEntityRequest>() {}); ModelResource model = api.create(version, body).block(); validateSimpleModel(model, "This is a model to test the APIs work as expected."); } @Test public void testList() { ModelResources models = api.list(version, SPACE_GUID, null, null, null, null, null).block(); assertNotNull(models); assertNotNull(models.getFirst()); assertEquals(models.getTotalCount(), Long.valueOf(1)); assertNotNull(models.getResources()); assertEquals(models.getResources().size(), 1); validateComplexModel(models.getResources().get(0)); } @Test public void testGet() { ModelResource model = api.get(MODEL_GUID, version, SPACE_GUID, null, null).block(); validateComplexModel(model); } @Test public void testListAttachments() { AllContentMetadata response = api.listAttachments(MODEL_GUID, version, SPACE_GUID, null, null, null, null).block(); assertNotNull(response); assertEquals(response.getTotalCount(), Integer.valueOf(1)); assertNotNull(response.getAttachments()); assertEquals(response.getAttachments().size(), 1); ContentMetadata one = response.getAttachments().get(0); assertNotNull(one); assertEquals(one.getAttachmentId(), attachmentId); assertEquals(one.getContentFormat(), "native"); assertTrue(one.getPersisted()); } @Test public void testCreateRevision() { ModelRevisionEntityRequest body = readRequestFromFile("createRevision", new TypeReference<ModelRevisionEntityRequest>() {}); ModelResource model = api.createRevision(MODEL_GUID, version, body).block(); validateSimpleModel(model, "This is a model to test the APIs work as expected."); assertNotNull(model); assertNotNull(model.getMetadata()); validateSimpleModelRevision(model.getMetadata()); } @Test public void testListRevisions() { ModelResources response = api.listRevisions(MODEL_GUID, version, SPACE_GUID, null, null, null).block(); assertNotNull(response); assertNotNull(response.getFirst()); assertEquals(response.getLimit(), Integer.valueOf(100)); assertNotNull(response.getResources()); assertEquals(response.getResources().size(), 1); ModelResource one = response.getResources().get(0); assertNull(one.getEntity()); assertNull(one.getSystem()); validateSimpleModelMetadata(one.getMetadata(), "This is a model to test the APIs work as expected."); validateSimpleModelRevision(one.getMetadata()); } @Test public void testUpdate() { List<JSONResourcePatchModel> body = readRequestFromFile("update", new TypeReference<List<JSONResourcePatchModel>>() {}); ModelResource model = api.update(MODEL_GUID, version, body, SPACE_GUID, null).block(); validateSimpleModel(model, "Now with an updated description."); } @Test public void testDownload1() { Mono<DataBuffer> stream = api.download(MODEL_GUID, attachmentId, version, SPACE_GUID, null, null); validateDownload(stream); } @Test public void testDownload2() { Mono<DataBuffer> stream = api.download(MODEL_GUID, version, SPACE_GUID, null, null, null, null, null); validateDownload(stream); } @Test public void testUpload() { File tar = getFileFromResources(getArea() + File.separator + "upload" + File.separator + "request.tgz"); ContentMetadata response = api.upload(MODEL_GUID, version, "native", tar, SPACE_GUID, null, null, null).getBody(); assertNotNull(response); assertEquals(response.getAttachmentId(), attachmentId); assertEquals(response.getContentFormat(), "native"); assertTrue(response.getPersisted()); } @Test public void testDeleteContent() { api.deleteContent(MODEL_GUID, attachmentId, version, SPACE_GUID, null).block(); } @Test public void testDelete() { api.delete(MODEL_GUID, version, SPACE_GUID, null).block(); } private void validateSimpleModel(ModelResource model, String description) { assertNotNull(model); validateSimpleModelEntity(model.getEntity()); validateSimpleModelMetadata(model.getMetadata(), description); validateModelSystem(model.getSystem()); } private void validateSimpleModelEntity(ModelEntity entity) { assertNotNull(entity); assertNull(entity.getCustom()); assertNull(entity.getLabelColumn()); assertNull(entity.getSchemas()); validateSoftwareSpec(entity.getSoftwareSpec()); assertNull(entity.getTrainingDataReferences()); assertEquals(entity.getType(), "scikit-learn_0.23"); } private void validateSimpleModelMetadata(ResourceMeta metadata, String description) { assertNotNull(metadata); assertNotNull(metadata.getCreatedAt()); assertEquals(metadata.getDescription(), description); assertEquals(metadata.getId(), MODEL_GUID); assertNotNull(metadata.getModifiedAt()); assertEquals(metadata.getName(), "Test Model"); assertEquals(metadata.getOwner(), EXSTUSER_GUID); assertEquals(metadata.getSpaceId(), SPACE_GUID); } private void validateSimpleModelRevision(ResourceMeta metadata) { assertEquals(metadata.getRev(), "1"); assertNotNull(metadata.getCommitInfo()); assertNotNull(metadata.getCommitInfo().getCommittedAt()); assertEquals(metadata.getCommitInfo().getCommitMessage(), "Testing the creation of a revision via API."); } private void validateComplexModel(ModelResource model) { assertNotNull(model); validateModelEntity(model.getEntity()); validateModelMetadata(model.getMetadata()); validateModelSystem(model.getSystem()); } private void validateModelEntity(ModelEntity entity) { assertNotNull(entity); validateCustom(entity.getCustom()); assertEquals(entity.getLabelColumn(), "RISK"); validateSchemas(entity.getSchemas()); validateSoftwareSpec(entity.getSoftwareSpec()); validateTrainingDataRefs(entity.getTrainingDataReferences()); assertEquals(entity.getType(), "scikit-learn_0.23"); } private void validateModelMetadata(ResourceMeta metadata) { assertNotNull(metadata); assertNotNull(metadata.getCreatedAt()); assertEquals(metadata.getDescription(), "Consumer Credit Risk - XGB"); assertEquals(metadata.getId(), MODEL_GUID); assertNotNull(metadata.getModifiedAt()); assertEquals(metadata.getName(), "Consumer Credit Risk - XGB"); assertEquals(metadata.getOwner(), EXSTUSER_GUID); assertEquals(metadata.getSpaceId(), SPACE_GUID); } private void validateModelSystem(SystemDetails system) { assertNotNull(system); assertNotNull(system.getWarnings()); assertTrue(system.getWarnings().isEmpty()); } private void validateCustom(Map<String, Object> custom) { assertNotNull(custom); assertEquals(custom.size(), 3); assertEquals(custom.get("feedback"), "credit_risk_feedback.csv"); assertEquals(custom.get("input_data"), "structured"); assertEquals(custom.get("problem_type"), "binary"); } private void validateSchemas(FunctionEntitySchemas schemas) { assertNotNull(schemas); assertNotNull(schemas.getInput()); assertEquals(schemas.getInput().size(), 1); validateSchema(schemas.getInput().get(0)); assertNotNull(schemas.getOutput()); assertTrue(schemas.getOutput().isEmpty()); } private void validateSoftwareSpec(SoftwareSpecRel spec) { assertNotNull(spec); assertEquals(spec.getId(), "e4429883-c883-42b6-87a8-f419d64088cd"); assertEquals(spec.getName(), "default_py3.7"); } private void validateTrainingDataRefs(List<DataConnectionReference> refs) { assertNotNull(refs); assertEquals(refs.size(), 1); DataConnectionReference one = refs.get(0); assertNotNull(one); Map<String, Object> connection = one.getConnection(); assertNotNull(connection); assertEquals(connection.size(), 4); assertEquals(connection.get("api_key"), "1234567890"); assertEquals(connection.get("iam_url"), "https://iam.cloud.ibm.com/identity/token"); assertEquals(connection.get("resource_instance_id"), "crn:v1:bluemix:public:cloud-object-storage:global:a/b11ef9462fd5cd198951947913b3ccff:4e23fcd9-8d9b-4b80-86c7-196e7de4efe8::"); assertEquals(connection.get("url"), "https://s3.private.us-south.cloud-object-storage.appdomain.cloud"); assertEquals(one.getId(), "credit_risk_training.csv"); Map<String, Object> location = one.getLocation(); assertNotNull(location); assertEquals(location.size(), 4); assertEquals(location.get("bucket"), "cp4d-samples-output"); assertEquals(location.get("file_format"), "csv"); assertEquals(location.get("file_name"), "credit_risk_training.csv"); assertEquals(location.get("firstlineheader"), "true"); DataSchema schema = one.getSchema(); assertNotNull(schema); List<DataSchemaField> fields = schema.getFields(); assertNotNull(fields); assertEquals(fields.size(), 20); assertEquals(fields.get(0).getName(), "EMPLDUR"); assertEquals(fields.get(0).getType(), DataSchemaFieldType.OBJECT); assertEquals(schema.getId(), "1"); assertEquals(schema.getType(), "DataFrame"); assertEquals(one.getType(), DataConnectionType.FS); } private void validateSchema(DataSchema schema) { assertNotNull(schema); assertEquals(schema.getId(), "1"); assertEquals(schema.getType(), "struct"); List<DataSchemaField> fields = schema.getFields(); assertNotNull(fields); assertEquals(fields.size(), 20); validateStringField(fields.get(0), "EMPLDUR", 5, "less_1"); validateStringField(fields.get(1), "SEX", 2, "female"); validateNumericField(fields.get(2), "RESIDUR", 1.0, 6.0); validateStringField(fields.get(3), "OWNSPROP", 4, "car_other"); validateNumericField(fields.get(4), "AGE", 18.0, 65.0); } private void validateStringField(DataSchemaField field, String name, int totalValues, String sampleValue) { assertEquals(field.getType(), DataSchemaFieldType.STRING); assertEquals(field.getName(), name); assertNotNull(field.getMetadata()); assertEquals(field.getMetadata().getModelingRole(), DataSchemaFieldModelingRole.INPUT); if (totalValues > 0) { assertNotNull(field.getMetadata().getValues()); assertEquals(field.getMetadata().getValues().size(), totalValues); assertTrue(field.getMetadata().getValues().contains(sampleValue)); } } private void validateNumericField(DataSchemaField field, String name, Double min, Double max) { assertEquals(field.getType(), DataSchemaFieldType.DOUBLE); assertEquals(field.getName(), name); assertNotNull(field.getMetadata()); assertEquals(field.getMetadata().getModelingRole(), DataSchemaFieldModelingRole.INPUT); if (min != null && max != null) { assertNotNull(field.getMetadata().getRange()); assertEquals(field.getMetadata().getRange().getMax(), max); assertEquals(field.getMetadata().getRange().getMin(), min); } } private void validateDownload(Mono<DataBuffer> stream) { assertNotNull(stream); Path output = api.saveDownloadAsFile("download.tgz", stream); assertNotNull(output); File file = output.toFile(); assertNotNull(file); assertTrue(file.exists()); assertTrue(file.length() > 10000); assertTrue(file.delete()); } }
3e0cc01f70a01aeabcba84f16eedc860a57fbd39
3,771
java
Java
l2j_server/src/main/java/com/l2jserver/gameserver/network/clientpackets/RequestPartyMatchList.java
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
null
null
null
l2j_server/src/main/java/com/l2jserver/gameserver/network/clientpackets/RequestPartyMatchList.java
RollingSoftware/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
38
2018-02-06T17:11:29.000Z
2018-06-05T20:47:59.000Z
l2j_server/src/main/java/com/l2jserver/gameserver/network/clientpackets/RequestPartyMatchList.java
Vladislav-Zolotaryov/L2J_HighFive_Hardcore
a3c794c82c32b5afca49416119b4aafa8fb9b6d4
[ "MIT" ]
null
null
null
27.933333
116
0.714399
5,407
/* * Copyright (C) 2004-2016 L2J Server * * This file is part of L2J Server. * * L2J Server is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2J Server is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jserver.gameserver.network.clientpackets; import com.l2jserver.gameserver.model.PartyMatchRoom; import com.l2jserver.gameserver.model.PartyMatchRoomList; import com.l2jserver.gameserver.model.PartyMatchWaitingList; import com.l2jserver.gameserver.model.actor.instance.L2PcInstance; import com.l2jserver.gameserver.network.SystemMessageId; import com.l2jserver.gameserver.network.serverpackets.ExPartyRoomMember; import com.l2jserver.gameserver.network.serverpackets.PartyMatchDetail; /** * author: Gnacik */ public class RequestPartyMatchList extends L2GameClientPacket { private static final String _C__80_REQUESTPARTYMATCHLIST = "[C] 80 RequestPartyMatchList"; private int _roomid; private int _membersmax; private int _lvlmin; private int _lvlmax; private int _loot; private String _roomtitle; @Override protected void readImpl() { _roomid = readD(); _membersmax = readD(); _lvlmin = readD(); _lvlmax = readD(); _loot = readD(); _roomtitle = readS(); } @Override protected void runImpl() { L2PcInstance _activeChar = getClient().getActiveChar(); if (_activeChar == null) { return; } if (_roomid > 0) { PartyMatchRoom _room = PartyMatchRoomList.getInstance().getRoom(_roomid); if (_room != null) { _log.info("PartyMatchRoom #" + _room.getId() + " changed by " + _activeChar.getName()); _room.setMaxMembers(_membersmax); _room.setMinLvl(_lvlmin); _room.setMaxLvl(_lvlmax); _room.setLootType(_loot); _room.setTitle(_roomtitle); for (L2PcInstance _member : _room.getPartyMembers()) { if (_member == null) { continue; } _member.sendPacket(new PartyMatchDetail(_activeChar, _room)); _member.sendPacket(SystemMessageId.PARTY_ROOM_REVISED); } } } else { int _maxid = PartyMatchRoomList.getInstance().getMaxId(); PartyMatchRoom _room = new PartyMatchRoom(_maxid, _roomtitle, _loot, _lvlmin, _lvlmax, _membersmax, _activeChar); _log.info("PartyMatchRoom #" + _maxid + " created by " + _activeChar.getName()); // Remove from waiting list PartyMatchWaitingList.getInstance().removePlayer(_activeChar); PartyMatchRoomList.getInstance().addPartyMatchRoom(_maxid, _room); if (_activeChar.isInParty()) { for (L2PcInstance ptmember : _activeChar.getParty().getMembers()) { if (ptmember == null) { continue; } if (ptmember == _activeChar) { continue; } ptmember.setPartyRoom(_maxid); // ptmember.setPartyMatching(1); _room.addMember(ptmember); } } _activeChar.sendPacket(new PartyMatchDetail(_activeChar, _room)); _activeChar.sendPacket(new ExPartyRoomMember(_activeChar, _room, 1)); _activeChar.sendPacket(SystemMessageId.PARTY_ROOM_CREATED); _activeChar.setPartyRoom(_maxid); // _activeChar.setPartyMatching(1); _activeChar.broadcastUserInfo(); } } @Override public String getType() { return _C__80_REQUESTPARTYMATCHLIST; } }
3e0cc0d770c1c3d42e10e1c44d7c61e3087be517
2,218
java
Java
src/main/java/com/lys/aspect/LogAspect.java
ROY-SNN/Blog_Website
b0a7e67976f2eb6de6e71cae5d41d0a56511bb1a
[ "Apache-2.0" ]
2
2021-05-23T09:35:13.000Z
2021-12-27T05:16:49.000Z
src/main/java/com/lys/aspect/LogAspect.java
ROY-SNN/Blog_Website
b0a7e67976f2eb6de6e71cae5d41d0a56511bb1a
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lys/aspect/LogAspect.java
ROY-SNN/Blog_Website
b0a7e67976f2eb6de6e71cae5d41d0a56511bb1a
[ "Apache-2.0" ]
null
null
null
33.104478
117
0.616772
5,408
package com.lys.aspect; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; @Aspect @Component public class LogAspect { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Pointcut("execution(* com.lys.web.*.*(..))") public void log(){} @Before("log()") public void doBefore(JoinPoint joinPoint){ ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String url = request.getRequestURL().toString(); String ip = request.getRemoteAddr(); String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName(); Object[] args = joinPoint.getArgs(); RequsetLog requsetLog = new RequsetLog(url, ip, classMethod, args); logger.info("Request:{}",requsetLog); } @After("log()") public void doAfter(){ // logger.info("----------------doAfter"); } @AfterReturning(returning = "result",pointcut = "log()") public void doAfterReturn(Object result){ logger.info("Result : {}",result); } private class RequsetLog{ private String url; private String ip; private String classMethod; private Object[] args; public RequsetLog(String url, String ip, String classMethod, Object[] args) { this.url = url; this.ip = ip; this.classMethod = classMethod; this.args = args; } @Override public String toString() { return "{" + "url='" + url + '\'' + ", ip='" + ip + '\'' + ", classMethod='" + classMethod + '\'' + ", args=" + Arrays.toString(args) + '}'; } } }
3e0cc1d4853689280a35b4588c26c71691ab65c0
582
java
Java
Curso_em_video_POO_para_JAVA/Aula_06_Encapsulamento/Controlador.java
antoniosereno95/Exercios_Resolvidos_Java_e_POO
12025eb9ba4c17032fb3b3baea6395ebee151f7b
[ "MIT" ]
null
null
null
Curso_em_video_POO_para_JAVA/Aula_06_Encapsulamento/Controlador.java
antoniosereno95/Exercios_Resolvidos_Java_e_POO
12025eb9ba4c17032fb3b3baea6395ebee151f7b
[ "MIT" ]
null
null
null
Curso_em_video_POO_para_JAVA/Aula_06_Encapsulamento/Controlador.java
antoniosereno95/Exercios_Resolvidos_Java_e_POO
12025eb9ba4c17032fb3b3baea6395ebee151f7b
[ "MIT" ]
null
null
null
27.714286
52
0.701031
5,409
package Aula_06_Encapsulamento; public interface Controlador { public abstract void ligar(); public abstract void desligar(); public abstract void abrirMenu(); public abstract void fecharMenu(); public abstract void maisVolume(); public abstract void menosVolume(); public abstract void ligarMudo(); public abstract void desligarMudo(); public abstract void play(); public abstract void pause(); //nem sempre o tipo dos metodos precisa ser void // mas nesse exemplo pra ficar mais facil ficou // tudo no void mesmo. }
3e0cc321e6588695768737cd6d08118aee03e5c4
936
java
Java
GoGame/src/main/java/tp_project/GoGameDBObject/DBGoBoard.java
artur00231/Project-TP
046e7f1e2aa630e1e2ad94c65278419bbdebf660
[ "MIT" ]
null
null
null
GoGame/src/main/java/tp_project/GoGameDBObject/DBGoBoard.java
artur00231/Project-TP
046e7f1e2aa630e1e2ad94c65278419bbdebf660
[ "MIT" ]
10
2019-12-03T20:45:30.000Z
2021-12-29T16:49:12.000Z
GoGame/src/main/java/tp_project/GoGameDBObject/DBGoBoard.java
artur00231/Project-TP
046e7f1e2aa630e1e2ad94c65278419bbdebf660
[ "MIT" ]
null
null
null
24.631579
55
0.701923
5,410
package tp_project.GoGameDBObject; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import tp_project.GoGame.GoBoard; @Entity(name = "board") public class DBGoBoard { @Column(name = "board") public String row_board; @Column(name = "round_number") public int round_number; @Column(name = "game_id") public int game_id; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; public DBGoBoard() {} public DBGoBoard createNext(GoBoard next_board) { DBGoBoard next_DBGoBoard = new DBGoBoard(); next_DBGoBoard.game_id = game_id; next_DBGoBoard.row_board = next_board.toText(); next_DBGoBoard.round_number = round_number + 1; return next_DBGoBoard; } public int getID() { return id; } }
3e0cc33b220e4f655758402cf6ec7c3bbc698eff
3,859
java
Java
src/main/java/org/thymeleaf/standard/expression/GreaterOrEqualToExpression.java
e-green/thymeleaf
e858dc8e1d74cfa67be99e0398343744393bd793
[ "Apache-2.0" ]
1
2019-11-16T02:24:18.000Z
2019-11-16T02:24:18.000Z
src/main/java/org/thymeleaf/standard/expression/GreaterOrEqualToExpression.java
e-green/thymeleaf
e858dc8e1d74cfa67be99e0398343744393bd793
[ "Apache-2.0" ]
null
null
null
src/main/java/org/thymeleaf/standard/expression/GreaterOrEqualToExpression.java
e-green/thymeleaf
e858dc8e1d74cfa67be99e0398343744393bd793
[ "Apache-2.0" ]
1
2019-11-16T02:24:17.000Z
2019-11-16T02:24:17.000Z
37.833333
145
0.641099
5,411
/* * ============================================================================= * * Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ============================================================================= */ package org.thymeleaf.standard.expression; import java.math.BigDecimal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.thymeleaf.Configuration; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.IProcessingContext; import org.thymeleaf.exceptions.TemplateProcessingException; import org.thymeleaf.util.EvaluationUtil; /** * * @author Daniel Fern&aacute;ndez * * @since 1.1 * */ public final class GreaterOrEqualToExpression extends GreaterLesserExpression { private static final long serialVersionUID = 4318966518910979010L; private static final Logger logger = LoggerFactory.getLogger(GreaterOrEqualToExpression.class); public GreaterOrEqualToExpression(final IStandardExpression left, final IStandardExpression right) { super(left, right); } @Override public String getStringRepresentation() { return getStringRepresentation(GREATER_OR_EQUAL_TO_OPERATOR); } @SuppressWarnings("unchecked") static Object executeGreaterOrEqualTo(final Configuration configuration, final IProcessingContext processingContext, final GreaterOrEqualToExpression expression, final StandardExpressionExecutionContext expContext) { Object leftValue = expression.getLeft().execute(configuration, processingContext, expContext); Object rightValue = expression.getRight().execute(configuration, processingContext, expContext); leftValue = LiteralValue.unwrap(leftValue); rightValue = LiteralValue.unwrap(rightValue); Boolean result = null; final BigDecimal leftNumberValue = EvaluationUtil.evaluateAsNumber(leftValue); final BigDecimal rightNumberValue = EvaluationUtil.evaluateAsNumber(rightValue); if (leftNumberValue != null && rightNumberValue != null) { result = Boolean.valueOf(leftNumberValue.compareTo(rightNumberValue) != -1); } else { if (leftValue != null && rightValue != null && leftValue.getClass().equals(rightValue.getClass()) && Comparable.class.isAssignableFrom(leftValue.getClass())) { result = Boolean.valueOf(((Comparable<Object>)leftValue).compareTo(rightValue) >= 0); } else { throw new TemplateProcessingException( "Cannot execute GREATER OR EQUAL TO from Expression \"" + expression.getStringRepresentation() + "\". Left is \"" + leftValue + "\", right is \"" + rightValue + "\""); } } if (logger.isTraceEnabled()) { logger.trace("[THYMELEAF][{}] Evaluating GREATER OR EQUAL TO expression: \"{}\". Left is \"{}\", right is \"{}\". Result is \"{}\"", new Object[] {TemplateEngine.threadIndex(), expression.getStringRepresentation(), leftValue, rightValue, result}); } return result; } }
3e0cc38abc840104b284cb3934083683e130f7bf
10,314
java
Java
src/net/sourceforge/docfetcher/model/index/outlook/OutlookIndex.java
docfetcher/DocFetcher
42f2accd840edc5059060447ed3536aa4d54b5d3
[ "Apache-2.0" ]
24
2018-07-22T13:02:53.000Z
2022-02-02T16:45:29.000Z
src/net/sourceforge/docfetcher/model/index/outlook/OutlookIndex.java
docfetcher/DocFetcher
42f2accd840edc5059060447ed3536aa4d54b5d3
[ "Apache-2.0" ]
null
null
null
src/net/sourceforge/docfetcher/model/index/outlook/OutlookIndex.java
docfetcher/DocFetcher
42f2accd840edc5059060447ed3536aa4d54b5d3
[ "Apache-2.0" ]
5
2018-12-29T10:38:03.000Z
2021-02-06T15:29:03.000Z
34.265781
93
0.696141
5,412
/******************************************************************************* * Copyright (c) 2010, 2011 Tran Nam Quang. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tran Nam Quang - initial API and implementation *******************************************************************************/ package net.sourceforge.docfetcher.model.index.outlook; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.sourceforge.docfetcher.model.Cancelable; import net.sourceforge.docfetcher.model.DocumentType; import net.sourceforge.docfetcher.model.Path; import net.sourceforge.docfetcher.model.TreeIndex; import net.sourceforge.docfetcher.model.UtilModel; import net.sourceforge.docfetcher.model.index.IndexWriterAdapter; import net.sourceforge.docfetcher.model.index.IndexingError; import net.sourceforge.docfetcher.model.index.IndexingError.ErrorType; import net.sourceforge.docfetcher.model.index.IndexingException; import net.sourceforge.docfetcher.model.index.IndexingReporter; import net.sourceforge.docfetcher.util.Util; import net.sourceforge.docfetcher.util.annotations.NotNull; import net.sourceforge.docfetcher.util.annotations.Nullable; import net.sourceforge.docfetcher.util.annotations.RecursiveMethod; import com.google.common.collect.Maps; import com.google.common.io.Closeables; import com.pff.PSTException; import com.pff.PSTFile; import com.pff.PSTFolder; import com.pff.PSTMessage; import com.pff.PSTObject; /** * @author Tran Nam Quang */ public final class OutlookIndex extends TreeIndex<MailDocument, MailFolder> { /* * Tests indicate we can directly retrieve any message via its ID, but not * attachments. This means in order to retrieve an attachment, we'll have to * fetch its message first. * * Tests also indicate that nothing serious happens if we read a PST file * that is currently open in Outlook. Since we're only reading the PST file, * the worst that could happen is to get some garbage out of the PST file, * as a result of Outlook writing to it concurrently. */ private static final long serialVersionUID = 1L; private MailFolder simplifiedRootFolder; public OutlookIndex(@Nullable File indexParentDir, @NotNull File pstFile) { super(indexParentDir, pstFile); } @NotNull protected String getIndexDirName(@NotNull File pstFile) { return Util.splitFilename(pstFile)[0]; } @NotNull protected MailFolder createRootFolder(@NotNull Path path) { return new MailFolder(path); } public boolean isEmailIndex() { return true; } public DocumentType getDocumentType() { return DocumentType.OUTLOOK; } public IndexingResult doUpdate( @NotNull IndexingReporter reporter, @NotNull Cancelable cancelable) { reporter.setStartTime(System.currentTimeMillis()); MailFolder rootFolder = getRootFolder(); rootFolder.setError(null); IndexWriterAdapter writer = null; PSTFile pstFile = null; try { /* * Return immediately if the last-modified field of the PST file * hasn't changed. */ File rootFile = getCanonicalRootFile(); long newLastModified = rootFile.lastModified(); if (UtilModel.isUnmodifiedArchive(rootFolder, newLastModified)) return IndexingResult.SUCCESS_UNCHANGED; rootFolder.setLastModified(newLastModified); writer = new IndexWriterAdapter(getLuceneDir()); OutlookContext context = new OutlookContext( getConfig(), writer, reporter, cancelable ); pstFile = new PSTFile(rootFile.getPath()); visitFolder(context, rootFolder, pstFile.getRootFolder()); simplifiedRootFolder = new TreeRootSimplifier<MailFolder> () { protected boolean hasContent(MailFolder node) { return node.getDocumentCount() > 0; } protected boolean hasDeepContent(MailFolder node) { return node.hasDeepContent(); } protected Collection<MailFolder> getChildren(MailFolder node) { return node.getSubFolders(); } }.getSimplifiedRoot(getRootFolder()); return IndexingResult.SUCCESS_CHANGED; } catch (PSTException e) { report(reporter, e); } catch (IOException e) { report(reporter, e); } catch (IndexingException e) { report(reporter, e.getIOException()); } finally { if (pstFile != null) { Closeables.closeQuietly(pstFile.getFileHandle()); } Closeables.closeQuietly(writer); reporter.setEndTime(System.currentTimeMillis()); } return IndexingResult.FAILURE; } private void report(@NotNull IndexingReporter reporter, @NotNull Exception e) { MailFolder rootFolder = getRootFolder(); IndexingError error = new IndexingError( ErrorType.IO_EXCEPTION, rootFolder, e); rootFolder.setError(error); reporter.fail(error); } // TODO post-release-1.1: method currently not in use @NotNull public MailFolder getSimplifiedRootFolder() { if (simplifiedRootFolder == null) // update method hasn't been called yet return getRootFolder(); return simplifiedRootFolder; } // TODO doc: stores in the given folder whether it has 'deep' content or not. @RecursiveMethod private static void visitFolder(@NotNull OutlookContext context, @NotNull MailFolder folder, @NotNull PSTFolder pstFolder) throws IndexingException, PSTException { folder.setHasDeepContent(false); final Map<String, MailDocument> unseenMails = Maps.newHashMap(folder.getDocumentMap()); final Map<String, MailFolder> unseenSubFolders = Maps.newHashMap(folder.getSubFolderMap()); final List<PSTFolder> subFoldersToVisit = new LinkedList<PSTFolder>(); // Visit mails if (pstFolder.getContentCount() > 0) { try { PSTObject pstObject; try { pstObject = pstFolder.getNextChild(); } catch (IndexOutOfBoundsException e) { // Bug #374. See similar bugfix inside the following loop. Util.printErr(e.getMessage()); pstObject = null; // skip following loop } while (pstObject != null) { if (context.isStopped()) break; /* * Bug #3561223: The documentation for java-libpst 0.7 * indicates we can expect the PST object to be an instance * of PSTMessage. However, a bug report has shown that it * may also be a PSTFolder, probably in some very rare * cases. */ if (pstObject instanceof PSTFolder) { subFoldersToVisit.add((PSTFolder) pstObject); } else if (pstObject instanceof PSTMessage) { /* * Note: The user should not be allowed to stop the * indexing in the middle of email processing (e.g. * between attachments), otherwise we could end up * indexing emails which have only one half of all * attachments, which would complicate email * modification detection. */ /* * Note: For the email UID, we'll use the 'descriptor * node ID' rather than the 'internet message ID', for * several reasons: (1) Not every email has an internet * message ID, e.g. unsent emails. (2) The descriptor * node ID is only an internal ID used by Outlook, but * it does not change. (3) The descriptor node ID allows * fast retrieval of single emails, which is what we * need for the preview. */ PSTMessage pstMail = (PSTMessage) pstObject; String id = String.valueOf(pstMail.getDescriptorNodeId()); Date newLastModDate = pstMail.getLastModificationTime(); // Bug #397: The last-modification date can be null long newLastMod = newLastModDate == null ? 0 : newLastModDate.getTime(); MailDocument mail = unseenMails.remove(id); if (mail == null) { // Mail added String subject = pstMail.getSubject(); mail = new MailDocument( folder, id, subject, newLastMod); context.index(mail, pstMail, true); } else if (mail.isModified(newLastMod)) { // Mail modified /* * Note: Outlook mails are not immutable, because * Outlook allows modifying the subject and body, as * well as removing attachments. Such modifications * will alter the last-modified value as provided by * the PSTMessage object. It is not clear though * whether any other changes are possible, and if * so, whether we can rely on the last-modified * value to reflect such changes. */ mail.setLastModified(newLastMod); context.index(mail, pstMail, false); } } try { pstObject = pstFolder.getNextChild(); } catch (IndexOutOfBoundsException e) { /* * Temporary fix for bug #3489947. Affects java-libpst * v0.5 and probably also v0.7. */ Util.printErr(e.getMessage()); pstObject = null; // get out of loop } } } catch (IOException e) { throw new IndexingException(e); } folder.setHasDeepContent(true); } // Visit subfolders if (pstFolder.hasSubfolders() || !subFoldersToVisit.isEmpty()) { try { subFoldersToVisit.addAll(pstFolder.getSubFolders()); for (PSTFolder pstSubFolder : subFoldersToVisit) { if (context.isStopped()) break; String foldername = pstSubFolder.getDisplayName(); MailFolder subFolder = unseenSubFolders.remove(foldername); if (subFolder == null) subFolder = new MailFolder(folder, foldername); visitFolder(context, subFolder, pstSubFolder); if (subFolder.hasDeepContent()) folder.setHasDeepContent(true); } } catch (IOException e) { throw new IndexingException(e); } } if (context.isStopped()) return; // Handle missing mails and folders for (MailDocument mail : unseenMails.values()) { /* * Bug #3475969: The UID must be retrieved *before* detaching the * document from its parent, as constructing the UID requires * accessing the parent. */ context.deleteFromIndex(mail.getUniqueId()); folder.removeDocument(mail); } for (MailFolder subFolder : unseenSubFolders.values()) folder.removeSubFolder(subFolder); } }
3e0cc48c24044bbfcfb4cb528215d48a57927445
732
java
Java
app/src/main/java/com/google/android/libraries/feed/host/logging/LoggingApi.java
DESUP2/WEB-BROWSER-sdk31
64b40144c9c2afc2dfc727731dc9a9b762fd94cb
[ "Apache-2.0" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
app/src/main/java/com/google/android/libraries/feed/host/logging/LoggingApi.java
DESUP2/WEB-BROWSER-sdk31
64b40144c9c2afc2dfc727731dc9a9b762fd94cb
[ "Apache-2.0" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
app/src/main/java/com/google/android/libraries/feed/host/logging/LoggingApi.java
DESUP2/WEB-BROWSER-sdk31
64b40144c9c2afc2dfc727731dc9a9b762fd94cb
[ "Apache-2.0" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
38.526316
75
0.748634
5,413
// Copyright 2018 The Feed Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.feed.host.logging; /** A placeholder API to write log messages. */ public interface LoggingApi {}
3e0cc4b2af5c4fdb00f5250175ba786d8773a69b
1,516
java
Java
src/main/java/com/blastedstudios/gdxworld/plugin/quest/manifestation/endlevel/EndLevelManifestation.java
narfman0/GDXWorld
a5e0ca6d9237ccbcf2e710ba8f4aaa8c1b0c2c59
[ "Beerware" ]
20
2015-01-21T20:20:12.000Z
2020-12-13T15:06:23.000Z
src/main/java/com/blastedstudios/gdxworld/plugin/quest/manifestation/endlevel/EndLevelManifestation.java
narfman0/GDXWorld
a5e0ca6d9237ccbcf2e710ba8f4aaa8c1b0c2c59
[ "Beerware" ]
4
2015-10-06T20:45:16.000Z
2015-10-13T02:04:19.000Z
src/main/java/com/blastedstudios/gdxworld/plugin/quest/manifestation/endlevel/EndLevelManifestation.java
narfman0/GDXWorld
a5e0ca6d9237ccbcf2e710ba8f4aaa8c1b0c2c59
[ "Beerware" ]
7
2017-03-02T05:11:41.000Z
2020-12-13T20:02:59.000Z
29.72549
88
0.781003
5,414
package com.blastedstudios.gdxworld.plugin.quest.manifestation.endlevel; import com.blastedstudios.gdxworld.util.PluginUtil; import com.blastedstudios.gdxworld.world.quest.QuestStatus.CompletionEnum; import com.blastedstudios.gdxworld.world.quest.manifestation.AbstractQuestManifestation; public class EndLevelManifestation extends AbstractQuestManifestation { private static final long serialVersionUID = 1L; public static EndLevelManifestation DEFAULT = new EndLevelManifestation(true, ""); private boolean success; private String nextLevel = ""; public EndLevelManifestation(){} public EndLevelManifestation(boolean success, String nextLevel){ this.success = success; this.nextLevel = nextLevel; } @Override public CompletionEnum execute(float dt) { for(IEndLevelHandler handler : PluginUtil.getPlugins(IEndLevelHandler.class)) if(handler.endLevel(success, nextLevel) == CompletionEnum.COMPLETED) return CompletionEnum.COMPLETED; return CompletionEnum.EXECUTING; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } @Override public AbstractQuestManifestation clone() { return new EndLevelManifestation(success, nextLevel); } @Override public String toString() { return "[EndLevelManifestation: success:" + success+"]"; } public String getNextLevel() { return nextLevel == null ? nextLevel = "" : nextLevel; } public void setNextLevel(String nextLevel) { this.nextLevel = nextLevel; } }
3e0cc4be69e1911f0289decfdda1f4e64c4b50ce
300
java
Java
src/application/CalModel.java
jo2544/-
0cbf109391ec212f4eb13a8d91065bc0d1c3b86c
[ "MIT" ]
null
null
null
src/application/CalModel.java
jo2544/-
0cbf109391ec212f4eb13a8d91065bc0d1c3b86c
[ "MIT" ]
null
null
null
src/application/CalModel.java
jo2544/-
0cbf109391ec212f4eb13a8d91065bc0d1c3b86c
[ "MIT" ]
null
null
null
15
50
0.496667
5,415
package application; public class CalModel { public int calculate(String op, int x, int y) { int result = 0; if(op == "+") { result = x + y; } else if(op == "-") { result = x - y; } else if(op == "*") { result = x * y; } else { result = x / y; } return result; } }
3e0cc4ed086f8d39adf82515a17cfaa9670fbdc0
209
java
Java
src/main/java/mezz/jei/runtime/package-info.java
Speiger/JustEnoughItems
9d0dcbd917ec0573a79eba21c41222e5862b5e7a
[ "MIT" ]
613
2015-02-16T06:51:24.000Z
2022-03-31T18:30:09.000Z
src/main/java/mezz/jei/runtime/package-info.java
MORIMORI0317/JustEnoughItems
30d8cfc1adeadc2d0b0aa2b80495780efc7cb641
[ "MIT" ]
2,698
2015-04-07T01:53:03.000Z
2022-03-30T21:45:28.000Z
src/main/java/mezz/jei/runtime/package-info.java
MORIMORI0317/JustEnoughItems
30d8cfc1adeadc2d0b0aa2b80495780efc7cb641
[ "MIT" ]
475
2015-11-24T01:33:38.000Z
2022-03-30T15:27:47.000Z
26.125
57
0.894737
5,416
@ParametersAreNonnullByDefault @FieldsAndMethodsAreNonnullByDefault package mezz.jei.runtime; import javax.annotation.ParametersAreNonnullByDefault; import mezz.jei.util.FieldsAndMethodsAreNonnullByDefault;
3e0cc5f019cf96664542e76b7035681ffca89016
1,237
java
Java
SQLPlugin/gen/com/sqlplugin/psi/impl/SqlSelectListImpl.java
smoothwind/SQL-IDEAplugin
3efa434095b4cac4772a0a7df18b34042a4c7557
[ "MIT" ]
null
null
null
SQLPlugin/gen/com/sqlplugin/psi/impl/SqlSelectListImpl.java
smoothwind/SQL-IDEAplugin
3efa434095b4cac4772a0a7df18b34042a4c7557
[ "MIT" ]
null
null
null
SQLPlugin/gen/com/sqlplugin/psi/impl/SqlSelectListImpl.java
smoothwind/SQL-IDEAplugin
3efa434095b4cac4772a0a7df18b34042a4c7557
[ "MIT" ]
null
null
null
25.770833
86
0.76637
5,417
// This is a generated file. Not intended for manual editing. package com.sqlplugin.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.sqlplugin.psi.SqlTypes.*; import com.intellij.extapi.psi.ASTWrapperPsiElement; import com.sqlplugin.psi.*; public class SqlSelectListImpl extends ASTWrapperPsiElement implements SqlSelectList { public SqlSelectListImpl(@NotNull ASTNode node) { super(node); } public void accept(@NotNull SqlVisitor visitor) { visitor.visitSelectList(this); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof SqlVisitor) accept((SqlVisitor)visitor); else super.accept(visitor); } @Override @Nullable public SqlAsterisk getAsterisk() { return findChildByClass(SqlAsterisk.class); } @Override @Nullable public SqlComma getComma() { return findChildByClass(SqlComma.class); } @Override @NotNull public List<SqlSelectSublist> getSelectSublistList() { return PsiTreeUtil.getChildrenOfTypeAsList(this, SqlSelectSublist.class); } }
3e0cc5f282d8e9bf77e1ad35140235062a41adb3
5,509
java
Java
src/main/java/co/lilpilot/blog/security/JwtTokenUtil.java
sunguangsg/blogDemo
4858ecd9a3748c178f9b90e257cbf4ddf2e43d14
[ "MIT" ]
13
2017-05-01T14:36:14.000Z
2018-04-16T11:06:30.000Z
src/main/java/co/lilpilot/blog/security/JwtTokenUtil.java
sunguangsg/blogDemo
4858ecd9a3748c178f9b90e257cbf4ddf2e43d14
[ "MIT" ]
null
null
null
src/main/java/co/lilpilot/blog/security/JwtTokenUtil.java
sunguangsg/blogDemo
4858ecd9a3748c178f9b90e257cbf4ddf2e43d14
[ "MIT" ]
2
2017-07-02T02:27:40.000Z
2019-05-15T09:09:41.000Z
33.186747
106
0.635506
5,418
package co.lilpilot.blog.security; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.mobile.device.Device; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Created by lilpilot on 2017/5/2. */ @Component public class JwtTokenUtil { static final String CLAIM_KEY_USERNAME = "sub"; static final String CLAIM_KEY_AUDIENCE = "audience"; static final String CLAIM_KEY_CREATED = "created"; private static final String AUDIENCE_UNKNOWN = "unknown"; private static final String AUDIENCE_WEB = "web"; private static final String AUDIENCE_MOBILE = "mobile"; private static final String AUDIENCE_TABLET = "tablet"; @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String getUsernameFromToken(String token) { String username; try { final Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; } public Date getCreatedDateFromToken(String token) { Date created; try { final Claims claims = getClaimsFromToken(token); created = new Date((Long) claims.get(CLAIM_KEY_CREATED)); } catch (Exception e) { created = null; } return created; } public Date getExpirationDateFromToken(String token) { Date expiration; try { final Claims claims = getClaimsFromToken(token); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; } public String getAudienceFromToken(String token) { String audience; try { final Claims claims = getClaimsFromToken(token); audience = (String) claims.get(CLAIM_KEY_AUDIENCE); } catch (Exception e) { audience = null; } return audience; } private Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { claims = null; } return claims; } private Date generateExpirationDate() { return new Date(System.currentTimeMillis() + expiration * 1000); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) { return (lastPasswordReset != null && created.before(lastPasswordReset)); } private String generateAudience(Device device) { String audience = AUDIENCE_UNKNOWN; if (device.isNormal()) { audience = AUDIENCE_WEB; } else if (device.isTablet()) { audience = AUDIENCE_TABLET; } else if (device.isMobile()) { audience = AUDIENCE_MOBILE; } return audience; } private Boolean ignoreTokenExpiration(String token) { String audience = getAudienceFromToken(token); return (AUDIENCE_TABLET.equals(audience) || AUDIENCE_MOBILE.equals(audience)); } public String generateToken(UserDetails userDetails, Device device) { Map<String, Object> claims = new HashMap<>(); claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); claims.put(CLAIM_KEY_AUDIENCE, generateAudience(device)); claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } String generateToken(Map<String, Object> claims) { return Jwts.builder() .setClaims(claims) .setExpiration(generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, secret) .compact(); } public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) { final Date created = getCreatedDateFromToken(token); return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset) && (!isTokenExpired(token) || ignoreTokenExpiration(token)); } public String refreshToken(String token) { String refreshedToken; try { final Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = generateToken(claims); } catch (Exception e) { refreshedToken = null; } return refreshedToken; } public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); final Date created = getCreatedDateFromToken(token); //final Date expiration = getExpirationDateFromToken(token); return ( username.equals(userDetails.getUsername()) && !isTokenExpired(token)); // && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())); } }
3e0cc5f960af1a205af08c7231ab793d03fbe4a5
1,138
java
Java
src/test/java/any/mytestproject2/ImplFive.java
dmarius99/ImplementationDiscriminator
bb449e9a00038483dcee2f00fa57a5e435b5c226
[ "Apache-2.0" ]
null
null
null
src/test/java/any/mytestproject2/ImplFive.java
dmarius99/ImplementationDiscriminator
bb449e9a00038483dcee2f00fa57a5e435b5c226
[ "Apache-2.0" ]
null
null
null
src/test/java/any/mytestproject2/ImplFive.java
dmarius99/ImplementationDiscriminator
bb449e9a00038483dcee2f00fa57a5e435b5c226
[ "Apache-2.0" ]
null
null
null
22.76
73
0.636204
5,419
package any.mytestproject2; import any.CommonInterface; import any.WrappedParam; import javax.inject.Named; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by Marius on 27/09/14. */ @Named public class ImplFive implements CommonInterface { public static final String MSG = "Show message from ImplFive... 111"; public void show(WrappedParam param1) { System.out.println(MSG); } public String getText1(WrappedParam param1, Integer p2) { System.out.println(MSG); return MSG; } public String getText2(Integer p1) { System.out.println(MSG); return MSG; } public List<String> getList(WrappedParam param1) { System.out.println(MSG); List<String> myList = new ArrayList<String>(); myList.add(MSG + "-1"); myList.add(MSG + "-11"); return myList; } public Set<Integer> getListWithNoParam() { System.out.println(MSG); Set<Integer> mySet = new HashSet<Integer>(); mySet.add(1); mySet.add(2); return mySet; } }
3e0cc5fa367d0b805a658aa5e171ed8c4bcf1e5c
2,349
java
Java
src/test/java/com/mjpitz/codeowners/ConfigTest.java
mjpitz/gerrit-codeowners
f9c21b9200d72c1e63ddb9701137c96f7f8abba3
[ "MIT" ]
null
null
null
src/test/java/com/mjpitz/codeowners/ConfigTest.java
mjpitz/gerrit-codeowners
f9c21b9200d72c1e63ddb9701137c96f7f8abba3
[ "MIT" ]
null
null
null
src/test/java/com/mjpitz/codeowners/ConfigTest.java
mjpitz/gerrit-codeowners
f9c21b9200d72c1e63ddb9701137c96f7f8abba3
[ "MIT" ]
null
null
null
61.710526
150
0.690405
5,420
package com.mjpitz.codeowners; import com.google.common.collect.Sets; import org.junit.Test; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; public class ConfigTest { @Test public void test() throws URISyntaxException, IOException { final Config config = Config.parse(Files.lines( Paths.get(ClassLoader.getSystemResource("TEST_CODEOWNERS").toURI()) )); assertEquals(11, config.rules.size()); assertEquals(3, config.reviewerCount); assertEquals(3, config.ownersFor("/apps/github").size()); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@js-owner", "@octocat"), config.ownersFor("/apps/main.js")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "envkt@example.com", "@octocat"), config.ownersFor("/apps/main.go")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@octocat", "@doctocat"), config.ownersFor("/scripts/deploy.sh")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@doctocat", "envkt@example.com"), config.ownersFor("/docs/README.md")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@octocat", "@js-owner"), config.ownersFor("/internal/apps/main.js")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@octocat", "envkt@example.com"), config.ownersFor("/internal/apps/main.go")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2"), config.ownersFor("/internal/docs/README.md")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@doctocat"), config.ownersFor("/build/logs/out.json")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@octo-org/octocats"), config.ownersFor("/internal/lib/lib.txt")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "envkt@example.com"), config.ownersFor("/internal/lib/lib.go")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@js-owner"), config.ownersFor("/internal/lib/index.js")); assertEquals(Sets.newHashSet("@global-owner1", "@global-owner2", "@global-owner1", "@global-owner2"), config.ownersFor("Jenkinsfile")); } }
3e0cc63193ac43bb779b04f0dc5c7597b97696d7
1,756
java
Java
src/main/java/org/spongepowered/api/util/rotation/Rotation.java
SpongeHistory/SpongeAPI
0c1cfecbbb5f9dfa9b560fc9097cdecb7946b967
[ "MIT" ]
null
null
null
src/main/java/org/spongepowered/api/util/rotation/Rotation.java
SpongeHistory/SpongeAPI
0c1cfecbbb5f9dfa9b560fc9097cdecb7946b967
[ "MIT" ]
null
null
null
src/main/java/org/spongepowered/api/util/rotation/Rotation.java
SpongeHistory/SpongeAPI
0c1cfecbbb5f9dfa9b560fc9097cdecb7946b967
[ "MIT" ]
null
null
null
35.12
80
0.724374
5,421
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.api.util.rotation; import org.spongepowered.api.util.annotation.CatalogedBy; /** * Represents an angle of rotation. */ @CatalogedBy(Rotations.class) public interface Rotation { /** * The angle in degrees. * * @return The angle in degrees */ //TODO we should have an Angle class in the future int getAngle(); /** * Checks if this is a flowerpot. * * @return Whether this is a flowerpot */ boolean isFlowerPot(); }
3e0cc672c5f40a78dbea407a52fa7dc8b96e1e61
7,025
java
Java
feedget-api/src/main/java/kr/co/mashup/feedgetapi/web/controller/CreationController.java
feedget/feedget-backend
a1c45089b1dbed3ebef919d031bbb59999c5d610
[ "MIT" ]
2
2018-02-01T04:49:46.000Z
2021-05-23T10:46:03.000Z
feedget-api/src/main/java/kr/co/mashup/feedgetapi/web/controller/CreationController.java
feedget/feedget-backend
a1c45089b1dbed3ebef919d031bbb59999c5d610
[ "MIT" ]
66
2017-12-09T16:50:35.000Z
2018-07-19T03:39:22.000Z
feedget-api/src/main/java/kr/co/mashup/feedgetapi/web/controller/CreationController.java
feedget/feedget-backend
a1c45089b1dbed3ebef919d031bbb59999c5d610
[ "MIT" ]
1
2018-06-29T11:44:31.000Z
2018-06-29T11:44:31.000Z
46.523179
134
0.633167
5,422
package kr.co.mashup.feedgetapi.web.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import kr.co.mashup.feedgetapi.exception.ErrorResponse; import kr.co.mashup.feedgetapi.service.CreationService; import kr.co.mashup.feedgetapi.web.CreationUpdateValidator; import kr.co.mashup.feedgetapi.web.dto.CreationDto; import kr.co.mashup.feedgetapi.web.dto.DataListResponse; import kr.co.mashup.feedgetapi.web.dto.DataResponse; import kr.co.mashup.feedgetapi.web.dto.Response; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; /** * ์ฐฝ์ž‘๋ฌผ ๊ด€๋ จ request์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ * <p> * Created by ethan.kim on 2017. 12. 21.. */ @RestController @RequestMapping(value = "/creations") @Api(description = "์ฐฝ์ž‘๋ฌผ", tags = {"creation"}) @Slf4j public class CreationController { @Autowired private CreationService creationService; @Autowired private CreationUpdateValidator creationUpdateValidator; // Todo: ์ •๋ ฌ ์ถ”๊ฐ€ - ์ตœ์‹ ์ˆœ, ๋งˆ๊ฐ๋น ๋ฅธ์ˆœ, ํฌ์ธํŠธ ๋งŽ์€ ์ˆœ, ํ”ผ๋“œ๋ฐฑ ๋งŽ์€ ์ˆœ, ํ”ผ๋“œ๋ฐฑ ์ ์€ @ApiOperation(value = "์ฐฝ์ž‘๋ฌผ ๋ฆฌ์ŠคํŠธ ์กฐํšŒ", notes = "์ฐฝ์ž‘๋ฌผ ๋ฆฌ์ŠคํŠธ๋ฅผ ์กฐํšŒํ•œ๋‹ค") @ApiResponses(value = { @ApiResponse(code = 200, message = "์กฐํšŒ ์„ฑ๊ณต"), @ApiResponse(code = 400, message = "์ž˜๋ชป๋œ ์š”์ฒญ(ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ˆ„๋ฝ)"), @ApiResponse(code = 500, message = "์„œ๋ฒ„ ์˜ค๋ฅ˜") }) @GetMapping public ResponseEntity<DataListResponse> readCreations(@RequestAttribute long userId, @RequestParam(value = "category", defaultValue = "ALL") String categoryName, @RequestParam(value = "cursor", required = false) Long cursor, @PageableDefault(page = 0, size = 20) Pageable pageable) { log.info("readCreations - userId : {}, category : {}, cursor : {}, pageable : {}", userId, categoryName, cursor, pageable); Page<CreationDto.Response> creationPage = creationService.readCreations(userId, categoryName, pageable); // Todo: header์—์„œ ๊ธฐํƒ€ ์ •๋ณด๋ฅผ ๋‚ด๋ฆด์ง€ ๊ณ ๋ ค // HttpHeaders headers = new HttpHeaders(); // headers.add("pageSize", String.valueOf(creationPage.getSize())); // headers.add("pageNo", String.valueOf(creationPage.getNumber())); // headers.add("total", String.valueOf(creationPage.getTotalElements())); // ๊ฒ€์ƒ‰๋œ ์ „์ฒด data ์ˆ˜ // headers.add("pageTotal", String.valueOf(creationPage.getTotalPages())); // ์ „์ฒด ํŽ˜์ด์ง€ ์ˆ˜ // return new ResponseEntity<>(new DataListResponse<>(creationPage), headers, HttpStatus.OK); return new ResponseEntity<>(new DataListResponse<>(creationPage), HttpStatus.OK); } @ApiOperation(value = "์ฐฝ์ž‘๋ฌผ ๋‹จ๊ฑด ์กฐํšŒ", notes = "๋‹จ๊ฑด์˜ ์ฐฝ์ž‘๋ฌผ์„ ์กฐํšŒํ•œ๋‹ค") @ApiResponses(value = { @ApiResponse(code = 200, message = "์กฐํšŒ ์„ฑ๊ณต"), @ApiResponse(code = 400, message = "์ž˜๋ชป๋œ ์š”์ฒญ(ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ˆ„๋ฝ)"), @ApiResponse(code = 500, message = "์„œ๋ฒ„ ์˜ค๋ฅ˜") }) @GetMapping(value = "/{creationId}") public DataResponse<CreationDto.DetailResponse> readCreation(@RequestAttribute long userId, @PathVariable(value = "creationId") long creationId) { log.info("readCreation - userId : {}, creationId : {}", userId, creationId); CreationDto.DetailResponse detailResponse = creationService.readCreation(userId, creationId); return new DataResponse<>(detailResponse); } @ApiOperation(value = "์ฐฝ์ž‘๋ฌผ ์ถ”๊ฐ€", notes = "์ฐฝ์ž‘๋ฌผ์„ ์ถ”๊ฐ€ํ•œ๋‹ค") @ApiResponses(value = { @ApiResponse(code = 201, message = "์ถ”๊ฐ€ ์„ฑ๊ณต"), @ApiResponse(code = 400, message = "์ž˜๋ชป๋œ ์š”์ฒญ(ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ˆ„๋ฝ)"), @ApiResponse(code = 500, message = "์„œ๋ฒ„ ์˜ค๋ฅ˜") }) @PostMapping public ResponseEntity createCreation(@RequestAttribute long userId, @Valid @RequestBody CreationDto.Create create, BindingResult result) { log.info("createCreation - userId : {}, dto : {}", userId, create); if (result.hasErrors()) { ErrorResponse errorRepoonse = new ErrorResponse(); errorRepoonse.setMessage("์งˆ๋ชป๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค"); errorRepoonse.setCode("bad request"); // Todo: BindingResult์•ˆ์— ๋“ค์–ด ์žˆ๋Š” ์—๋Ÿฌ ์ •๋ณด ์‚ฌ์šฉ return new ResponseEntity<>(errorRepoonse, HttpStatus.BAD_REQUEST); } long creationId = creationService.addCreation(userId, create); return new ResponseEntity<>(new DataResponse<>(creationId), HttpStatus.CREATED); } @ApiOperation(value = "์ฐฝ์ž‘๋ฌผ ์ˆ˜์ •", notes = "์ฐฝ์ž‘๋ฌผ์„ ์ˆ˜์ •ํ•œ๋‹ค") @ApiResponses(value = { @ApiResponse(code = 200, message = "์ˆ˜์ • ์„ฑ๊ณต"), @ApiResponse(code = 400, message = "์ž˜๋ชป๋œ ์š”์ฒญ(ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ˆ„๋ฝ)"), @ApiResponse(code = 500, message = "์„œ๋ฒ„ ์˜ค๋ฅ˜") }) @PutMapping(value = "/{creationId}") public ResponseEntity updateCreation(@RequestAttribute long userId, @PathVariable(value = "creationId") long creationId, @RequestBody CreationDto.Update update, BindingResult result) { log.info("updateCreation - userId : {}, creationId : {}, dto : {}", userId, creationId, update); creationUpdateValidator.validate(update, result); if (result.hasErrors()) { ErrorResponse errorRepoonse = new ErrorResponse(); errorRepoonse.setMessage("์งˆ๋ชป๋œ ์š”์ฒญ์ž…๋‹ˆ๋‹ค"); errorRepoonse.setCode("bad request"); // Todo: BindingResult์•ˆ์— ๋“ค์–ด ์žˆ๋Š” ์—๋Ÿฌ ์ •๋ณด ์‚ฌ์šฉ return new ResponseEntity<>(errorRepoonse, HttpStatus.BAD_REQUEST); } creationService.modifyCreation(userId, creationId, update); return new ResponseEntity<>(Response.ok(), HttpStatus.OK); } @ApiOperation(value = "์ฐฝ์ž‘๋ฌผ ์‚ญ์ œ", notes = "์ฐฝ์ž‘๋ฌผ๋ฅผ ์‚ญ์ œํ•œ๋‹ค") @ApiResponses(value = { @ApiResponse(code = 200, message = "์‚ญ์ œ ์„ฑ๊ณต"), @ApiResponse(code = 400, message = "์ž˜๋ชป๋œ ์š”์ฒญ(ํ•„์ˆ˜ ํŒŒ๋ผ๋ฏธํ„ฐ ๋ˆ„๋ฝ)"), @ApiResponse(code = 500, message = "์„œ๋ฒ„ ์˜ค๋ฅ˜") }) @DeleteMapping(value = "/{creationId}") public ResponseEntity deleteCreation(@RequestAttribute long userId, @PathVariable(value = "creationId") long creationId) { log.info("deleteCreation - userId : {}, creationId : {}", userId, creationId); creationService.removeCreation(userId, creationId); return ResponseEntity.ok().build(); } // Todo: ์„œ๋น„์Šค ๋‹จ์˜ exception handler ์ถ”๊ฐ€ }
3e0cc7c22774a6b87546bafaa92db35a7f24b57b
2,550
java
Java
core/deployment/src/test/java/io/quarkus/deployment/conditionaldeps/ConditionalDependencyWithTwoConditionsTest.java
orekyuu/quarkus
fde00251204517ddc57356288fe3e7b6ef7c98c4
[ "Apache-2.0" ]
10,225
2019-03-07T11:55:54.000Z
2022-03-31T21:16:53.000Z
core/deployment/src/test/java/io/quarkus/deployment/conditionaldeps/ConditionalDependencyWithTwoConditionsTest.java
orekyuu/quarkus
fde00251204517ddc57356288fe3e7b6ef7c98c4
[ "Apache-2.0" ]
18,675
2019-03-07T11:56:33.000Z
2022-03-31T22:25:22.000Z
core/deployment/src/test/java/io/quarkus/deployment/conditionaldeps/ConditionalDependencyWithTwoConditionsTest.java
orekyuu/quarkus
fde00251204517ddc57356288fe3e7b6ef7c98c4
[ "Apache-2.0" ]
2,190
2019-03-07T12:07:18.000Z
2022-03-30T05:41:35.000Z
41.129032
114
0.701569
5,423
package io.quarkus.deployment.conditionaldeps; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.HashSet; import java.util.Set; import io.quarkus.bootstrap.resolver.TsArtifact; import io.quarkus.bootstrap.resolver.TsQuarkusExt; import io.quarkus.deployment.runnerjar.ExecutableOutputOutcomeTestBase; import io.quarkus.maven.dependency.ArtifactDependency; import io.quarkus.maven.dependency.Dependency; import io.quarkus.maven.dependency.DependencyFlags; import io.quarkus.maven.dependency.GACTV; public class ConditionalDependencyWithTwoConditionsTest extends ExecutableOutputOutcomeTestBase { @Override protected TsArtifact modelApp() { final TsQuarkusExt extA = new TsQuarkusExt("ext-a"); final TsQuarkusExt extD = new TsQuarkusExt("ext-d"); final TsQuarkusExt extB = new TsQuarkusExt("ext-b"); extB.setDependencyCondition(extA, extD); install(extB); final TsQuarkusExt extC = new TsQuarkusExt("ext-c"); extC.setConditionalDeps(extB); addToExpectedLib(extA.getRuntime()); addToExpectedLib(extB.getRuntime()); addToExpectedLib(extC.getRuntime()); addToExpectedLib(extD.getRuntime()); return TsArtifact.jar("app") .addManagedDependency(platformDescriptor()) .addManagedDependency(platformProperties()) .addDependency(extC) .addDependency(extA) .addDependency(extD); } @Override protected void assertDeploymentDeps(Set<Dependency> deploymentDeps) throws Exception { final Set<Dependency> expected = new HashSet<>(); expected.add(new ArtifactDependency( new GACTV(TsArtifact.DEFAULT_GROUP_ID, "ext-c-deployment", TsArtifact.DEFAULT_VERSION), "compile", DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( new GACTV(TsArtifact.DEFAULT_GROUP_ID, "ext-a-deployment", TsArtifact.DEFAULT_VERSION), "compile", DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( new GACTV(TsArtifact.DEFAULT_GROUP_ID, "ext-b-deployment", TsArtifact.DEFAULT_VERSION), "runtime", DependencyFlags.DEPLOYMENT_CP)); expected.add(new ArtifactDependency( new GACTV(TsArtifact.DEFAULT_GROUP_ID, "ext-d-deployment", TsArtifact.DEFAULT_VERSION), "compile", DependencyFlags.DEPLOYMENT_CP)); assertEquals(expected, deploymentDeps); } }
3e0cc82ac1fdf41eedfa16e234fbaf081eb64030
15,035
java
Java
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/v6/Activiti6ExecutionTest.java
HurryUpWb/Activiti
a0cc6985d29695c8043b8e2413729348478b3828
[ "Apache-2.0" ]
8,599
2015-01-01T01:29:48.000Z
2022-03-30T03:23:40.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/v6/Activiti6ExecutionTest.java
LoveMyOrange/Activiti
e39053d02c47cfebbece7a4978ab4dd1eaf2d620
[ "Apache-2.0" ]
2,988
2015-01-03T19:45:21.000Z
2022-03-31T04:08:38.000Z
activiti-core/activiti-engine/src/test/java/org/activiti/engine/test/api/v6/Activiti6ExecutionTest.java
Harshit51435/Activiti
03a0e06921a9ff51c0e700a8c14770ca2c2eb49d
[ "Apache-2.0" ]
7,097
2015-01-02T06:32:21.000Z
2022-03-31T08:17:25.000Z
39.775132
157
0.73994
5,424
/* * Copyright 2010-2020 Alfresco Software, 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 org.activiti.engine.test.api.v6; import static org.assertj.core.api.Assertions.assertThat; import java.util.ArrayList; import java.util.List; import org.activiti.engine.delegate.event.ActivitiActivityCancelledEvent; import org.activiti.engine.delegate.event.ActivitiActivityEvent; import org.activiti.engine.delegate.event.ActivitiEvent; import org.activiti.engine.delegate.event.ActivitiEventListener; import org.activiti.engine.history.HistoricActivityInstance; import org.activiti.engine.impl.history.HistoryLevel; import org.activiti.engine.impl.test.PluggableActivitiTestCase; import org.activiti.engine.runtime.Execution; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; import org.activiti.engine.test.Deployment; import org.junit.Test; public class Activiti6ExecutionTest extends PluggableActivitiTestCase { @Test @Deployment public void testOneTaskProcess() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess"); List<Execution> executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(2); Execution rootProcessInstance = null; Execution childExecution = null; for (Execution execution : executionList) { if (execution.getId().equals(execution.getProcessInstanceId())) { rootProcessInstance = execution; assertThat(execution.getActivityId()).isNull(); } else { childExecution = execution; assertThat(execution.getId()).isNotEqualTo(execution.getProcessInstanceId()); assertThat(execution.getActivityId()).isEqualTo("theTask"); } } assertThat(rootProcessInstance).isNotNull(); assertThat(childExecution).isNotNull(); Task task = taskService.createTaskQuery().singleResult(); assertThat(task.getExecutionId()).isEqualTo(childExecution.getId()); taskService.complete(task.getId()); if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { List<HistoricActivityInstance> historicActivities = historyService.createHistoricActivityInstanceQuery() .processInstanceId(processInstance.getId()) .list(); assertThat(historicActivities).hasSize(3); List<String> activityIds = new ArrayList<String>(); activityIds.add("theStart"); activityIds.add("theTask"); activityIds.add("theEnd"); for (HistoricActivityInstance historicActivityInstance : historicActivities) { activityIds.remove(historicActivityInstance.getActivityId()); assertThat(historicActivityInstance.getExecutionId()).isEqualTo(childExecution.getId()); } assertThat(activityIds).hasSize(0); } } @Test @Deployment public void testOneNestedTaskProcess() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneNestedTaskProcess"); List<Execution> executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(2); Execution rootProcessInstance = null; Execution childExecution = null; for (Execution execution : executionList) { if (execution.getId().equals(execution.getProcessInstanceId())) { rootProcessInstance = execution; assertThat(execution.getActivityId()).isNull(); } else { childExecution = execution; assertThat(execution.getId()).isNotEqualTo(execution.getProcessInstanceId()); assertThat(execution.getActivityId()).isEqualTo("theTask1"); } } assertThat(rootProcessInstance).isNotNull(); assertThat(childExecution).isNotNull(); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getExecutionId()).isEqualTo(childExecution.getId()); taskService.complete(task.getId()); executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(3); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("subTask"); Execution subTaskExecution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult(); assertThat(subTaskExecution.getActivityId()).isEqualTo("subTask"); Execution subProcessExecution = runtimeService.createExecutionQuery().executionId(subTaskExecution.getParentId()).singleResult(); assertThat(subProcessExecution.getActivityId()).isEqualTo("subProcess"); assertThat(subProcessExecution.getParentId()).isEqualTo(rootProcessInstance.getId()); taskService.complete(task.getId()); executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(2); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(childExecution.getId()).isNotEqualTo(task.getExecutionId()); Execution finalTaskExecution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult(); assertThat(finalTaskExecution.getActivityId()).isEqualTo("theTask2"); assertThat(finalTaskExecution.getParentId()).isEqualTo(rootProcessInstance.getId()); taskService.complete(task.getId()); assertProcessEnded(processInstance.getId()); if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { List<HistoricActivityInstance> historicActivities = historyService.createHistoricActivityInstanceQuery() .processInstanceId(processInstance.getId()) .list(); assertThat(historicActivities).hasSize(8); List<String> activityIds = new ArrayList<String>(); activityIds.add("theStart"); activityIds.add("theTask1"); activityIds.add("subProcess"); activityIds.add("subStart"); activityIds.add("subTask"); activityIds.add("subEnd"); activityIds.add("theTask2"); activityIds.add("theEnd"); for (HistoricActivityInstance historicActivityInstance : historicActivities) { String activityId = historicActivityInstance.getActivityId(); activityIds.remove(activityId); if ("theStart".equalsIgnoreCase(activityId) || "theTask1".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(childExecution.getId()); } else if ("theTask2".equalsIgnoreCase(activityId) || "theEnd".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(finalTaskExecution.getId()); } else if ("subStart".equalsIgnoreCase(activityId) || "subTask".equalsIgnoreCase(activityId) || "subEnd".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(subTaskExecution.getId()); } else if ("subProcess".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(subProcessExecution.getId()); } } assertThat(activityIds).hasSize(0); } } @Test @Deployment public void testSubProcessWithTimer() { ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("subProcessWithTimer"); List<Execution> executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(2); Execution rootProcessInstance = null; Execution childExecution = null; for (Execution execution : executionList) { if (execution.getId().equals(execution.getProcessInstanceId())) { rootProcessInstance = execution; assertThat(execution.getActivityId()).isNull(); } else { childExecution = execution; assertThat(execution.getActivityId()).isEqualTo("theTask1"); } } assertThat(rootProcessInstance).isNotNull(); assertThat(childExecution).isNotNull(); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getExecutionId()).isEqualTo(childExecution.getId()); taskService.complete(task.getId()); executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(4); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(task.getTaskDefinitionKey()).isEqualTo("subTask"); Execution subTaskExecution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult(); assertThat(subTaskExecution.getActivityId()).isEqualTo("subTask"); Execution subProcessExecution = runtimeService.createExecutionQuery().executionId(subTaskExecution.getParentId()).singleResult(); assertThat(subProcessExecution.getActivityId()).isEqualTo("subProcess"); assertThat(subProcessExecution.getParentId()).isEqualTo(rootProcessInstance.getId()); taskService.complete(task.getId()); executionList = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).list(); assertThat(executionList).hasSize(2); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); assertThat(childExecution.getId()).isNotEqualTo(task.getExecutionId()); Execution finalTaskExecution = runtimeService.createExecutionQuery().executionId(task.getExecutionId()).singleResult(); assertThat(finalTaskExecution.getActivityId()).isEqualTo("theTask2"); assertThat(finalTaskExecution.getParentId()).isEqualTo(rootProcessInstance.getId()); taskService.complete(task.getId()); assertProcessEnded(processInstance.getId()); if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) { List<HistoricActivityInstance> historicActivities = historyService.createHistoricActivityInstanceQuery() .processInstanceId(processInstance.getId()) .list(); assertThat(historicActivities).hasSize(8); List<String> activityIds = new ArrayList<String>(); activityIds.add("theStart"); activityIds.add("theTask1"); activityIds.add("subProcess"); activityIds.add("subStart"); activityIds.add("subTask"); activityIds.add("subEnd"); activityIds.add("theTask2"); activityIds.add("theEnd"); for (HistoricActivityInstance historicActivityInstance : historicActivities) { String activityId = historicActivityInstance.getActivityId(); activityIds.remove(activityId); if ("theStart".equalsIgnoreCase(activityId) || "theTask1".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(childExecution.getId()); } else if ("theTask2".equalsIgnoreCase(activityId) || "theEnd".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(finalTaskExecution.getId()); } else if ("subStart".equalsIgnoreCase(activityId) || "subTask".equalsIgnoreCase(activityId) || "subEnd".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(subTaskExecution.getId()); } else if ("subProcess".equalsIgnoreCase(activityId)) { assertThat(historicActivityInstance.getExecutionId()).isEqualTo(subProcessExecution.getId()); } } assertThat(activityIds).hasSize(0); } } @Test @Deployment public void testSubProcessEvents() { SubProcessEventListener listener = new SubProcessEventListener(); processEngineConfiguration.getEventDispatcher().addEventListener(listener); ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("subProcessEvents"); Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); Execution subProcessExecution = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId()).activityId("subProcess").singleResult(); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult(); taskService.complete(task.getId()); assertProcessEnded(processInstance.getId()); // Verify Events List<ActivitiEvent> events = listener.getEventsReceived(); assertThat(events).hasSize(2); ActivitiActivityEvent event = (ActivitiActivityEvent) events.get(0); assertThat(event.getActivityType()).isEqualTo("subProcess"); assertThat(event.getExecutionId()).isEqualTo(subProcessExecution.getId()); event = (ActivitiActivityEvent) events.get(1); assertThat(event.getActivityType()).isEqualTo("subProcess"); assertThat(event.getExecutionId()).isEqualTo(subProcessExecution.getId()); processEngineConfiguration.getEventDispatcher().removeEventListener(listener); } public class SubProcessEventListener implements ActivitiEventListener { private List<ActivitiEvent> eventsReceived; public SubProcessEventListener() { eventsReceived = new ArrayList<ActivitiEvent>(); } public List<ActivitiEvent> getEventsReceived() { return eventsReceived; } public void clearEventsReceived() { eventsReceived.clear(); } @Override public void onEvent(ActivitiEvent activitiEvent) { if (activitiEvent instanceof ActivitiActivityEvent) { ActivitiActivityEvent event = (ActivitiActivityEvent) activitiEvent; if ("subProcess".equals(event.getActivityType())) { eventsReceived.add(event); } } else if (activitiEvent instanceof ActivitiActivityCancelledEvent) { ActivitiActivityCancelledEvent event = (ActivitiActivityCancelledEvent) activitiEvent; if ("subProcess".equals(event.getActivityType())) { eventsReceived.add(event); } } } @Override public boolean isFailOnException() { return true; } } }