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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e15c16974dd6f08150c5d599e9c7022842a40e5 | 633 | java | Java | DomeOS/src/test/java/org/domeos/framework/api/biz/project/ProjectBizTest.java | eliukehua/domeos-mye | b476603512d2f8a8d50b697c793bc6cebf5ab575 | [
"Apache-2.0"
] | null | null | null | DomeOS/src/test/java/org/domeos/framework/api/biz/project/ProjectBizTest.java | eliukehua/domeos-mye | b476603512d2f8a8d50b697c793bc6cebf5ab575 | [
"Apache-2.0"
] | null | null | null | DomeOS/src/test/java/org/domeos/framework/api/biz/project/ProjectBizTest.java | eliukehua/domeos-mye | b476603512d2f8a8d50b697c793bc6cebf5ab575 | [
"Apache-2.0"
] | null | null | null | 26.375 | 62 | 0.718799 | 9,238 | package org.domeos.framework.api.biz.project;
import org.domeos.base.BaseTestCase;
import org.domeos.framework.api.model.ci.BuildHistory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by feiliu206363 on 2016/4/7.
*/
public class ProjectBizTest extends BaseTestCase {
@Autowired
ProjectBiz projectBiz;
@Test
public void testInsertRow() throws Exception {
BuildHistory history = new BuildHistory();
history.setName("test");
history.setSecret("aaa");
history.setProjectId(1);
projectBiz.addBuildHistory(history);
}
} |
3e15c1aef21db7c63adfe16d93c233c78b145a01 | 9,771 | java | Java | platform/core.kit/test/perf/src/org/openide/ErrorManagerTest.java | tusharvjoshi/incubator-netbeans | a61bd21f4324f7e73414633712522811cb20ac93 | [
"Apache-2.0"
] | 1,056 | 2019-04-25T20:00:35.000Z | 2022-03-30T04:46:14.000Z | platform/core.kit/test/perf/src/org/openide/ErrorManagerTest.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 1,846 | 2019-04-25T20:50:05.000Z | 2022-03-31T23:40:41.000Z | platform/core.kit/test/perf/src/org/openide/ErrorManagerTest.java | Marc382/netbeans | 4bee741d24a3fdb05baf135de5e11a7cd95bd64e | [
"Apache-2.0"
] | 550 | 2019-04-25T20:04:33.000Z | 2022-03-25T17:43:01.000Z | 35.274368 | 172 | 0.592263 | 9,239 | /*
* 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.openide;
import java.io.*;
import java.util.*;
import org.netbeans.performance.Benchmark;
public class ErrorManagerTest extends Benchmark {
static {
Properties prop = System.getProperties();
prop.put("perf.test.enabled", "-5");
// prop.put("perf.test.disabled", "0x1000000");
}
private static final ErrorManager enabled;
private static final ErrorManager disabled;
static {
ErrorManager en = ErrorManager.getDefault().getInstance("perf.test.enabled");
enabled = en.isLoggable(ErrorManager.INFORMATIONAL) ? en : null;
ErrorManager dis = ErrorManager.getDefault().getInstance("perf.test.disabled");
disabled = dis.isLoggable(ErrorManager.INFORMATIONAL) ? dis : null;
assertNull("disabled is loggable", disabled);
}
public ErrorManagerTest(String name) {
super( name );
}
public void testLogEnabled() throws Exception {
int count = getIterationCount();
ErrorManager en = ErrorManager.getDefault().getInstance("perf.test.enabled");
while( count-- > 0 ) {
// do the stuff here,
en.log("Logging event #" + count);
}
}
public void testLogDisabled() throws Exception {
int count = getIterationCount();
ErrorManager dis = ErrorManager.getDefault().getInstance("perf.test.disabled");
while( count-- > 0 ) {
// do the stuff here,
dis.log("Logging event #" + count);
}
}
public void testCheckedEnabled() throws Exception {
int count = getIterationCount();
ErrorManager en = ErrorManager.getDefault().getInstance("perf.test.enabled");
while( count-- > 0 ) {
// do the stuff here,
if(en.isLoggable(ErrorManager.INFORMATIONAL)) en.log("Logging event #" + count);
}
}
public void testCheckedDisabled() throws Exception {
int count = getIterationCount();
ErrorManager dis = ErrorManager.getDefault().getInstance("perf.test.disabled");
while( count-- > 0 ) {
// do the stuff here,
if(dis.isLoggable(ErrorManager.INFORMATIONAL)) dis.log("Logging event #" + count);
}
}
public void testNullEnabled() throws Exception {
int count = getIterationCount();
while( count-- > 0 ) {
// do the stuff here,
if(enabled != null) enabled.log("Logging event #" + count);
}
}
public void testNullDisabled() throws Exception {
int count = getIterationCount();
while( count-- > 0 ) {
// do the stuff here,
if(disabled != null) disabled.log("Logging event #" + count);
}
}
public void testNull16Disabled() throws Exception {
int count = getIterationCount();
while( count-- > 0 ) {
// do the stuff here,
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
if(disabled != null) disabled.log("Logging event #" + count);
}
}
public static void main(String[] args) {
simpleRun( ErrorManager.class );
}
/** Crippled version of NbErrorManager that does the logging the same way */
public static final class EM extends ErrorManager {
/** The writer to the log file*/
private PrintWriter logWriter = new PrintWriter(System.err);
/** Minimum value of severity to write message to the log file*/
private int minLogSeverity = ErrorManager.INFORMATIONAL + 1; // NOI18N
/** Prefix preprended to customized loggers, if any. */
private String prefix = null;
// Make sure two distinct EM impls log differently even with the same name.
private int uniquifier = 0; // 0 for root EM (prefix == null), else >= 1
static final Map uniquifiedIds = new HashMap(20); // Map<String,Integer>
/** Initializes the log stream.
*/
private PrintWriter getLogWriter () {
return logWriter;
}
public synchronized Throwable annotate (
Throwable t,
int severity, String message, String localizedMessage,
Throwable stackTrace, java.util.Date date
) {
return t;
}
/** Associates annotations with this thread.
*
* @param arr array of annotations (or null)
*/
public synchronized Throwable attachAnnotations (Throwable t, Annotation[] arr) {
return t;
}
/** Notifies all the exceptions associated with
* this thread.
*/
public synchronized void notify (int severity, Throwable t) {
}
public void log(int severity, String s) {
if (isLoggable (severity)) {
PrintWriter log = getLogWriter ();
if (prefix != null) {
boolean showUniquifier;
// Print a unique EM sequence # if there is more than one
// with this name. Shortcut: if the # > 1, clearly there are.
if (uniquifier > 1) {
showUniquifier = true;
} else if (uniquifier == 1) {
synchronized (uniquifiedIds) {
int count = ((Integer)uniquifiedIds.get(prefix)).intValue();
showUniquifier = count > 1;
}
} else {
throw new IllegalStateException("prefix != null yet uniquifier == 0");
}
if (showUniquifier) {
log.print ("[" + prefix + " #" + uniquifier + "] "); // NOI18N
} else {
log.print ("[" + prefix + "] "); // NOI18N
}
}
log.println(s);
log.flush();
}
}
/** Allows to test whether messages with given severity will be logged
* or not prior to constraction of complicated and time expensive
* logging messages.
*
* @param severity the severity to check
* @return false if the next call to log method with the same severity will
* discard the message
*/
public boolean isLoggable (int severity) {
return severity >= minLogSeverity;
}
/** Returns an instance with given name. The name
* can be dot separated list of names creating
* a hierarchy.
*/
public final ErrorManager getInstance(String name) {
EM newEM = new EM();
newEM.prefix = (prefix == null) ? name : prefix + '.' + name;
synchronized (uniquifiedIds) {
Integer i = (Integer)uniquifiedIds.get(newEM.prefix);
if (i == null) {
newEM.uniquifier = 1;
} else {
newEM.uniquifier = i.intValue() + 1;
}
uniquifiedIds.put(newEM.prefix, new Integer(newEM.uniquifier));
}
newEM.minLogSeverity = minLogSeverity;
String prop = newEM.prefix;
while (prop != null) {
String value = System.getProperty (prop);
//System.err.println ("Trying; prop=" + prop + " value=" + value);
if (value != null) {
try {
newEM.minLogSeverity = Integer.parseInt (value);
} catch (NumberFormatException nfe) {
notify (WARNING, nfe);
}
break;
} else {
int idx = prop.lastIndexOf ('.');
if (idx == -1)
prop = null;
else
prop = prop.substring (0, idx);
}
}
//System.err.println ("getInstance: prefix=" + prefix + " mls=" + minLogSeverity + " name=" + name + " prefix2=" + newEM.prefix + " mls2=" + newEM.minLogSeverity);
return newEM;
}
/** Finds annotations associated with given exception.
* @param t the exception
* @return array of annotations or null
*/
public synchronized Annotation[] findAnnotations (Throwable t) {
return new Annotation[0];
}
public String toString() {
return super.toString() + "<" + prefix + "," + minLogSeverity + ">"; // NOI18N
}
}
}
|
3e15c21e72b8e070a21ed90b64bd13ecb355f0fb | 1,360 | java | Java | Chapter06/GeneticAlgorithm/src/com/javferna/packtpub/mastering/geneticAlgorithm/serial/SerialMain.java | JavaProgrammerLB/Mastering-Concurrency-Programming-with-Java-9-Second-Edition | fb5d6552403f712b382e9d1003e65335e40362cb | [
"MIT"
] | 1 | 2020-11-06T11:54:17.000Z | 2020-11-06T11:54:17.000Z | Chapter06/GeneticAlgorithm/src/com/javferna/packtpub/mastering/geneticAlgorithm/serial/SerialMain.java | ShaofenWu/Mastering-Concurrency-Programming-with-Java-9-Second-Edition | dacd4d69318a6d961bb84ef98f63b378ba03aba8 | [
"MIT"
] | null | null | null | Chapter06/GeneticAlgorithm/src/com/javferna/packtpub/mastering/geneticAlgorithm/serial/SerialMain.java | ShaofenWu/Mastering-Concurrency-Programming-with-Java-9-Second-Edition | dacd4d69318a6d961bb84ef98f63b378ba03aba8 | [
"MIT"
] | 1 | 2018-10-06T14:44:11.000Z | 2018-10-06T14:44:11.000Z | 34 | 107 | 0.660294 | 9,240 | package com.javferna.packtpub.mastering.geneticAlgorithm.serial;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
import com.javferna.packtpub.mastering.geneticAlgorithm.common.DataLoader;
import com.javferna.packtpub.mastering.geneticAlgorithm.common.Individual;
public class SerialMain {
public static void main(String[] args) throws IOException {
Date start, end;
int generations = 10000;
int individuals = 1000;
for (String name : new String[] { "lau15_dist", "kn57_dist" }) {
int[][] distanceMatrix = DataLoader.load(Paths.get("data", name + ".txt"));
SerialGeneticAlgorithm serialGeneticAlgorithm = new SerialGeneticAlgorithm(distanceMatrix, generations,
individuals);
start = new Date();
Individual result = serialGeneticAlgorithm.calculate();
end = new Date();
System.out.println("=======================================");
System.out.println("Example:"+name);
System.out.println("Generations: " + generations);
System.out.println("Population: " + individuals);
System.out.println("Execution Time: " + (end.getTime() - start.getTime()));
System.out.println("Best Individual: " + result);
System.out.println("Total Distance: " + result.getValue());
System.out.println("=======================================");
}
}
}
|
3e15c2f869d0907c71c91441f3eced13ccf3ab2e | 1,131 | java | Java | gmall-ums/src/main/java/com/atguigu/gmall/ums/entity/MemberCollectSubjectEntity.java | wuwu55-55/gmall | 2af99d0ea2000a4050c4a97a19c96373b1cca6a5 | [
"Apache-2.0"
] | null | null | null | gmall-ums/src/main/java/com/atguigu/gmall/ums/entity/MemberCollectSubjectEntity.java | wuwu55-55/gmall | 2af99d0ea2000a4050c4a97a19c96373b1cca6a5 | [
"Apache-2.0"
] | 3 | 2020-08-03T11:28:32.000Z | 2021-09-20T20:52:26.000Z | gmall-ums/src/main/java/com/atguigu/gmall/ums/entity/MemberCollectSubjectEntity.java | wuwu55-55/gmall | 2af99d0ea2000a4050c4a97a19c96373b1cca6a5 | [
"Apache-2.0"
] | null | null | null | 21.692308 | 65 | 0.728723 | 9,241 | package com.atguigu.gmall.ums.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 会员收藏的专题活动
*
* @author yuanyuanyuan
* @email lyhxr@example.com
* @date 2019-09-23 18:13:38
*/
@ApiModel
@Data
@TableName("ums_member_collect_subject")
public class MemberCollectSubjectEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
@ApiModelProperty(name = "id",value = "id")
private Long id;
/**
* subject_id
*/
@ApiModelProperty(name = "subjectId",value = "subject_id")
private Long subjectId;
/**
* subject_name
*/
@ApiModelProperty(name = "subjectName",value = "subject_name")
private String subjectName;
/**
* subject_img
*/
@ApiModelProperty(name = "subjectImg",value = "subject_img")
private String subjectImg;
/**
* 活动url
*/
@ApiModelProperty(name = "subjectUrll",value = "活动url")
private String subjectUrll;
}
|
3e15c38fa3c0d097b81adb81d0003051cbad163d | 1,169 | java | Java | Resources/Code/Eclipse-SW360antenna/antenna/modules/sw360/src/main/java/org/eclipse/sw360/antenna/sw360/rest/resource/SW360HalResourceUtility.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | 2 | 2020-02-07T17:32:14.000Z | 2022-02-08T09:14:01.000Z | Resources/Code/Eclipse-SW360antenna/antenna/modules/sw360/src/main/java/org/eclipse/sw360/antenna/sw360/rest/resource/SW360HalResourceUtility.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | Resources/Code/Eclipse-SW360antenna/antenna/modules/sw360/src/main/java/org/eclipse/sw360/antenna/sw360/rest/resource/SW360HalResourceUtility.java | briancabbott/xtrax | 3bfcbe1c2f5c355b886d8171481a604cca7f4f16 | [
"MIT"
] | null | null | null | 29.225 | 80 | 0.645851 | 9,242 | /*
* Copyright (c) Bosch Software Innovations GmbH 2017-2018.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.sw360.antenna.sw360.rest.resource;
import java.util.Optional;
public class SW360HalResourceUtility {
private SW360HalResourceUtility() {
// Utility
}
public static Optional<String> getLastIndexOfSelfLink(LinkObjects linkObj) {
if (linkObj != null) {
return getLastIndexOfSelfLink(linkObj.getSelf());
}
return Optional.empty();
}
public static Optional<String> getLastIndexOfSelfLink(Self selfObj) {
if (selfObj != null) {
String href = selfObj.getHref();
if (href != null && !href.isEmpty()) {
int lastSlashIndex = href.lastIndexOf('/');
return Optional.of(href.substring(lastSlashIndex + 1));
}
}
return Optional.empty();
}
}
|
3e15c39e095c207a61c38a1cc1ca2fb050a4629f | 20,111 | java | Java | test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | test/fixtures/s3-fixture/src/main/java/fixture/s3/S3HttpHandler.java | diwasjoshi/elasticsearch | 58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f | [
"Apache-2.0"
] | null | null | null | 50.15212 | 136 | 0.546567 | 9,243 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package fixture.s3;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.bytes.CompositeBytesReference;
import org.elasticsearch.common.hash.MessageDigests;
import org.elasticsearch.common.io.Streams;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.core.Tuple;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.RestUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.nio.charset.StandardCharsets.UTF_8;
/**
* Minimal HTTP handler that acts as a S3 compliant server
*/
@SuppressForbidden(reason = "this test uses a HttpServer to emulate an S3 endpoint")
public class S3HttpHandler implements HttpHandler {
private final String bucket;
private final String path;
private final ConcurrentMap<String, BytesReference> blobs = new ConcurrentHashMap<>();
public S3HttpHandler(final String bucket) {
this(bucket, null);
}
public S3HttpHandler(final String bucket, @Nullable final String basePath) {
this.bucket = Objects.requireNonNull(bucket);
this.path = bucket + (basePath != null && basePath.isEmpty() == false ? "/" + basePath : "");
}
@Override
public void handle(final HttpExchange exchange) throws IOException {
final String request = exchange.getRequestMethod() + " " + exchange.getRequestURI().toString();
if (request.startsWith("GET") || request.startsWith("HEAD") || request.startsWith("DELETE")) {
int read = exchange.getRequestBody().read();
assert read == -1 : "Request body should have been empty but saw [" + read + "]";
}
try {
if (Regex.simpleMatch("HEAD /" + path + "/*", request)) {
final BytesReference blob = blobs.get(exchange.getRequestURI().getPath());
if (blob == null) {
exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1);
} else {
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1);
}
} else if (Regex.simpleMatch("POST /" + path + "/*?uploads", request)) {
final String uploadId = UUIDs.randomBase64UUID();
byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<InitiateMultipartUploadResult>\n"
+ " <Bucket>"
+ bucket
+ "</Bucket>\n"
+ " <Key>"
+ exchange.getRequestURI().getPath()
+ "</Key>\n"
+ " <UploadId>"
+ uploadId
+ "</UploadId>\n"
+ "</InitiateMultipartUploadResult>").getBytes(StandardCharsets.UTF_8);
blobs.put(multipartKey(uploadId, 0), BytesArray.EMPTY);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length);
exchange.getResponseBody().write(response);
} else if (Regex.simpleMatch("PUT /" + path + "/*?uploadId=*&partNumber=*", request)) {
final Map<String, String> params = new HashMap<>();
RestUtils.decodeQueryString(exchange.getRequestURI().getQuery(), 0, params);
final String uploadId = params.get("uploadId");
if (blobs.containsKey(multipartKey(uploadId, 0))) {
final Tuple<String, BytesReference> blob = parseRequestBody(exchange);
final int partNumber = Integer.parseInt(params.get("partNumber"));
blobs.put(multipartKey(uploadId, partNumber), blob.v2());
exchange.getResponseHeaders().add("ETag", blob.v1());
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1);
} else {
exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1);
}
} else if (Regex.simpleMatch("POST /" + path + "/*?uploadId=*", request)) {
Streams.readFully(exchange.getRequestBody());
final Map<String, String> params = new HashMap<>();
RestUtils.decodeQueryString(exchange.getRequestURI().getQuery(), 0, params);
final String uploadId = params.get("uploadId");
final int nbParts = blobs.keySet()
.stream()
.filter(blobName -> blobName.startsWith(uploadId))
.map(blobName -> blobName.replaceFirst(uploadId + '\n', ""))
.mapToInt(Integer::parseInt)
.max()
.orElse(0);
final ByteArrayOutputStream blob = new ByteArrayOutputStream();
for (int partNumber = 0; partNumber <= nbParts; partNumber++) {
BytesReference part = blobs.remove(multipartKey(uploadId, partNumber));
if (part == null) {
throw new AssertionError("Upload part is null");
}
part.writeTo(blob);
}
blobs.put(exchange.getRequestURI().getPath(), new BytesArray(blob.toByteArray()));
byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<CompleteMultipartUploadResult>\n"
+ "<Bucket>"
+ bucket
+ "</Bucket>\n"
+ "<Key>"
+ exchange.getRequestURI().getPath()
+ "</Key>\n"
+ "</CompleteMultipartUploadResult>").getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length);
exchange.getResponseBody().write(response);
} else if (Regex.simpleMatch("PUT /" + path + "/*", request)) {
final Tuple<String, BytesReference> blob = parseRequestBody(exchange);
blobs.put(exchange.getRequestURI().toString(), blob.v2());
exchange.getResponseHeaders().add("ETag", blob.v1());
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), -1);
} else if (Regex.simpleMatch("GET /" + bucket + "/?prefix=*", request)) {
final Map<String, String> params = new HashMap<>();
RestUtils.decodeQueryString(exchange.getRequestURI().getQuery(), 0, params);
if (params.get("list-type") != null) {
throw new AssertionError("Test must be adapted for GET Bucket (List Objects) Version 2");
}
final StringBuilder list = new StringBuilder();
list.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
list.append("<ListBucketResult>");
final String prefix = params.get("prefix");
if (prefix != null) {
list.append("<Prefix>").append(prefix).append("</Prefix>");
}
final Set<String> commonPrefixes = new HashSet<>();
final String delimiter = params.get("delimiter");
if (delimiter != null) {
list.append("<Delimiter>").append(delimiter).append("</Delimiter>");
}
for (Map.Entry<String, BytesReference> blob : blobs.entrySet()) {
if (prefix != null && blob.getKey().startsWith("/" + bucket + "/" + prefix) == false) {
continue;
}
String blobPath = blob.getKey().replace("/" + bucket + "/", "");
if (delimiter != null) {
int fromIndex = (prefix != null ? prefix.length() : 0);
int delimiterPosition = blobPath.indexOf(delimiter, fromIndex);
if (delimiterPosition > 0) {
commonPrefixes.add(blobPath.substring(0, delimiterPosition) + delimiter);
continue;
}
}
list.append("<Contents>");
list.append("<Key>").append(blobPath).append("</Key>");
list.append("<Size>").append(blob.getValue().length()).append("</Size>");
list.append("</Contents>");
}
if (commonPrefixes.isEmpty() == false) {
list.append("<CommonPrefixes>");
commonPrefixes.forEach(commonPrefix -> list.append("<Prefix>").append(commonPrefix).append("</Prefix>"));
list.append("</CommonPrefixes>");
}
list.append("</ListBucketResult>");
byte[] response = list.toString().getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length);
exchange.getResponseBody().write(response);
} else if (Regex.simpleMatch("GET /" + path + "/*", request)) {
final BytesReference blob = blobs.get(exchange.getRequestURI().toString());
if (blob != null) {
final String range = exchange.getRequestHeaders().getFirst("Range");
if (range == null) {
exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), blob.length());
blob.writeTo(exchange.getResponseBody());
} else {
final Matcher matcher = Pattern.compile("^bytes=([0-9]+)-([0-9]+)$").matcher(range);
if (matcher.matches() == false) {
throw new AssertionError("Bytes range does not match expected pattern: " + range);
}
final int start = Integer.parseInt(matcher.group(1));
final int end = Integer.parseInt(matcher.group(2));
final BytesReference rangeBlob = blob.slice(start, end + 1 - start);
exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
exchange.getResponseHeaders()
.add("Content-Range", String.format(Locale.ROOT, "bytes %d-%d/%d", start, end, rangeBlob.length()));
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), rangeBlob.length());
rangeBlob.writeTo(exchange.getResponseBody());
}
} else {
exchange.sendResponseHeaders(RestStatus.NOT_FOUND.getStatus(), -1);
}
} else if (Regex.simpleMatch("DELETE /" + path + "/*", request)) {
int deletions = 0;
for (Iterator<Map.Entry<String, BytesReference>> iterator = blobs.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, BytesReference> blob = iterator.next();
if (blob.getKey().startsWith(exchange.getRequestURI().toString())) {
iterator.remove();
deletions++;
}
}
exchange.sendResponseHeaders((deletions > 0 ? RestStatus.OK : RestStatus.NO_CONTENT).getStatus(), -1);
} else if (Regex.simpleMatch("POST /" + bucket + "/?delete", request)) {
final String requestBody = Streams.copyToString(new InputStreamReader(exchange.getRequestBody(), UTF_8));
final StringBuilder deletes = new StringBuilder();
deletes.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
deletes.append("<DeleteResult>");
for (Iterator<Map.Entry<String, BytesReference>> iterator = blobs.entrySet().iterator(); iterator.hasNext();) {
Map.Entry<String, BytesReference> blob = iterator.next();
String key = blob.getKey().replace("/" + bucket + "/", "");
if (requestBody.contains("<Key>" + key + "</Key>")) {
deletes.append("<Deleted><Key>").append(key).append("</Key></Deleted>");
iterator.remove();
}
}
deletes.append("</DeleteResult>");
byte[] response = deletes.toString().getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/xml");
exchange.sendResponseHeaders(RestStatus.OK.getStatus(), response.length);
exchange.getResponseBody().write(response);
} else {
exchange.sendResponseHeaders(RestStatus.INTERNAL_SERVER_ERROR.getStatus(), -1);
}
} finally {
exchange.close();
}
}
public Map<String, BytesReference> blobs() {
return blobs;
}
private static String multipartKey(final String uploadId, int partNumber) {
return uploadId + "\n" + partNumber;
}
private static final Pattern chunkSignaturePattern = Pattern.compile("^([0-9a-z]+);chunk-signature=([^\\r\\n]*)$");
private static Tuple<String, BytesReference> parseRequestBody(final HttpExchange exchange) throws IOException {
try {
final BytesReference bytesReference;
final String headerDecodedContentLength = exchange.getRequestHeaders().getFirst("x-amz-decoded-content-length");
if (headerDecodedContentLength == null) {
bytesReference = Streams.readFully(exchange.getRequestBody());
} else {
BytesReference requestBody = Streams.readFully(exchange.getRequestBody());
int chunkIndex = 0;
final List<BytesReference> chunks = new ArrayList<>();
while (true) {
chunkIndex += 1;
final int headerLength = requestBody.indexOf((byte) '\n', 0) + 1; // includes terminating \r\n
if (headerLength == 0) {
throw new IllegalStateException("header of chunk [" + chunkIndex + "] was not terminated");
}
if (headerLength > 150) {
throw new IllegalStateException(
"header of chunk [" + chunkIndex + "] was too long at [" + headerLength + "] bytes"
);
}
if (headerLength < 3) {
throw new IllegalStateException(
"header of chunk [" + chunkIndex + "] was too short at [" + headerLength + "] bytes"
);
}
if (requestBody.get(headerLength - 1) != '\n' || requestBody.get(headerLength - 2) != '\r') {
throw new IllegalStateException("header of chunk [" + chunkIndex + "] not terminated with [\\r\\n]");
}
final String header = requestBody.slice(0, headerLength - 2).utf8ToString();
final Matcher matcher = chunkSignaturePattern.matcher(header);
if (matcher.find() == false) {
throw new IllegalStateException(
"header of chunk [" + chunkIndex + "] did not match expected pattern: [" + header + "]"
);
}
final int chunkSize = Integer.parseUnsignedInt(matcher.group(1), 16);
if (requestBody.get(headerLength + chunkSize) != '\r' || requestBody.get(headerLength + chunkSize + 1) != '\n') {
throw new IllegalStateException("chunk [" + chunkIndex + "] not terminated with [\\r\\n]");
}
if (chunkSize != 0) {
chunks.add(requestBody.slice(headerLength, chunkSize));
}
final int toSkip = headerLength + chunkSize + 2;
requestBody = requestBody.slice(toSkip, requestBody.length() - toSkip);
if (chunkSize == 0) {
break;
}
}
bytesReference = CompositeBytesReference.of(chunks.toArray(new BytesReference[0]));
if (bytesReference.length() != Integer.parseInt(headerDecodedContentLength)) {
throw new IllegalStateException(
"Something went wrong when parsing the chunked request "
+ "[bytes read="
+ bytesReference.length()
+ ", expected="
+ headerDecodedContentLength
+ "]"
);
}
}
return Tuple.tuple(MessageDigests.toHexString(MessageDigests.digest(bytesReference, MessageDigests.md5())), bytesReference);
} catch (Exception e) {
exchange.sendResponseHeaders(500, 0);
try (PrintStream printStream = new PrintStream(exchange.getResponseBody())) {
printStream.println(e.toString());
e.printStackTrace(printStream);
}
throw new AssertionError("parseRequestBody failed", e);
}
}
public static void sendError(final HttpExchange exchange, final RestStatus status, final String errorCode, final String message)
throws IOException {
final Headers headers = exchange.getResponseHeaders();
headers.add("Content-Type", "application/xml");
final String requestId = exchange.getRequestHeaders().getFirst("x-amz-request-id");
if (requestId != null) {
headers.add("x-amz-request-id", requestId);
}
if (errorCode == null || "HEAD".equals(exchange.getRequestMethod())) {
exchange.sendResponseHeaders(status.getStatus(), -1L);
exchange.close();
} else {
final byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Error>"
+ "<Code>"
+ errorCode
+ "</Code>"
+ "<Message>"
+ message
+ "</Message>"
+ "<RequestId>"
+ requestId
+ "</RequestId>"
+ "</Error>").getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(status.getStatus(), response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
}
}
|
3e15c4082f6e40539ac40d71375a9da570e1835c | 2,311 | java | Java | DynmapCore/src/main/java/org/dynmap/web/FilterHandler.java | hammermaps/dynmap | 94eab3b6a842c0a3745c5173c578307fc9a5d0b1 | [
"Apache-2.0"
] | 1,403 | 2015-01-10T20:19:16.000Z | 2022-03-30T12:31:52.000Z | DynmapCore/src/main/java/org/dynmap/web/FilterHandler.java | hammermaps/dynmap | 94eab3b6a842c0a3745c5173c578307fc9a5d0b1 | [
"Apache-2.0"
] | 2,232 | 2015-01-01T11:47:21.000Z | 2022-03-31T18:54:18.000Z | DynmapCore/src/main/java/org/dynmap/web/FilterHandler.java | hammermaps/dynmap | 94eab3b6a842c0a3745c5173c578307fc9a5d0b1 | [
"Apache-2.0"
] | 477 | 2015-01-03T10:32:42.000Z | 2022-03-29T20:20:26.000Z | 32.549296 | 179 | 0.633492 | 9,244 | package org.dynmap.web;
import org.dynmap.Log;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.servlet.FilterHolder;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
public class FilterHandler extends AbstractHandler {
private Handler handler;
private LinkedList<FilterHolder> filters = new LinkedList<FilterHolder>();
public FilterHandler() {
}
public FilterHandler(Handler handler, Iterable<Filter> filters) {
this.handler = handler;
for(Filter f : filters) {
try {
FilterHolder holder = new FilterHolder(f);
holder.start();
holder.initialize();
this.filters.add(holder);
}catch (Exception e){
Log.severe("Failed to initialize filter holder: "+e.toString());
}
}
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public Iterable<FilterHolder> getFilters() {
return filters;
}
public void addFilter(Filter filter) {
filters.add(new FilterHolder(filter));
}
@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
final Handler handler = this.getHandler();
final Iterator<FilterHolder> iterator = getFilters().iterator();
final FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest re, ServletResponse rs) throws IOException, ServletException {
if (iterator.hasNext()) {
Filter f = iterator.next().getFilter();
f.doFilter(request, response, this);
} else {
handler.handle(target, baseRequest, request, response);
}
}
};
chain.doFilter(request, response);
}
}
|
3e15c42ea219c08eda729b1e8dab226c0c1b9cb1 | 1,937 | java | Java | middle/multithreading/src/test/java/ru/job4j/synchronize/storage/UserStorageTest.java | DmitriyShaplov/job4j | 46acbe6deb17ecfd00492533555f27e0df481d37 | [
"Apache-2.0"
] | null | null | null | middle/multithreading/src/test/java/ru/job4j/synchronize/storage/UserStorageTest.java | DmitriyShaplov/job4j | 46acbe6deb17ecfd00492533555f27e0df481d37 | [
"Apache-2.0"
] | 8 | 2020-03-04T23:08:50.000Z | 2021-12-14T20:37:44.000Z | middle/multithreading/src/test/java/ru/job4j/synchronize/storage/UserStorageTest.java | DmitriyShaplov/job4j | 46acbe6deb17ecfd00492533555f27e0df481d37 | [
"Apache-2.0"
] | null | null | null | 31.241935 | 85 | 0.618482 | 9,245 | package ru.job4j.synchronize.storage;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class UserStorageTest {
@Test
public void whenCreateUserThenAddUserToStorageTwiceResultFirstTrueSecondFalse() {
UserStorage storage = new UserStorage();
User user1 = new User(1, 100);
var res1 = storage.add(user1);
var res2 = storage.add(user1);
assertTrue(res1);
assertFalse(res2);
}
@Test
public void whenCreate2UsersThenTransferMoneyResultChangedAmount() {
UserStorage storage = new UserStorage();
User user1 = new User(1, 100);
User user2 = new User(2, 200);
storage.add(user1);
storage.add(user2);
var res = storage.transfer(1, 2, 50);
assertTrue(res);
assertThat(user1.getAmount(), is(50));
assertThat(user2.getAmount(), is(250));
}
@Test
public void whenCreate2UsersThenDeleteOneResultFalse() {
UserStorage storage = new UserStorage();
User user1 = new User(1, 100);
User user2 = new User(2, 200);
storage.add(user1);
storage.add(user2);
var resDel = storage.delete(user1);
var resTrans = storage.transfer(1, 2, 50);
assertTrue(resDel);
assertFalse(resTrans);
assertThat(user2.getAmount(), is(200));
}
@Test
public void whenAddOneUserThenReplaceItResultNewValue() {
UserStorage storage = new UserStorage();
User user1 = new User(1, 100);
User user2 = new User(2, 200);
User userNew = new User(1, 50);
storage.add(user1);
storage.add(user2);
var resRep = storage.update(userNew);
var res = storage.transfer(1, 2, 50);
assertTrue(resRep);
assertTrue(res);
assertThat(user1.getAmount(), is(100));
assertThat(userNew.getAmount(), is(0));
}
} |
3e15c450c7fc88d9e04acb1ea4c04025fa89edca | 4,892 | java | Java | src/main/java/am/ik/yavi/arguments/Arguments7Validator.java | JWThewes/yavi | 6f45c2926540c61c5c38222634eb842616cf5993 | [
"Apache-2.0"
] | null | null | null | src/main/java/am/ik/yavi/arguments/Arguments7Validator.java | JWThewes/yavi | 6f45c2926540c61c5c38222634eb842616cf5993 | [
"Apache-2.0"
] | null | null | null | src/main/java/am/ik/yavi/arguments/Arguments7Validator.java | JWThewes/yavi | 6f45c2926540c61c5c38222634eb842616cf5993 | [
"Apache-2.0"
] | null | null | null | 41.811966 | 154 | 0.724857 | 9,246 | /*
* Copyright (C) 2018-2020 Toshiaki Maki <upchh@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 am.ik.yavi.arguments;
import java.util.List;
import java.util.Locale;
import am.ik.yavi.core.CollectionValidator;
import am.ik.yavi.core.ConstraintCondition;
import am.ik.yavi.core.ConstraintGroup;
import am.ik.yavi.core.ConstraintPredicates;
import am.ik.yavi.core.ConstraintViolations;
import am.ik.yavi.core.ConstraintViolationsException;
import am.ik.yavi.core.Validator;
import am.ik.yavi.core.ValidatorSubset;
import am.ik.yavi.fn.Either;
import am.ik.yavi.fn.Pair;
import am.ik.yavi.message.MessageFormatter;
/**
* Generated by https://github.com/making/yavi/blob/develop/scripts/generate-args.sh
*
* @since 0.3.0
*/
public final class Arguments7Validator<A1, A2, A3, A4, A5, A6, A7, X>
extends Validator<Arguments7<A1, A2, A3, A4, A5, A6, A7>> {
private final Arguments7.Mapper<A1, A2, A3, A4, A5, A6, A7, X> mapper;
public Arguments7Validator(String messageKeySeparator,
List<ConstraintPredicates<Arguments7<A1, A2, A3, A4, A5, A6, A7>, ?>> constraintPredicates,
List<CollectionValidator<Arguments7<A1, A2, A3, A4, A5, A6, A7>, ?, ?>> collectionValidators,
List<Pair<ConstraintCondition<Arguments7<A1, A2, A3, A4, A5, A6, A7>>, ValidatorSubset<Arguments7<A1, A2, A3, A4, A5, A6, A7>>>> conditionalValidators,
MessageFormatter messageFormatter, Arguments7.Mapper<A1, A2, A3, A4, A5, A6, A7, X> mapper) {
super(messageKeySeparator, constraintPredicates, collectionValidators,
conditionalValidators, messageFormatter);
this.mapper = mapper;
}
public Either<ConstraintViolations, X> validateArgs(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) {
return this
.validateToEither(Arguments.of(a1, a2, a3, a4, a5, a6, a7), Locale.getDefault(),
ConstraintGroup.DEFAULT)
.rightMap(values -> values.map(this.mapper));
}
public Either<ConstraintViolations, X> validateArgs(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
ConstraintGroup constraintGroup) {
return this.validateToEither(Arguments.of(a1, a2, a3, a4, a5, a6, a7), Locale.getDefault(),
constraintGroup).rightMap(values -> values.map(this.mapper));
}
public Either<ConstraintViolations, X> validateArgs(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
Locale locale) {
return this
.validateToEither(Arguments.of(a1, a2, a3, a4, a5, a6, a7), locale,
ConstraintGroup.DEFAULT)
.rightMap(values -> values.map(this.mapper));
}
public Either<ConstraintViolations, X> validateArgs(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7,
Locale locale, ConstraintGroup constraintGroup) {
ConstraintViolations violations = this.validate(Arguments.of(a1, a2, a3, a4, a5, a6, a7), locale,
constraintGroup);
if (violations.isValid()) {
return Either.right(Arguments.of(a1, a2, a3, a4, a5, a6, a7).map(this.mapper));
}
else {
return Either.left(violations);
}
}
public ConstraintViolations validateOnly(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
A7 a7) {
return this.validate(Arguments.of(a1, a2, a3, a4, a5, a6, a7));
}
public ConstraintViolations validateOnly(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6,
A7 a7, ConstraintGroup constraintGroup) {
return this.validate(Arguments.of(a1, a2, a3, a4, a5, a6, a7), constraintGroup);
}
public X validated(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) throws ConstraintViolationsException {
return this.validateArgs(a1, a2, a3, a4, a5, a6, a7)
.rightOrElseThrow(ConstraintViolationsException::new);
}
public X validated(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, ConstraintGroup constraintGroup)
throws ConstraintViolationsException {
return this.validateArgs(a1, a2, a3, a4, a5, a6, a7, constraintGroup)
.rightOrElseThrow(ConstraintViolationsException::new);
}
public X validated(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, Locale locale) throws ConstraintViolationsException {
return this.validateArgs(a1, a2, a3, a4, a5, a6, a7, locale)
.rightOrElseThrow(ConstraintViolationsException::new);
}
public X validated(A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, Locale locale, ConstraintGroup constraintGroup)
throws ConstraintViolationsException {
return this.validateArgs(a1, a2, a3, a4, a5, a6, a7, locale, constraintGroup)
.rightOrElseThrow(ConstraintViolationsException::new);
}
}
|
3e15c5104a5261614354b9d6f85a5fe334e4b2f6 | 1,878 | java | Java | src/main/java/diyeats/logic/parsers/ParserUtil.java | AY1920S1-CS2113T-W13-4/main | ecd5062fa588fbb6045d2c9ea359a7ece34ce31c | [
"MIT"
] | 2 | 2019-09-10T15:44:09.000Z | 2019-10-21T08:37:50.000Z | src/main/java/diyeats/logic/parsers/ParserUtil.java | AY1920S1-CS2113T-W13-4/main | ecd5062fa588fbb6045d2c9ea359a7ece34ce31c | [
"MIT"
] | 136 | 2019-09-10T12:54:07.000Z | 2019-11-13T01:58:37.000Z | src/main/java/diyeats/logic/parsers/ParserUtil.java | AY1920S1-CS2113T-W13-4/main | ecd5062fa588fbb6045d2c9ea359a7ece34ce31c | [
"MIT"
] | 4 | 2019-09-17T14:44:34.000Z | 2020-02-12T15:01:04.000Z | 29.34375 | 79 | 0.643237 | 9,247 | package diyeats.logic.parsers;
import diyeats.commons.exceptions.ProgramException;
import diyeats.logic.autocorrect.Autocorrect;
import diyeats.logic.commands.HistoryCommand;
//@@author Fractalisk
/**
* Utility class to handle pre-parsing of user inputs.
*/
public class ParserUtil {
private Autocorrect autocorrect;
private static HistoryCommand history = new HistoryCommand(true);
private String command;
private String argument;
/**
* Constructor for ParserUtil.
* @param autocorrect the autocorrect object to be set
*/
public ParserUtil(Autocorrect autocorrect) {
this.autocorrect = autocorrect;
}
/**
* Parse fullCommand into command and arguments.
* @param fullCommand the full command entered by the user
* @throws ProgramException if the full command cannot be parsed
*/
public void parse(String fullCommand) throws ProgramException {
argument = "";
try {
String[] splitCommand = fullCommand.split(" ", 2);
if (splitCommand.length != 2) {
splitCommand = new String[]{splitCommand[0], ""};
}
command = splitCommand[0];
argument = splitCommand[1];
} catch (Exception e) {
throw new ProgramException("A parser error has been encountered.");
}
command = autocorrect.runOnCommand(command);
argument = autocorrect.runOnArgument(argument);
history.addCommand(command);
}
/**
* Getter for command.
* @return command The string containing the command made by the user.
*/
public String getCommand() {
return command;
}
/**
* Getter for argument.
* @return argument The string containing the arguments made by the user.
*/
public String getArgument() {
return argument;
}
}
|
3e15c528a53058f55800aa1ffcfb4445e6ddd841 | 2,178 | java | Java | src/main/java/com/helospark/lightdi/util/DependencyChooser.java | helospark/light-di | fd5e8d00f30ffa99a090a5be194eb453c1eb41c4 | [
"MIT"
] | 10 | 2018-01-06T19:21:10.000Z | 2021-06-09T16:28:50.000Z | src/main/java/com/helospark/lightdi/util/DependencyChooser.java | helospark/light-di | fd5e8d00f30ffa99a090a5be194eb453c1eb41c4 | [
"MIT"
] | 1 | 2019-07-04T08:27:34.000Z | 2019-07-13T16:02:42.000Z | src/main/java/com/helospark/lightdi/util/DependencyChooser.java | helospark/light-di | fd5e8d00f30ffa99a090a5be194eb453c1eb41c4 | [
"MIT"
] | null | null | null | 38.892857 | 138 | 0.698806 | 9,248 | package com.helospark.lightdi.util;
import java.util.Collection;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import com.helospark.lightdi.common.StreamFactory;
import com.helospark.lightdi.descriptor.DependencyDescriptor;
import com.helospark.lightdi.descriptor.DependencyDescriptorQuery;
public class DependencyChooser {
private StreamFactory streamFactory;
public DependencyChooser(StreamFactory streamFactory) {
this.streamFactory = streamFactory;
}
public DependencyDescriptor findDependencyFromQuery(Collection<DependencyDescriptor> dependencies, DependencyDescriptorQuery toFind) {
SortedSet<DependencyDescriptor> found = findDependencyDescriptor(dependencies, toFind);
return findDependencyToGenerate(found, toFind);
}
public SortedSet<DependencyDescriptor> findDependencyDescriptor(Collection<DependencyDescriptor> dependencies,
DependencyDescriptorQuery toFind) {
return streamFactory.stream(dependencies)
.filter(dependencyEntry -> dependencyEntry.doesMatch(toFind))
.collect(Collectors.toCollection(() -> new TreeSet<>()));
}
public DependencyDescriptor findDependencyToGenerate(SortedSet<DependencyDescriptor> dependencyToCreate,
DependencyDescriptorQuery toFind) {
if (dependencyToCreate.size() == 1) {
return dependencyToCreate.first();
} else {
Optional<DependencyDescriptor> primary = findPrimary(dependencyToCreate);
if (primary.isPresent()) {
return primary.get();
} else if (!toFind.isRequired()) {
return null;
} else {
throw new IllegalArgumentException("No single match for found for " + toFind + ", found " + dependencyToCreate);
}
}
}
public static Optional<DependencyDescriptor> findPrimary(
SortedSet<DependencyDescriptor> foundDependencies) {
return foundDependencies.stream()
.filter(dependency -> dependency.isPrimary())
.findFirst();
}
}
|
3e15c5f94607381a2ece026324e7c579d2d6c67e | 221 | java | Java | api/src/test/java/com/mmontsheng/library/LibrarySystemApplicationTests.java | Mmontsheng/library-system | 92d6364e867792404711a3a161fe443c2d05f88a | [
"MIT"
] | null | null | null | api/src/test/java/com/mmontsheng/library/LibrarySystemApplicationTests.java | Mmontsheng/library-system | 92d6364e867792404711a3a161fe443c2d05f88a | [
"MIT"
] | null | null | null | api/src/test/java/com/mmontsheng/library/LibrarySystemApplicationTests.java | Mmontsheng/library-system | 92d6364e867792404711a3a161fe443c2d05f88a | [
"MIT"
] | null | null | null | 15.785714 | 60 | 0.79638 | 9,249 | package com.mmontsheng.library;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class LibrarySystemApplicationTests {
@Test
void contextLoads() {
}
}
|
3e15c648108dbcfe700c5669f6b6446a4e749b38 | 741 | java | Java | cntrace-admin/src/main/java/io/cntrace/modules/oss/entity/SysOssEntity.java | zainwang1/cntrace-boot | c503d65914d1cb038943f04850b9bc0444eb2b62 | [
"Apache-2.0"
] | null | null | null | cntrace-admin/src/main/java/io/cntrace/modules/oss/entity/SysOssEntity.java | zainwang1/cntrace-boot | c503d65914d1cb038943f04850b9bc0444eb2b62 | [
"Apache-2.0"
] | 2 | 2021-04-22T17:08:13.000Z | 2021-09-20T20:58:28.000Z | cntrace-admin/src/main/java/io/cntrace/modules/oss/entity/SysOssEntity.java | zainwang1/cntrace-boot | c503d65914d1cb038943f04850b9bc0444eb2b62 | [
"Apache-2.0"
] | null | null | null | 17.302326 | 65 | 0.716398 | 9,250 | /**
* CCopyright © 2016-2025 中国追溯链-一带一路 All rights reserved.
*
* 中国追溯链.com
*
* 版权所有,侵权必究!
*/
package io.cntrace.modules.oss.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 文件上传
*
* @author Mark upchh@example.com
*/
@Data
@TableName("sys_oss")
public class SysOssEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId
private Long id;
/**
* URL地址
*/
private String url;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createDate;
}
|
3e15c64e010d774ff3ea53dd5bac6ac95fdde16f | 2,810 | java | Java | src/main/java/com/github/pettyfer/caas/framework/biz/service/impl/BizServiceDiscoveryServiceImpl.java | pettyferlove/caas-platform-backend | e653cd856f0692f2d254699da739e3693940befc | [
"Apache-2.0"
] | 1 | 2021-04-12T01:41:55.000Z | 2021-04-12T01:41:55.000Z | src/main/java/com/github/pettyfer/caas/framework/biz/service/impl/BizServiceDiscoveryServiceImpl.java | pettyferlove/caas-platform-backend | e653cd856f0692f2d254699da739e3693940befc | [
"Apache-2.0"
] | 1 | 2022-01-20T06:01:42.000Z | 2022-01-20T06:01:42.000Z | src/main/java/com/github/pettyfer/caas/framework/biz/service/impl/BizServiceDiscoveryServiceImpl.java | pettyferlove/caas-platform-backend | e653cd856f0692f2d254699da739e3693940befc | [
"Apache-2.0"
] | null | null | null | 40.142857 | 152 | 0.757295 | 9,251 | package com.github.pettyfer.caas.framework.biz.service.impl;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pettyfer.caas.framework.biz.entity.BizServiceDiscovery;
import com.github.pettyfer.caas.framework.biz.mapper.BizServiceDiscoveryMapper;
import com.github.pettyfer.caas.framework.biz.service.IBizServiceDiscoveryService;
import com.github.pettyfer.caas.global.exception.BaseRuntimeException;
import com.github.pettyfer.caas.utils.SecurityUtil;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.Objects;
/**
* <p>
* 服务实现类
* </p>
*
* @author Petty
* @since 2021-04-20
*/
@Service
public class BizServiceDiscoveryServiceImpl extends ServiceImpl<BizServiceDiscoveryMapper, BizServiceDiscovery> implements IBizServiceDiscoveryService {
@Override
public IPage<BizServiceDiscovery> page(String namespaceId, BizServiceDiscovery bizServiceDiscovery, Page<BizServiceDiscovery> page) {
LambdaQueryWrapper<BizServiceDiscovery> queryWrapper = Wrappers.<BizServiceDiscovery>lambdaQuery()
.eq(BizServiceDiscovery::getNamespaceId, namespaceId)
.ne(BizServiceDiscovery::getNetwork, "none")
.likeRight(StrUtil.isNotEmpty(bizServiceDiscovery.getName()), BizServiceDiscovery::getName, bizServiceDiscovery.getName())
.eq(ObjectUtil.isNotNull(bizServiceDiscovery.getEnvType()), BizServiceDiscovery::getEnvType, bizServiceDiscovery.getEnvType());
return this.page(page, queryWrapper);
}
@Override
public BizServiceDiscovery get(String id) {
return this.getById(id);
}
@Override
public Boolean delete(String id) {
return this.removeById(id);
}
@Override
public String create(BizServiceDiscovery bizServiceDiscovery) {
bizServiceDiscovery.setCreator(Objects.requireNonNull(SecurityUtil.getUser()).getId());
bizServiceDiscovery.setCreateTime(LocalDateTime.now());
if (this.save(bizServiceDiscovery)) {
return bizServiceDiscovery.getId();
} else {
throw new BaseRuntimeException("新增失败");
}
}
@Override
public Boolean update(BizServiceDiscovery bizServiceDiscovery) {
bizServiceDiscovery.setModifier(Objects.requireNonNull(SecurityUtil.getUser()).getId());
bizServiceDiscovery.setModifyTime(LocalDateTime.now());
return this.updateById(bizServiceDiscovery);
}
}
|
3e15c6590da4562ce2e5d5a2b4ef950fa6553784 | 12,277 | java | Java | CoreNLP/src/edu/stanford/nlp/international/spanish/SpanishVerbStripper.java | natemalek/molen-pater-nathan-rma-thesis-coreference-with-singletons | 3d2d6c751eadd6438a80b0c24f48b2635bc6acc7 | [
"MIT"
] | null | null | null | CoreNLP/src/edu/stanford/nlp/international/spanish/SpanishVerbStripper.java | natemalek/molen-pater-nathan-rma-thesis-coreference-with-singletons | 3d2d6c751eadd6438a80b0c24f48b2635bc6acc7 | [
"MIT"
] | null | null | null | CoreNLP/src/edu/stanford/nlp/international/spanish/SpanishVerbStripper.java | natemalek/molen-pater-nathan-rma-thesis-coreference-with-singletons | 3d2d6c751eadd6438a80b0c24f48b2635bc6acc7 | [
"MIT"
] | null | null | null | 32.307895 | 120 | 0.641525 | 9,252 | package edu.stanford.nlp.international.spanish;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.util.Pair;
import edu.stanford.nlp.util.logging.Redwood;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Provides a utility function for removing attached pronouns from
* Spanish verb forms.
*
* @author Jon Gauthier
* @author Ishita Prasad
*/
public final class SpanishVerbStripper implements Serializable {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(SpanishVerbStripper.class);
// The following three classes of verb forms can carry attached
// pronouns:
//
// - Infinitives
// - Gerunds
// - Affirmative imperatives
/**
* A struct describing the result of verb stripping.
*/
public static class StrippedVerb {
private String stem;
private String originalStem;
private List<String> pronouns;
public StrippedVerb(String originalStem, List<String> pronouns) {
this.originalStem = originalStem;
this.pronouns = pronouns;
}
public void setStem(String stem) {
this.stem = stem;
}
/**
* Return the normalized stem of the verb -- the way it would appear in
* isolation without attached pronouns.
*
* Here are example mappings from original verb to normalized stem:
*
* <ul>
* <li>sentaos -> sentad</li>
* <li>vámonos -> vamos</li>
* </ul>
*/
public String getStem() { return stem; }
/**
* Returns the original stem of the verb, simply split off from pronouns.
* (Contrast with {@link #getStem()}, which returns a normalized form.)
*/
public String getOriginalStem() { return originalStem; }
public List<String> getPronouns() { return pronouns; }
}
/* HashMap of singleton instances */
private static final Map<String, SpanishVerbStripper> instances = new HashMap<>();
private final HashMap<String, String> dict;
private static final String DEFAULT_DICT =
"edu/stanford/nlp/international/spanish/enclitic-inflections.data";
/** Any attached pronouns. The extra grouping around this pattern allows it to be used in String concatenations. */
private static final String PATTERN_ATTACHED_PRONOUNS =
"(?:(?:[mts]e|n?os|les?)(?:l[oa]s?)?|l[oa]s?)$";
private static final Pattern pTwoAttachedPronouns =
Pattern.compile("([mts]e|n?os|les?)(l[eoa]s?)$");
private static final Pattern pOneAttachedPronoun =
Pattern.compile("([mts]e|n?os|les?|l[oa]s?)$");
/**
* Matches infinitives and gerunds with attached pronouns.
* Original: Pattern.compile("(?:[aeiáéí]r|[áé]ndo)" + PATTERN_ATTACHED_PRONOUNS);
*/
private static final Pattern pStrippable =
Pattern.compile("(?:[aeiáéí]r|[áé]ndo|[aeáé]n?|[aeáé]mos?|[aeiáéí](?:d(?!os)|(?=os)))" + PATTERN_ATTACHED_PRONOUNS);
/**
* Matches irregular imperatives:
* decir = di, hacer = haz, ver = ve, poner = pon, salir = sal,
* ser = sé, tener = ten, venir = ven
* And id + os = idos, not ios
*/
private static final Pattern pIrregulars =
Pattern.compile("^(?:d[ií]|h[aá]z|v[eé]|p[oó]n|s[aá]l|sé|t[eé]n|v[eé]n|(?:id(?=os$)))" + PATTERN_ATTACHED_PRONOUNS);
/**
* Sets up dictionary of valid verbs and their POS info from an input file.
* The input file must be a list of whitespace-separated verb-lemma-POS triples, one verb
* form per line.
*
* @param dictPath the path to the dictionary file
*/
private static HashMap<String, String> setupDictionary(String dictPath) {
HashMap<String, String> dictionary = new HashMap<>();
BufferedReader br = null;
try {
br = IOUtils.readerFromString(dictPath);
for (String line; (line = br.readLine()) != null; ) {
String[] words = line.trim().split("\\s");
if (words.length < 3) {
System.err.printf("SpanishVerbStripper: adding words to dict, missing fields, ignoring line: %s%n", line);
} else {
dictionary.put(words[0], words[2]);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
log.info("Could not load Spanish data file " + dictPath);
} finally {
IOUtils.closeIgnoringExceptions(br);
}
return dictionary;
}
@SuppressWarnings("unchecked")
private static final Pair<Pattern, String>[] accentFixes = new Pair[] {
new Pair(Pattern.compile("á"), "a"),
new Pair(Pattern.compile("é"), "e"),
new Pair(Pattern.compile("í"), "i"),
new Pair(Pattern.compile("ó"), "o"),
new Pair(Pattern.compile("ú"), "u")
};
// CONSTRUCTOR
/** Access via the singleton-like getInstance() methods. */
private SpanishVerbStripper(String dictPath) {
dict = setupDictionary(dictPath);
}
/**
* Singleton pattern function for getting a default verb stripper.
*/
public static SpanishVerbStripper getInstance() {
return getInstance(DEFAULT_DICT);
}
/**
* Singleton pattern function for getting a verb stripper based on
* the dictionary at dictPath.
*
* @param dictPath the path to the dictionary for this verb stripper.
*/
public static SpanishVerbStripper getInstance(String dictPath) {
SpanishVerbStripper svs = instances.get(dictPath);
if (svs == null) {
svs = new SpanishVerbStripper(dictPath);
instances.put(dictPath, svs);
}
return svs;
}
/**
* The verbs in this set have accents in their infinitive forms;
* don't remove the accents when stripping pronouns!
*/
private static final Set<String> accentedInfinitives = new HashSet<>(Arrays.asList(
"desleír",
"desoír",
"embaír",
"engreír",
"entreoír",
"freír",
"oír",
"refreír",
"reír",
"sofreír",
"sonreír"
));
// STATIC FUNCTIONS
/**
* Determine if the given word is a verb which needs to be stripped.
*/
public static boolean isStrippable(String word) {
return pStrippable.matcher(word).find() || pIrregulars.matcher(word).find();
}
private static String removeAccents(String word) {
if (accentedInfinitives.contains(word))
return word;
String stripped = word;
for (Pair<Pattern, String> accentFix : accentFixes)
stripped = accentFix.first().matcher(stripped)
.replaceAll(accentFix.second());
return stripped;
}
/**
* Determines the case of the letter as if it had been part of the
* original string
*
* @param letter The character whose case must be determined
* @param original The string we are modelling the case on
*/
private static char getCase(String original, char letter) {
if (Character.isUpperCase(original.charAt(original.length()-1))) {
return Character.toUpperCase(letter);
} else {
return Character.toLowerCase(letter);
}
}
private static final Pattern nosse = Pattern.compile("nos|se");
/**
* Validate and normalize the given verb stripper result.
*
* Returns <tt>true</tt> if the given data is a valid pairing of verb form
* and clitic pronoun(s).
*
* May modify <tt>pair</tt> in place in order to make the pair valid.
* For example, if the pair <tt>(senta, os)</tt> is provided, this
* method will return <tt>true</tt> and modify the pair to be
* <tt>(sentad, os)</tt>.
*/
private boolean normalizeStrippedVerb(StrippedVerb verb) {
String normalized = removeAccents(verb.getOriginalStem());
String firstPron = verb.getPronouns().get(0).toLowerCase();
// Look up verb in dictionary.
String verbKey = normalized.toLowerCase();
String pos = dict.get(verbKey);
boolean valid = false;
// System.out.println(verbKey + " " + dict.containsKey(verbKey + 's'));
// Validate resulting split verb and normalize the new form at the same
// time.
if (pos != null) {
// Check not invalid combination of verb root and pronoun.
// (If we combine a second-person plural imperative and the
// second person plural object pronoun, we expect to see an
// elided verb root, not the normal one that's in the
// dictionary.)
valid = ! (pos.equals("VMM02P0") && firstPron.equalsIgnoreCase("os"));
} else if (firstPron.equalsIgnoreCase("os") && dict.containsKey(verbKey + 'd')) {
// Special case: de-elide elided verb root in the case of a second
// person plural imperative + second person object pronoun
//
// (e.g., given (senta, os), return (sentad, os))
normalized = normalized + getCase(normalized, 'd');
valid = true;
} else if (nosse.matcher(firstPron).matches() && dict.containsKey(verbKey + 's')) {
// Special case: de-elide elided verb root in the case of a first
// person plural imperative + object pronoun
//
// (vámo, nos) -> (vámos, nos)
normalized = normalized + getCase(normalized, 's');
valid = true;
}
if (valid) {
// Update normalized form.
verb.setStem(normalized);
return true;
}
return false;
}
/**
* Separate attached pronouns from the given verb.
*
* @param word A valid Spanish verb with clitic pronouns attached.
* @param pSuffix A pattern to match these attached pronouns.
* @return A {@link StrippedVerb} instance or <tt>null</tt> if no attached
* pronouns were found.
*/
private StrippedVerb stripSuffix(String word, Pattern pSuffix) {
Matcher m = pSuffix.matcher(word);
if (m.find()) {
String stripped = word.substring(0, m.start());
List<String> attached = new ArrayList<>();
for (int i = 0; i < m.groupCount(); i++)
attached.add(m.group(i + 1));
return new StrippedVerb(stripped, attached);
}
return null;
}
/**
* Attempt to separate attached pronouns from the given verb.
*
* @param verb Spanish verb
* @return Returns a tuple <tt>((originalStem, normalizedStem), pronouns)</tt>,
* or <tt>null</tt> if no pronouns could be located and separated.
* <ul>
* <li>Pair of:
* <ul>
* <li><tt>originalStem</tt>: The verb stem simply split from the
* following pronouns.</li>
* <li><tt>normalizedStem</tt>: The verb stem normalized to
* dictionary form, i.e. in the form it would appear with the
* same conjugation but no pronouns. See
* {@link #validateVerbPair(Pair<Pair<String, String>, List<String>)}
* for more details.</li>
* </ul></li>
* <li><tt>pronouns</tt>: Pronouns which were attached to the verb.</li>
* </ul>
*/
public StrippedVerb separatePronouns(String verb) {
StrippedVerb result;
// Try to strip just one pronoun first
result = stripSuffix(verb, pOneAttachedPronoun);
if (result != null && normalizeStrippedVerb(result)) {
return result;
}
// Now two
result = stripSuffix(verb, pTwoAttachedPronouns);
if (result != null && normalizeStrippedVerb(result)) {
return result;
}
return null;
}
/**
* Remove attached pronouns from a strippable Spanish verb form. (Use
* {@link #isStrippable(String)} to determine if a word is a
* strippable verb.)
*
* Converts, e.g.,
* <ul>
* <li> decírmelo -> decir
* <li> mudarse -> mudar
* <li> contándolos -> contando
* <li> hazlo -> haz
* </ul>
*
* @return A verb form stripped of attached pronouns, or <tt>null</tt>
* if no pronouns were located / stripped.
*/
public String stripVerb(String verb) {
StrippedVerb separated = separatePronouns(verb);
if (separated != null) {
return separated.getStem();
}
return null;
}
private static final long serialVersionUID = -4780144226395772354L;
}
|
3e15c6cb6a4bf3bcf375ece0d336a19d6406683f | 3,259 | java | Java | examples/basic/src/test/java/io/github/jlmc/jpa/BookEntityQueriesTest.java | jlmc/jpa-junit5-extensions | b06292b33ed8ac5b86eb7fca9b358cb9a1eb1a62 | [
"Apache-2.0"
] | null | null | null | examples/basic/src/test/java/io/github/jlmc/jpa/BookEntityQueriesTest.java | jlmc/jpa-junit5-extensions | b06292b33ed8ac5b86eb7fca9b358cb9a1eb1a62 | [
"Apache-2.0"
] | 2 | 2022-01-21T23:44:17.000Z | 2022-01-21T23:44:41.000Z | examples/basic/src/test/java/io/github/jlmc/jpa/BookEntityQueriesTest.java | jlmc/jpa-junit5-extensions | b06292b33ed8ac5b86eb7fca9b358cb9a1eb1a62 | [
"Apache-2.0"
] | null | null | null | 31.038095 | 114 | 0.635471 | 9,253 | package io.github.jlmc.jpa;
import io.github.jlmc.jpa.test.annotation.JpaContext;
import io.github.jlmc.jpa.test.annotation.JpaTest;
import io.github.jlmc.jpa.test.annotation.Sql;
import io.github.jlmc.jpa.test.junit.JpaProvider;
import org.hibernate.annotations.QueryHints;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayNameGeneration;
import org.junit.jupiter.api.DisplayNameGenerator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import javax.persistence.EntityManager;
import java.util.List;
import static io.github.jlmc.jpa.test.annotation.Sql.Phase.AFTER_TEST_METHOD;
import static io.github.jlmc.jpa.test.annotation.Sql.Phase.BEFORE_TEST_METHOD;
import static org.junit.jupiter.api.Assertions.assertEquals;
@JpaTest(persistenceUnit = "it")
@Sql(
statements = {
"insert into book (id, title) values (9901, 'Mastering Java 11')",
"insert into book (id, title) values (9902, 'Refactoring. Improving the Design of Existing Code')"
},
phase = BEFORE_TEST_METHOD
)
@Sql(
statements = "delete from book where true",
phase = AFTER_TEST_METHOD)
@DisplayNameGeneration(DisplayNameGenerator.Standard.class)
class BookEntityQueriesTest {
@JpaContext
JpaProvider jpa;
@ParameterizedTest
@ValueSource(ints = {9901, 9902})
void findBookById(int bookId) {
final Book book = jpa.em().find(Book.class, bookId);
Assertions.assertNotNull(book);
assertEquals(bookId, book.getId());
}
@Test
void createBook() {
EntityManager em = jpa.em();
em.getTransaction().begin();
em.persist(new Book().setTitle("The Great Gatsby"));
em.getTransaction().commit();
em.close();
}
@Test
void findAllBooks() {
List<Book> books = jpa.em()
.createQuery("select b from Book b", Book.class)
.getResultList();
assertEquals(2, books.size());
}
@Test
void createAndGetBook() {
Book savedBook = jpa.doInTxWithReturn(em -> {
final Book newBook = new Book().setTitle("do In Tx");
em.persist(newBook);
return newBook;
});
final Book book = jpa.em().find(Book.class, savedBook.getId());
Assertions.assertNotSame(savedBook, book);
assertEquals(savedBook.getId(), book.getId());
assertEquals(savedBook.getTitle(), book.getTitle());
}
@Test
void updateBookTitle() {
final int bookId = 9901;
jpa.doInTx(em -> {
final Book book = em.find(Book.class, bookId);
book.setTitle(book.getTitle().toUpperCase());
});
//@formatter:off
final Book book = jpa
.em()
.createQuery("select b from Book b where b.id = :id", Book.class)
.setParameter("id", bookId)
.setHint(QueryHints.FETCH_SIZE, 1)
.setHint(QueryHints.READ_ONLY, true)
.getSingleResult();
//@formatter:on
assertEquals("Mastering Java 11".toUpperCase(), book.getTitle());
}
} |
3e15c6d53685f94bc0179876b5ea1600818d993f | 3,725 | java | Java | support/flyway/src/main/java/io/zephyr/support/flyway/ClasspathModuleResourceProvider.java | josiahhaswell/zephyr | 6cb5d0ae0493bb61a7d759a9b302241f6a661e45 | [
"MIT"
] | 34 | 2019-12-04T14:21:11.000Z | 2022-03-03T07:22:53.000Z | support/flyway/src/main/java/io/zephyr/support/flyway/ClasspathModuleResourceProvider.java | josiahhaswell/zephyr | 6cb5d0ae0493bb61a7d759a9b302241f6a661e45 | [
"MIT"
] | 68 | 2020-01-02T19:19:37.000Z | 2022-02-26T00:41:59.000Z | support/flyway/src/main/java/io/zephyr/support/flyway/ClasspathModuleResourceProvider.java | josiahhaswell/zephyr | 6cb5d0ae0493bb61a7d759a9b302241f6a661e45 | [
"MIT"
] | 4 | 2021-10-02T07:46:21.000Z | 2022-01-14T14:01:49.000Z | 31.567797 | 98 | 0.681342 | 9,254 | package io.zephyr.support.flyway;
import io.zephyr.kernel.Module;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Level;
import java.util.regex.Pattern;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import lombok.extern.java.Log;
import lombok.val;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.ResourceProvider;
import org.flywaydb.core.api.resource.LoadableResource;
@Log
public class ClasspathModuleResourceProvider implements ResourceProvider {
private final Module module;
private final List<String> locations;
private final boolean searchSubAssemblies;
private final Map<String, LoadableResource> resources;
public ClasspathModuleResourceProvider(Module module, String... locations) {
this(module, false, locations);
}
public ClasspathModuleResourceProvider(
Module module, boolean searchSubAssemblies, String... locations) {
this.module = Objects.requireNonNull(module, "Module must not be null");
validate(locations);
this.locations = Arrays.asList(locations);
this.resources = new LinkedHashMap<>();
this.searchSubAssemblies = searchSubAssemblies;
}
@Override
public LoadableResource getResource(String name) {
return resources.get(name);
}
@Override
public Collection<LoadableResource> getResources(String prefix, String[] suffixes) {
resources.clear();
loadResourcesIn(module.getAssembly().getFile(), prefix, suffixes);
if (searchSubAssemblies) {
for (val library : module.getAssembly().getLibraries()) {
loadResourcesIn(library.getFile(), prefix, suffixes);
}
}
return Collections.unmodifiableCollection(resources.values());
}
private void loadResourcesIn(File file, String prefix, String[] suffixes) {
try {
loadResources(file, prefix, suffixes);
} catch (ZipException ex) {
log.log(Level.WARNING, "Error opening assembly file: ''{0}''", ex.getMessage());
}
}
private void validate(String[] locations) {
if (locations.length == 0) {
throw new IllegalArgumentException("Error: locations must not be empty");
}
}
private void loadResources(File assemblyFile, String prefix, String[] suffixes)
throws ZipException {
try (val file = new ZipFile(assemblyFile)) {
for (val location : locations) {
var normalizedLocation = location;
if (isWar(file)) {
normalizedLocation = "WEB-INF/classes/" + location;
}
val entries = file.entries();
while (entries.hasMoreElements()) {
val next = entries.nextElement();
val nextSegs = next.getName().split(Pattern.quote("/"));
val nextName = nextSegs[nextSegs.length - 1];
if (!next.isDirectory()
&& next.getName().startsWith(normalizedLocation)
&& nextName.startsWith(prefix)
&& endsWith(nextName, suffixes)) {
resources.put(
next.getName(),
new ModuleLoadableResource(module.getAssembly().getFile(), file, next, location));
}
}
}
} catch (ZipException ex) {
throw ex;
} catch (IOException ex) {
throw new FlywayException(ex);
}
}
private boolean endsWith(String next, String[] suffixes) {
for (val suffix : suffixes) {
if (next.endsWith(suffix)) {
return true;
}
}
return false;
}
private boolean isWar(ZipFile file) {
return file.getEntry("WEB-INF/classes") != null;
}
}
|
3e15c764e10ed44c1a730ec06ec2edfff5d5cae8 | 1,209 | java | Java | src/main/java/com/github/linfeng/controller/UserController.java | linfeng56/spring-weixin | 07c596f05aa4d46f41e49a1244e28a7f4b25f023 | [
"MIT"
] | 1 | 2022-03-18T02:49:29.000Z | 2022-03-18T02:49:29.000Z | src/main/java/com/github/linfeng/controller/UserController.java | linfeng56/spring-weixin | 07c596f05aa4d46f41e49a1244e28a7f4b25f023 | [
"MIT"
] | null | null | null | src/main/java/com/github/linfeng/controller/UserController.java | linfeng56/spring-weixin | 07c596f05aa4d46f41e49a1244e28a7f4b25f023 | [
"MIT"
] | null | null | null | 25.723404 | 75 | 0.717949 | 9,255 | package com.github.linfeng.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSONObject;
import com.github.linfeng.entity.Users;
import com.github.linfeng.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 默认控制器
*
* @author 黄麟峰
*/
@Controller
@RequestMapping("/mini/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 默认列表
*
* @return 列表
*/
@RequestMapping(value = "/list", produces = "text/plain;charset=utf-8")
@ResponseBody
public String list(HttpServletRequest request, Model model) {
List<Users> users = userService.list();
Map<String, Object> result = new HashMap<>(6);
result.put("status", "success");
result.put("userList", users);
String retData = JSONObject.toJSONString(result);
return retData;
}
}
|
3e15c8045216ad4ffa0539fb5d02caf6825f575e | 283 | java | Java | src/main/java/top/aaronysj/rss/datasource/DataSource.java | aaronysj/Rss-SpringBoot | 9c7183f0ef9e3fa00575a797dfbb39854e264f90 | [
"Apache-2.0"
] | 1 | 2021-10-04T01:05:31.000Z | 2021-10-04T01:05:31.000Z | src/main/java/top/aaronysj/rss/datasource/DataSource.java | aaronysj/Rss-SpringBoot | 9c7183f0ef9e3fa00575a797dfbb39854e264f90 | [
"Apache-2.0"
] | null | null | null | src/main/java/top/aaronysj/rss/datasource/DataSource.java | aaronysj/Rss-SpringBoot | 9c7183f0ef9e3fa00575a797dfbb39854e264f90 | [
"Apache-2.0"
] | null | null | null | 12.304348 | 36 | 0.54417 | 9,256 | package top.aaronysj.rss.datasource;
/**
* 数据源接口
*
* @author aaronysj
* @date 11/14/21
*/
public interface DataSource {
/**
* 获取数据,并通过 mq 发送出去
* @param data 数据时间
*/
void produceData(String data);
/**
* 初始化
*/
default void init(){}
}
|
3e15c843565e096a8363293ccf3c3468f9d78cd0 | 3,356 | java | Java | src/test/java/seedu/address/storage/JsonAdaptedCourseTest.java | monikernemo/main | 2df46bc0c6659cdd1004bb7d60faffe23d3389e4 | [
"MIT"
] | null | null | null | src/test/java/seedu/address/storage/JsonAdaptedCourseTest.java | monikernemo/main | 2df46bc0c6659cdd1004bb7d60faffe23d3389e4 | [
"MIT"
] | 64 | 2019-02-20T03:38:08.000Z | 2019-07-26T07:19:54.000Z | src/test/java/seedu/address/storage/JsonAdaptedCourseTest.java | monikernemo/main | 2df46bc0c6659cdd1004bb7d60faffe23d3389e4 | [
"MIT"
] | 9 | 2019-02-04T07:08:38.000Z | 2019-02-22T11:20:07.000Z | 46.611111 | 118 | 0.778308 | 9,257 | package seedu.address.storage;
import static org.junit.Assert.assertEquals;
import static seedu.address.storage.coursestorage.JsonAdaptedCourse.MISSING_FIELD_MESSAGE_FORMAT;
import static seedu.address.testutil.Assert.assertThrows;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Test;
import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.course.CompositeRequirement;
import seedu.address.model.course.Course;
import seedu.address.model.course.CourseDescription;
import seedu.address.model.course.CourseName;
import seedu.address.model.course.PrimitiveRequirement;
import seedu.address.model.util.SampleCourse;
import seedu.address.storage.coursestorage.JsonAdaptedCompositeRequirement;
import seedu.address.storage.coursestorage.JsonAdaptedCourse;
import seedu.address.storage.coursestorage.JsonAdaptedCourseRequirement;
import seedu.address.storage.coursestorage.JsonAdaptedPrimitiveRequirement;
public class JsonAdaptedCourseTest {
private final Course algorithms = SampleCourse.COMPUTER_SCIENCE_ALGORITHMS;
private final String courseName = algorithms.getCourseName().toString();
private final String courseDesc = algorithms.getCourseDescription().toString();
private final List<JsonAdaptedCourseRequirement> courseRequirements =
algorithms.getCourseRequirements().stream()
.map(courseRequirement -> courseRequirement instanceof CompositeRequirement
? new JsonAdaptedCompositeRequirement((CompositeRequirement) courseRequirement)
: new JsonAdaptedPrimitiveRequirement((PrimitiveRequirement) courseRequirement))
.collect(Collectors.toList());
private final String invalidName = "!@^%^";
private final String invalidDesc = " description";
@Test
public void toModelType_validCourse_returnsCourse() throws Exception {
JsonAdaptedCourse test = new JsonAdaptedCourse(algorithms);
assertEquals(algorithms, test.toModelType());
}
@Test
public void toModelType_missingName_throwsIllegalValueException() {
JsonAdaptedCourse test = new JsonAdaptedCourse(null, courseDesc, courseRequirements);
String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, CourseName.class.getSimpleName());
assertThrows(IllegalValueException.class, expectedMessage, test::toModelType);
}
@Test
public void toModelType_invalidName_throwsIllegalValueException() {
JsonAdaptedCourse test = new JsonAdaptedCourse(invalidName, courseDesc, courseRequirements);
assertThrows(IllegalValueException.class, test::toModelType);
}
@Test
public void toModelType_missingDesc_throwsIllegalValueException() {
JsonAdaptedCourse test = new JsonAdaptedCourse(courseName, null , courseRequirements);
String expectedMessage = String.format(MISSING_FIELD_MESSAGE_FORMAT, CourseDescription.class.getSimpleName());
assertThrows(IllegalValueException.class, expectedMessage, test::toModelType);
}
@Test
public void toModelType_invalidDesc_throwsIllegalValueException() {
JsonAdaptedCourse test = new JsonAdaptedCourse(courseName, invalidDesc, courseRequirements);
assertThrows(IllegalValueException.class, test::toModelType);
}
}
|
3e15c95c30f055e0831c958cc523c681ab0db198 | 1,084 | java | Java | sdk/storage/mgmt/src/main/java/com/azure/management/storage/implementation/StorageSkusImpl.java | Azure-Fluent/azure-sdk-for-java | c123e88d3e78b3d1b81a977aae0646220457f2c1 | [
"MIT"
] | 1 | 2020-10-05T18:51:27.000Z | 2020-10-05T18:51:27.000Z | sdk/storage/mgmt/src/main/java/com/azure/management/storage/implementation/StorageSkusImpl.java | Azure-Fluent/azure-sdk-for-java | c123e88d3e78b3d1b81a977aae0646220457f2c1 | [
"MIT"
] | 24 | 2020-05-27T05:21:27.000Z | 2021-06-25T15:37:42.000Z | sdk/storage/mgmt/src/main/java/com/azure/management/storage/implementation/StorageSkusImpl.java | Azure-Fluent/azure-sdk-for-java | c123e88d3e78b3d1b81a977aae0646220457f2c1 | [
"MIT"
] | null | null | null | 26.439024 | 69 | 0.714945 | 9,258 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.management.storage.implementation;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.management.storage.StorageSku;
import com.azure.management.storage.StorageSkus;
import com.azure.management.storage.models.SkusInner;
/** The implementation for {@link StorageSkus}. */
class StorageSkusImpl implements StorageSkus {
private final StorageManager manager;
StorageSkusImpl(StorageManager storageManager) {
this.manager = storageManager;
}
@Override
public StorageManager manager() {
return this.manager;
}
@Override
public PagedIterable<StorageSku> list() {
return this.inner().list().mapPage(StorageSkuImpl::new);
}
@Override
public PagedFlux<StorageSku> listAsync() {
return this.inner().listAsync().mapPage(StorageSkuImpl::new);
}
@Override
public SkusInner inner() {
return manager.inner().skus();
}
}
|
3e15c98c9a0c6067de5e81924854875c50994632 | 2,221 | java | Java | netconf-server-modelnode-fwk/src/main/java/org/broadband_forum/obbaa/netconf/mn/fwk/server/model/EditContext.java | BroadbandForum/obbaa-netconf-stack | 1895ed252d27863c4a01f2ae1f3ed51a7424ffc4 | [
"Apache-2.0"
] | 2 | 2021-04-26T16:11:56.000Z | 2022-03-01T06:41:29.000Z | netconf-server-modelnode-fwk/src/main/java/org/broadband_forum/obbaa/netconf/mn/fwk/server/model/EditContext.java | BroadbandForum/obbaa-netconf-stack | 1895ed252d27863c4a01f2ae1f3ed51a7424ffc4 | [
"Apache-2.0"
] | 3 | 2020-03-13T13:10:37.000Z | 2021-03-31T21:08:50.000Z | netconf-server-modelnode-fwk/src/main/java/org/broadband_forum/obbaa/netconf/mn/fwk/server/model/EditContext.java | BroadbandForum/obbaa-netconf-stack | 1895ed252d27863c4a01f2ae1f3ed51a7424ffc4 | [
"Apache-2.0"
] | 2 | 2019-05-15T05:44:37.000Z | 2021-09-05T07:38:39.000Z | 31.728571 | 145 | 0.725799 | 9,259 | package org.broadband_forum.obbaa.netconf.mn.fwk.server.model;
import org.broadband_forum.obbaa.netconf.api.client.NetconfClientInfo;
import org.broadband_forum.obbaa.netconf.api.messages.EditConfigErrorOptions;
public class EditContext {
public EditContainmentNode m_editNode;
public NotificationContext m_notificationContext;
private String m_errorOption = EditConfigErrorOptions.ROLLBACK_ON_ERROR;
private NetconfClientInfo m_clientInfo;
private EditContext m_parent;
public EditContext(EditContainmentNode editNode, NotificationContext notificationContext, String errorOption, NetconfClientInfo clientInfo) {
m_editNode = editNode;
m_notificationContext = notificationContext;
m_errorOption = errorOption;
m_clientInfo = clientInfo;
}
public EditContext(EditContext that) {
m_editNode = new EditContainmentNode(that.getEditNode());
m_notificationContext = that.getNotificationContext();
m_errorOption = that.getErrorOption();
m_clientInfo = that.getClientInfo();
}
public EditContainmentNode getEditNode() {
return m_editNode;
}
public EditContext setEditNode(EditContainmentNode editNode) {
m_editNode = editNode;
return this;
}
public EditContext appendNotificationInfo(NotificationInfo info){
m_notificationContext.appendNotificationInfo(info);
return this;
}
public NotificationContext getNotificationContext() {
return m_notificationContext;
}
public String getErrorOption() {
return m_errorOption ;
}
public EditContext setErrorOption(String errorOption) {
m_errorOption = errorOption;
return this;
}
public NetconfClientInfo getClientInfo() {
return m_clientInfo;
}
public void setClientInfo(NetconfClientInfo clientInfo) {
this.m_clientInfo = clientInfo;
}
@Override
public String toString() {
return "EditContext [m_editNode=" + m_editNode + ", m_clientInfo=" + m_clientInfo + "]";
}
public void setParentContext(EditContext parentContext) {
m_parent = parentContext;
}
public EditContext getParent() {
return m_parent;
}
} |
3e15c9a04c8c4d5ebc11756dfcbb96a2dce6ee05 | 1,499 | java | Java | core/src/main/java/io/github/scroojalix/npcmanager/common/storage/StorageFactory.java | Scroojalix/NPCManager | 7a5b950ab72460d1c17aba3e0946603a38d256b6 | [
"MIT"
] | 5 | 2020-12-23T10:08:56.000Z | 2022-02-03T07:58:55.000Z | core/src/main/java/io/github/scroojalix/npcmanager/common/storage/StorageFactory.java | Scroojalix/NPCManager | 7a5b950ab72460d1c17aba3e0946603a38d256b6 | [
"MIT"
] | 13 | 2020-10-28T00:42:54.000Z | 2021-06-23T12:42:49.000Z | core/src/main/java/io/github/scroojalix/npcmanager/common/storage/StorageFactory.java | Scroojalix/NPCManager | 7a5b950ab72460d1c17aba3e0946603a38d256b6 | [
"MIT"
] | null | null | null | 33.311111 | 102 | 0.678452 | 9,260 | package io.github.scroojalix.npcmanager.common.storage;
import java.util.logging.Level;
import io.github.scroojalix.npcmanager.NPCMain;
import io.github.scroojalix.npcmanager.common.storage.implementation.JsonStorage;
import io.github.scroojalix.npcmanager.common.storage.implementation.MongoStorage;
import io.github.scroojalix.npcmanager.common.storage.implementation.MySQLStorage;
import io.github.scroojalix.npcmanager.common.storage.implementation.interfaces.StorageImplementation;
public class StorageFactory {
private NPCMain main;
private StorageType type;
public StorageFactory(NPCMain main) {
this.main = main;
this.type = StorageType.parse(main.getConfig().getString("save-method"));
}
public StorageType getType() {
return this.type;
}
public Storage getInstance() {
this.main.log(Level.INFO, "Loading storage provider... [" + type.getName() + "]");
Storage storage = new Storage(this.main, createNewImplementation(type));
storage.init();
return storage;
}
public StorageImplementation createNewImplementation(StorageType type) {
switch (type) {
case JSON:
return new JsonStorage(main);
case MYSQL:
return new MySQLStorage(main);
case MONGODB:
return new MongoStorage(main);
default:
throw new RuntimeException("Unknown storage type: " + type);
}
}
}
|
3e15cac95f9b336bf785ecf78de3a4f85de9823a | 3,040 | java | Java | hydrograph.ui/hydrograph.ui.common.datastructures/src/main/java/hydrograph/ui/datastructure/property/FTPProtocolDetails.java | oleksiy/Hydrograph | 52836a0b7cecb84079a3edadfdd4ac7497eb2fde | [
"Apache-2.0"
] | 129 | 2017-03-11T05:18:14.000Z | 2018-10-31T21:50:58.000Z | hydrograph.ui/hydrograph.ui.common.datastructures/src/main/java/hydrograph/ui/datastructure/property/FTPProtocolDetails.java | oleksiy/Hydrograph | 52836a0b7cecb84079a3edadfdd4ac7497eb2fde | [
"Apache-2.0"
] | 58 | 2017-03-14T19:55:48.000Z | 2018-09-19T15:48:31.000Z | hydrograph.ui/hydrograph.ui.common.datastructures/src/main/java/hydrograph/ui/datastructure/property/FTPProtocolDetails.java | oleksiy/Hydrograph | 52836a0b7cecb84079a3edadfdd4ac7497eb2fde | [
"Apache-2.0"
] | 116 | 2017-03-11T05:18:16.000Z | 2018-10-27T16:48:19.000Z | 24.32 | 96 | 0.636184 | 9,261 | /********************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.ui.datastructure.property;
import hydrograph.ui.common.cloneableinterface.IDataStructure;
/**
* The Class FTPProtocolDetails persists FTP protocol details
* @author Bitwise
*
*/
public class FTPProtocolDetails implements IDataStructure{
private String protocol = "FTP";
private String host;
private String port;
public FTPProtocolDetails(String protocol, String host, String port) {
this.protocol = protocol;
this.host = host;
this.port = port;
}
/**
* @return protocol
*/
public String getProtocol() {
return protocol;
}
/**
* @param protocol
*/
public void setProtocol(String protocol) {
this.protocol = protocol;
}
/**
* @return host
*/
public String getHost() {
return host;
}
/**
* @param host
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return port
*/
public String getPort() {
return port;
}
/**
* @param port
*/
public void setPort(String port) {
this.port = port;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((host == null) ? 0 : host.hashCode());
result = prime * result + ((port == null) ? 0 : port.hashCode());
result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
return result;
}
@Override
public FTPProtocolDetails clone() {
FTPProtocolDetails ftpProtocolDetails = new FTPProtocolDetails(getProtocol(),
getHost(), getPort());
return ftpProtocolDetails;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FTPProtocolDetails other = (FTPProtocolDetails) obj;
if (host == null) {
if (other.host != null)
return false;
} else if (!host.equals(other.host))
return false;
if (port == null) {
if (other.port != null)
return false;
} else if (!port.equals(other.port))
return false;
if (protocol == null) {
if (other.protocol != null)
return false;
} else if (!protocol.equals(other.protocol))
return false;
return true;
}
@Override
public String toString() {
return "FTPProtocolDetails [protocol=" + protocol + ", host=" + host + ", port=" + port + "]";
}
}
|
3e15cad0f38f698119cb333311b887800bf87673 | 1,830 | java | Java | src/integrations/spigot-1.16/work/decompile-d7866d9c/net/minecraft/world/level/newbiome/layer/GenLayerDesert.java | alexjvan/BrokenCube | 2b7c8ae2ada23ba3d0831738d2b46acb85f68289 | [
"Apache-2.0"
] | 1 | 2021-03-19T06:10:32.000Z | 2021-03-19T06:10:32.000Z | src/integrations/spigot-1.16/work/decompile-d7866d9c/net/minecraft/world/level/newbiome/layer/GenLayerDesert.java | alexjvan/BrokenCube | 2b7c8ae2ada23ba3d0831738d2b46acb85f68289 | [
"Apache-2.0"
] | null | null | null | src/integrations/spigot-1.16/work/decompile-d7866d9c/net/minecraft/world/level/newbiome/layer/GenLayerDesert.java | alexjvan/BrokenCube | 2b7c8ae2ada23ba3d0831738d2b46acb85f68289 | [
"Apache-2.0"
] | null | null | null | 30.5 | 154 | 0.413661 | 9,262 | package net.minecraft.world.level.newbiome.layer;
import net.minecraft.world.level.newbiome.context.WorldGenContext;
import net.minecraft.world.level.newbiome.layer.traits.AreaTransformer7;
public enum GenLayerDesert implements AreaTransformer7 {
INSTANCE;
private GenLayerDesert() {}
@Override
public int a(WorldGenContext worldgencontext, int i, int j, int k, int l, int i1) {
int[] aint = new int[1];
if (!this.a(aint, i1) && !this.a(aint, i, j, k, l, i1, 38, 37) && !this.a(aint, i, j, k, l, i1, 39, 37) && !this.a(aint, i, j, k, l, i1, 32, 5)) {
if (i1 == 2 && (i == 12 || j == 12 || l == 12 || k == 12)) {
return 34;
} else {
if (i1 == 6) {
if (i == 2 || j == 2 || l == 2 || k == 2 || i == 30 || j == 30 || l == 30 || k == 30 || i == 12 || j == 12 || l == 12 || k == 12) {
return 1;
}
if (i == 21 || k == 21 || j == 21 || l == 21 || i == 168 || k == 168 || j == 168 || l == 168) {
return 23;
}
}
return i1;
}
} else {
return aint[0];
}
}
private boolean a(int[] aint, int i) {
if (!GenLayers.a(i, 3)) {
return false;
} else {
aint[0] = i;
return true;
}
}
private boolean a(int[] aint, int i, int j, int k, int l, int i1, int j1, int k1) {
if (i1 != j1) {
return false;
} else {
if (GenLayers.a(i, j1) && GenLayers.a(j, j1) && GenLayers.a(l, j1) && GenLayers.a(k, j1)) {
aint[0] = i1;
} else {
aint[0] = k1;
}
return true;
}
}
}
|
3e15cafee63c71b3ae3e0850c0a319a7f027767d | 601 | java | Java | Aulas/Base/EntradaDeDados/src/Account.java | AndrewMarques2018/AprendendoJava | 67b2ff675c84c3ec5b5aa49f4b404c54ad8d2a9f | [
"MIT"
] | null | null | null | Aulas/Base/EntradaDeDados/src/Account.java | AndrewMarques2018/AprendendoJava | 67b2ff675c84c3ec5b5aa49f4b404c54ad8d2a9f | [
"MIT"
] | null | null | null | Aulas/Base/EntradaDeDados/src/Account.java | AndrewMarques2018/AprendendoJava | 67b2ff675c84c3ec5b5aa49f4b404c54ad8d2a9f | [
"MIT"
] | null | null | null | 16.694444 | 49 | 0.552413 | 9,263 | public class Account {
private String name;
private double balance;
public Account (String name, double balance){
this.name = name;
if (balance >= 0.0) {
this.balance = balance;
}
}
public void deposit ( double amount ){
this.balance += amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
|
3e15cb031fc6653689dd2ee4ccb84916db9ffe26 | 1,051 | java | Java | src/test/java/no/jsosi/EnheterGrunnkretsTest.java | halset/jsosi | 56d9f3943327ecdb4eda015c2e136be2732e9753 | [
"Apache-2.0"
] | 2 | 2015-09-21T17:24:37.000Z | 2022-03-01T11:13:49.000Z | src/test/java/no/jsosi/EnheterGrunnkretsTest.java | halset/jsosi | 56d9f3943327ecdb4eda015c2e136be2732e9753 | [
"Apache-2.0"
] | 4 | 2015-06-24T14:01:06.000Z | 2018-12-17T17:21:56.000Z | src/test/java/no/jsosi/EnheterGrunnkretsTest.java | halset/jsosi | 56d9f3943327ecdb4eda015c2e136be2732e9753 | [
"Apache-2.0"
] | 6 | 2015-06-24T13:29:20.000Z | 2020-11-12T15:42:25.000Z | 30.028571 | 86 | 0.62607 | 9,264 | package no.jsosi;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import org.locationtech.jts.geom.Envelope;
import junit.framework.TestCase;
public class EnheterGrunnkretsTest extends TestCase {
public void testEnheterGrunnkrets() throws Exception {
File file = new File("src/test/resources/STAT_enheter_grunnkretser.sos");
assertTrue(file.canRead());
SosiReader ri = new SosiReader(file);
assertEquals("EPSG:25833", ri.getCrs());
assertEquals(new Envelope(6426048, 7962744, -99553, 1121942), ri.getBounds());
Feature fi = null;
int count = 0;
Set<String> objtypes = new HashSet<String>();
while ((fi = ri.nextFeature()) != null) {
assertNotNull(fi);
assertNotNull(fi.getGeometry());
count++;
assertNotNull(fi.get("OBJTYPE"));
objtypes.add(fi.get("OBJTYPE").toString());
}
assertEquals(8, objtypes.size());
assertEquals(79724, count);
ri.close();
}
}
|
3e15cb7c7f24bf5e76b97f3a21cf5bac08948ec0 | 1,648 | java | Java | StackStruWithArray/src/com/example/stackwitharray/Stack.java | weijunjievip/DataStructure | 79faa98603e74195ab6d53e5030a7beb26ae13bb | [
"Apache-2.0"
] | null | null | null | StackStruWithArray/src/com/example/stackwitharray/Stack.java | weijunjievip/DataStructure | 79faa98603e74195ab6d53e5030a7beb26ae13bb | [
"Apache-2.0"
] | null | null | null | StackStruWithArray/src/com/example/stackwitharray/Stack.java | weijunjievip/DataStructure | 79faa98603e74195ab6d53e5030a7beb26ae13bb | [
"Apache-2.0"
] | null | null | null | 21.402597 | 70 | 0.477549 | 9,265 | package com.example.stackwitharray;
/**
* 数组作为底层数据结构实现的栈
*/
public class Stack<T> {
private T[] array = (T[]) new Object[10];//存储栈中数据的底层数据
private int size = 0;//记录栈中实际存储的数据量
/**
* 判断栈中是否有数据
*
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 新的数据入栈
*
* @param element 将新的数据添加到栈顶
*/
public void push(T element) {
if (size == array.length) {
resize();
}
array[size] = element;
size++;
}
/**
* 栈顶数据出栈
*
* @return 获取栈顶数据并返回
*/
public T pull() {
if (isEmpty()) {
throw new NullPointerException("栈为空,没有可以出栈的数据");
}
T element = array[size - 1];
size--;
return element;
}
/**
* 当栈满时,对作为底层数据结构的数组进行扩容,将其容量扩充至原先容量的1.5倍
*/
private void resize() {
int len = array.length;
T[] newArray = (T[]) new Object[len + len / 2];
System.arraycopy(array, 0, newArray, 0, len);
array = newArray;
}
/**
* 以[(栈底) element1 -> element2 -> element3 -> ... (栈顶)]的形式返回栈中所有数据
*
* @return
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getClass().getName()).append(":[(栈底) ");
if (isEmpty()) {
builder.append(" (栈顶)]");
} else {
for (int i = 0; i < size - 1; i++) {
builder.append(array[i]).append(" -> ");
}
builder.append(array[size - 1]).append(" (栈顶)]");
}
return builder.toString();
}
}
|
3e15cb9dc790c70c70da0197c6e38baf8f5f840d | 95 | java | Java | src/test/java/MyTest.java | Leeloomoscow/-lario-and-muigi-pipe-problem | a39d52048ebce2015d12f30966a5ceb3d4a28967 | [
"MIT"
] | 2 | 2021-12-01T06:49:22.000Z | 2021-12-06T07:46:09.000Z | src/test/java/MyTest.java | Leeloomoscow/-lario-and-muigi-pipe-problem | a39d52048ebce2015d12f30966a5ceb3d4a28967 | [
"MIT"
] | 2 | 2021-12-01T06:45:56.000Z | 2021-12-08T14:00:42.000Z | src/test/java/MyTest.java | Leeloomoscow/-lario-and-muigi-pipe-problem | a39d52048ebce2015d12f30966a5ceb3d4a28967 | [
"MIT"
] | null | null | null | 10.555556 | 34 | 0.6 | 9,266 | import org.junit.jupiter.api.Test;
public class MyTest {
@Test
void name() {
}
}
|
3e15cbfa5f0cd5d6aeca8f71d119e207753ca808 | 1,357 | java | Java | bb-integration-tests/src/test/java/com/cognifide/qa/bb/core/cookies/CookiesDefaultSettingsTest.java | cogbobcat/bobcat | b38faa94af322dbd08f28455a4e1de45f015694b | [
"Apache-2.0"
] | 102 | 2016-08-08T16:40:18.000Z | 2020-12-10T15:22:20.000Z | bb-integration-tests/src/test/java/com/cognifide/qa/bb/core/cookies/CookiesDefaultSettingsTest.java | cogbobcat/bobcat | b38faa94af322dbd08f28455a4e1de45f015694b | [
"Apache-2.0"
] | 302 | 2016-08-04T07:54:47.000Z | 2021-01-22T17:34:56.000Z | bb-integration-tests/src/test/java/com/cognifide/qa/bb/core/cookies/CookiesDefaultSettingsTest.java | cogbobcat/bobcat | b38faa94af322dbd08f28455a4e1de45f015694b | [
"Apache-2.0"
] | 48 | 2016-08-08T10:19:30.000Z | 2020-10-06T07:36:31.000Z | 29.5 | 75 | 0.753132 | 9,267 | /*-
* #%L
* Bobcat
* %%
* Copyright (C) 2018 Cognifide 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.
* #L%
*/
package com.cognifide.qa.bb.core.cookies;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import com.cognifide.qa.bb.junit5.BobcatExtension;
import com.cognifide.qa.bb.junit5.guice.Modules;
import com.google.inject.Inject;
@BobcatExtension
@Modules(TestModuleWithEnabledAutoLoad.class)
public class CookiesDefaultSettingsTest {
@Inject
private WebDriver webDriver;
private Cookie expectedCookie = new Cookie("test-cookie", "value", "/");
@Test
public void shouldSetCookiesFromCookiesYamlAutomatically() {
assertThat(webDriver.manage().getCookies()).contains(expectedCookie);
}
}
|
3e15ccd673e9f4f7dd721dfb59b17eb7cd43d78c | 6,297 | java | Java | app/src/main/java/com/icucse/android/kannada/MainActivity.java | hjoshi123/KannadaNoobs | a5178dba04b3288609a2acd8e9e22cb07a610959 | [
"Apache-2.0"
] | 1 | 2018-02-12T18:16:47.000Z | 2018-02-12T18:16:47.000Z | app/src/main/java/com/icucse/android/kannada/MainActivity.java | hjoshi123/KannadaNoobs | a5178dba04b3288609a2acd8e9e22cb07a610959 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/icucse/android/kannada/MainActivity.java | hjoshi123/KannadaNoobs | a5178dba04b3288609a2acd8e9e22cb07a610959 | [
"Apache-2.0"
] | null | null | null | 39.85443 | 106 | 0.646181 | 9,268 | /*
* 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.icucse.android.kannada;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.graphics.Color;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private boolean isFirstRun;
@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);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
//Intialize shared preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getBaseContext());
isFirstRun = preferences.getBoolean("firstStart",true);
if(isFirstRun){
startActivity(new Intent(MainActivity.this,IntroActivity.class));
//Make a new preferences editor
SharedPreferences.Editor e = preferences.edit();
//edit preferences to false because we dont want to run it again
e.putBoolean("firstStart",false);
e.apply();
}
}
});
t.start();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Kannada for Noobs");
//toolbar.setNavigationIcon(R.drawable.ic_action_ka);
// Find the view pager that will allow the user to swipe between fragments
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
CategoriesAdapter adapter = new CategoriesAdapter(getSupportFragmentManager());
//Set the adapter on the viewpager
viewPager.setAdapter(adapter);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_names);
tabLayout.setupWithViewPager(viewPager);
toolbar.setBackgroundColor(getResources().getColor(R.color.category_numbers));
tabLayout.setBackgroundColor(getResources().getColor(R.color.category_numbers_toolbar));
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if(tabLayout.getSelectedTabPosition()==0){
tabLayout.setBackgroundColor(getResources().getColor(R.color.category_numbers));
toolbar.setBackgroundColor(getResources().getColor(R.color.category_numbers_toolbar));
viewPager.setCurrentItem(tab.getPosition());
}
else if(tabLayout.getSelectedTabPosition()==1){
tabLayout.setBackgroundColor(getResources().getColor(R.color.category_colors));
toolbar.setBackgroundColor(getResources().getColor(R.color.category_colors_toolbar));
viewPager.setCurrentItem(tab.getPosition());
}
else if(tabLayout.getSelectedTabPosition()==2){
tabLayout.setBackgroundColor(getResources().getColor(R.color.category_family));
toolbar.setBackgroundColor(getResources().getColor(R.color.category_family_toolbar));
viewPager.setCurrentItem(tab.getPosition());
}
else{
tabLayout.setBackgroundColor(getResources().getColor(R.color.category_phrases));
toolbar.setBackgroundColor(getResources().getColor(R.color.category_phrases_toolbar));
viewPager.setCurrentItem(tab.getPosition());
}
tabLayout.setTabTextColors(Color.BLACK,Color.WHITE);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
tabLayout.setBackgroundColor(getResources().getColor(R.color.primary_color));
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_items,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.about_us_id:
Intent aboutActivity = new Intent(MainActivity.this,AboutUs.class);
startActivity(aboutActivity);
break;
case R.id.contact_us_id:
Toast.makeText(this,"Clicked on Contact us",Toast.LENGTH_SHORT).show();
break;
case R.id.translate:
startActivity(new Intent(MainActivity.this,TranslateActivity.class));
break;
default:
break;
}
return true;
}
/*public void openNumbers(View view){
Intent numbersClass = new Intent(this,NumbersActivity.class);
startActivity(numbersClass);
}*/
}
|
3e15cd0674e6810b83614ebf0b3281934c69af67 | 1,306 | java | Java | sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/SpringBootWebApplication.java | straybirdzls/sofa-tracer | c595c9af05cd37217975014821cb35ca42d45946 | [
"Apache-2.0"
] | 502 | 2018-05-14T12:30:26.000Z | 2019-05-11T16:42:51.000Z | sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/SpringBootWebApplication.java | straybirdzls/sofa-tracer | c595c9af05cd37217975014821cb35ca42d45946 | [
"Apache-2.0"
] | 176 | 2018-05-22T03:08:15.000Z | 2019-05-08T10:16:59.000Z | sofa-tracer-plugins/sofa-tracer-httpclient-plugin/src/test/java/com/alipay/sofa/tracer/plugins/httpclient/base/SpringBootWebApplication.java | straybirdzls/sofa-tracer | c595c9af05cd37217975014821cb35ca42d45946 | [
"Apache-2.0"
] | 199 | 2019-01-25T12:41:17.000Z | 2022-03-28T10:03:23.000Z | 37.314286 | 100 | 0.7634 | 9,269 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.sofa.tracer.plugins.httpclient.base;
import org.springframework.boot.SpringApplication;
/**
* SpringBootWebApplication
*
* @author yangguanchao
* @since 2018/08/07
*/
@org.springframework.boot.autoconfigure.SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication springApplication = new SpringApplication(SpringBootWebApplication.class);
springApplication.run(args);
}
}
|
3e15ce02840563b130b18d642df15e684c9e1817 | 872 | java | Java | src/main/org/botka/utility/api/security/Key.java | JakeB1998/Aveona-Utility-Library | ccd26708eb508c89559b78c85dc159f13418f7d9 | [
"Apache-2.0"
] | null | null | null | src/main/org/botka/utility/api/security/Key.java | JakeB1998/Aveona-Utility-Library | ccd26708eb508c89559b78c85dc159f13418f7d9 | [
"Apache-2.0"
] | null | null | null | src/main/org/botka/utility/api/security/Key.java | JakeB1998/Aveona-Utility-Library | ccd26708eb508c89559b78c85dc159f13418f7d9 | [
"Apache-2.0"
] | null | null | null | 16.769231 | 89 | 0.674312 | 9,270 | /*
* File name: Key.java
*
* Programmer : Jake Botka
*
* Date: Aug 19, 2020
*
*/
package main.org.botka.utility.api.security;
/**
* <insert class description here>
*
* @author Jake Botka
*
*/
public class Key {
/**
*
* @param algorithm
* @return
*/
public static KeyAlgorithmType keyAlgorithmType(KeyAlgorithm algorithm) {
// TODO
return null;
}
/**
*
* @param keyAlgorithmType
* @return
*/
public static KeyAlgorithm[] allKeyAlgorithmsOfType(KeyAlgorithmType keyAlgorithmType) {
KeyAlgorithm[] algorithms = null;
final KeyAlgorithm[] symmetricAlgorithms = {};
final KeyAlgorithm[] asymmetricAlgorithms = {};
switch (keyAlgorithmType) {
case Asymmetric:
algorithms = asymmetricAlgorithms;
break;
case Symmetric:
algorithms = symmetricAlgorithms;
break;
default:
break;
}
return algorithms;
}
}
|
3e15d05e1ddbccdce2b512ee73e8e83cc5767e38 | 5,787 | java | Java | src/com/android/launcher3/util/PackageManagerHelper.java | mohith777/Flick-Launcher | 6eaf0676bfa60eb6f67c7b122acdd5e84607c9cc | [
"Apache-2.0"
] | 337 | 2017-03-22T02:12:29.000Z | 2022-03-28T17:06:21.000Z | src/com/android/launcher3/util/PackageManagerHelper.java | andy1729/FlickLauncher | 6eaf0676bfa60eb6f67c7b122acdd5e84607c9cc | [
"Apache-2.0"
] | 64 | 2017-03-22T02:12:15.000Z | 2021-06-14T08:42:52.000Z | src/com/android/launcher3/util/PackageManagerHelper.java | andy1729/FlickLauncher | 6eaf0676bfa60eb6f67c7b122acdd5e84607c9cc | [
"Apache-2.0"
] | 108 | 2017-03-21T07:54:33.000Z | 2021-09-18T08:48:47.000Z | 37.577922 | 99 | 0.665284 | 9,271 | /*
* 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.android.launcher3.util;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.text.TextUtils;
import com.android.launcher3.Utilities;
import java.util.ArrayList;
/**
* Utility methods using package manager
*/
public class PackageManagerHelper {
private static final int FLAG_SUSPENDED = 1<<30;
private static final String LIVE_WALLPAPER_PICKER_PKG = "com.android.wallpaper.livepicker";
/**
* Returns true if the app can possibly be on the SDCard. This is just a workaround and doesn't
* guarantee that the app is on SD card.
*/
public static boolean isAppOnSdcard(PackageManager pm, String packageName) {
return isAppEnabled(pm, packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
}
public static boolean isAppEnabled(PackageManager pm, String packageName) {
return isAppEnabled(pm, packageName, 0);
}
public static boolean isAppEnabled(PackageManager pm, String packageName, int flags) {
try {
ApplicationInfo info = pm.getApplicationInfo(packageName, flags);
return info != null && info.enabled;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public static boolean isAppSuspended(PackageManager pm, String packageName) {
try {
ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
return info != null && isAppSuspended(info);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public static boolean isAppSuspended(ApplicationInfo info) {
// The value of FLAG_SUSPENDED was reused by a hidden constant
// ApplicationInfo.FLAG_PRIVILEGED prior to N, so only check for suspended flag on N
// or later.
if (Utilities.isNycOrAbove()) {
return (info.flags & FLAG_SUSPENDED) != 0;
} else {
return false;
}
}
/**
* Returns the package for a wallpaper picker system app giving preference to a app which
* is not as image picker.
*/
public static String getWallpaperPickerPackage(PackageManager pm) {
ArrayList<String> excludePackages = new ArrayList<>();
// Exclude packages which contain an image picker
for (ResolveInfo info : pm.queryIntentActivities(
new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"), 0)) {
excludePackages.add(info.activityInfo.packageName);
}
excludePackages.add(LIVE_WALLPAPER_PICKER_PKG);
for (ResolveInfo info : pm.queryIntentActivities(
new Intent(Intent.ACTION_SET_WALLPAPER), 0)) {
if (!excludePackages.contains(info.activityInfo.packageName) &&
(info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
return info.activityInfo.packageName;
}
}
return excludePackages.get(0);
}
/**
* Returns true if {@param srcPackage} has the permission required to start the activity from
* {@param intent}. If {@param srcPackage} is null, then the activity should not need
* any permissions
*/
public static boolean hasPermissionForActivity(Context context, Intent intent,
String srcPackage) {
PackageManager pm = context.getPackageManager();
ResolveInfo target = pm.resolveActivity(intent, 0);
if (target == null) {
// Not a valid target
return false;
}
if (TextUtils.isEmpty(target.activityInfo.permission)) {
// No permission is needed
return true;
}
if (TextUtils.isEmpty(srcPackage)) {
// The activity requires some permission but there is no source.
return false;
}
// Source does not have sufficient permissions.
if(pm.checkPermission(target.activityInfo.permission, srcPackage) !=
PackageManager.PERMISSION_GRANTED) {
return false;
}
if (!Utilities.ATLEAST_MARSHMALLOW) {
// These checks are sufficient for below M devices.
return true;
}
// On M and above also check AppOpsManager for compatibility mode permissions.
if (TextUtils.isEmpty(AppOpsManager.permissionToOp(target.activityInfo.permission))) {
// There is no app-op for this permission, which could have been disabled.
return true;
}
// There is no direct way to check if the app-op is allowed for a particular app. Since
// app-op is only enabled for apps running in compatibility mode, simply block such apps.
try {
return pm.getApplicationInfo(srcPackage, 0).targetSdkVersion >= Build.VERSION_CODES.M;
} catch (NameNotFoundException e) { }
return false;
}
}
|
3e15d0dc079a9142f0a625701db3966b3c5fcc1f | 3,320 | java | Java | RoomScheduler/src/main/java/ResultSetTableModel.java | Tingwei-Justin/Room-Schedular-System-in-Java | ae6e6383962e2330f295560ff710d6972195e0c3 | [
"MIT"
] | 6 | 2020-05-08T07:37:26.000Z | 2021-08-08T07:00:47.000Z | RoomScheduler/src/main/java/ResultSetTableModel.java | Tingwei-Justin/Room-Schedular-System-in-Java | ae6e6383962e2330f295560ff710d6972195e0c3 | [
"MIT"
] | 1 | 2020-06-10T04:48:23.000Z | 2020-06-10T04:48:23.000Z | RoomScheduler/src/main/java/ResultSetTableModel.java | Tingwei-Justin/Room-Schedular-System-in-Java | ae6e6383962e2330f295560ff710d6972195e0c3 | [
"MIT"
] | null | null | null | 29.642857 | 110 | 0.618675 | 9,272 |
import javax.swing.table.AbstractTableModel;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
/*
* 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.
*/
/**
*
* @author luckyjustin
*/
public class ResultSetTableModel extends AbstractTableModel{
private final Connection connection;
private final Statement statement;
private ResultSet resultSet;
private int numberOfRows;
private ResultSetMetaData metaData;
private boolean connectedToDataBase = false;
public ResultSetTableModel(String query) throws SQLException {
connection = DBConnection.getConnection();
statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
connectedToDataBase = true;
setQuery(query);
}
@Override
public int getRowCount() {
if (!connectedToDataBase) {
throw new IllegalStateException("Not connected to database");
}
return numberOfRows;
}
@Override
public int getColumnCount() {
if (!connectedToDataBase) {
throw new IllegalStateException("Not connected to database");
}
try {
return metaData.getColumnCount();
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return 0;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (!connectedToDataBase) {
throw new IllegalStateException("Not connected to database");
}
try {
resultSet.absolute(rowIndex + 1);
return resultSet.getObject(columnIndex + 1);
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return ""; //return emtpy if problems
}
private void setQuery(String query) throws SQLException, IllegalStateException {
if (!connectedToDataBase) {
throw new IllegalStateException("Not connected to database");
}
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
resultSet.last();
numberOfRows = resultSet.getRow();
fireTableStructureChanged(); // notify JTable
}
public String getColumnName(int column) throws IllegalStateException {
if (!connectedToDataBase) {
throw new IllegalStateException("Not connected to database");
}
try {
return metaData.getColumnName(column + 1);
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return "";
}
public void disconnectFromDatabase() {
if (connectedToDataBase) {
try {
resultSet.close();
statement.close();
connection.close();
}
catch(SQLException sqlException) {
sqlException.printStackTrace();
}
finally {
connectedToDataBase = false;
}
}
}
}
|
3e15d0e7545b34f86612600be8f8bb246a92523a | 409 | java | Java | securityrat-backend/src/main/java/org/appsec/securityrat/web/dto/FrontendProjectTypeDto.java | rylyade1/SecurityRAT | a8d4c10f906ab1652726d128fe78e2e3d3bc9bd5 | [
"Apache-2.0"
] | 147 | 2016-05-30T16:28:31.000Z | 2022-03-30T15:34:20.000Z | securityrat-backend/src/main/java/org/appsec/securityrat/web/dto/FrontendProjectTypeDto.java | rylyade1/SecurityRAT | a8d4c10f906ab1652726d128fe78e2e3d3bc9bd5 | [
"Apache-2.0"
] | 160 | 2016-07-05T14:28:38.000Z | 2022-03-02T12:58:15.000Z | securityrat-backend/src/main/java/org/appsec/securityrat/web/dto/FrontendProjectTypeDto.java | rylyade1/SecurityRAT | a8d4c10f906ab1652726d128fe78e2e3d3bc9bd5 | [
"Apache-2.0"
] | 48 | 2016-05-06T10:50:03.000Z | 2022-03-30T13:05:57.000Z | 25.5625 | 55 | 0.782396 | 9,273 | package org.appsec.securityrat.web.dto;
import java.util.Set;
import lombok.Data;
import org.appsec.securityrat.api.dto.Dto;
@Data
public class FrontendProjectTypeDto implements Dto {
private Long id;
private String name;
private String description;
private Integer showOrder;
private Set<FrontendOptionColumnDto> optionColumns;
private Set<FrontendStatusColumnDto> statusColumns;
}
|
3e15d12756cdde17b5dd7be660c73743d0aac406 | 2,216 | java | Java | src/test/java/com/sajed/service/AddressServiceTest.java | Sajed49/Family | 442ee138477a95692c23906eca110e83574d5356 | [
"MIT"
] | null | null | null | src/test/java/com/sajed/service/AddressServiceTest.java | Sajed49/Family | 442ee138477a95692c23906eca110e83574d5356 | [
"MIT"
] | null | null | null | src/test/java/com/sajed/service/AddressServiceTest.java | Sajed49/Family | 442ee138477a95692c23906eca110e83574d5356 | [
"MIT"
] | null | null | null | 30.777778 | 98 | 0.749549 | 9,274 | package com.sajed.service;
import com.sajed.main.FamilyApplication;
import com.sajed.models.Address;
import com.sajed.repository.AddressRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@SpringBootTest(classes = FamilyApplication.class)
class AddressServiceTest {
@Autowired
private AddressService addressService;
@MockBean
private AddressRepository addressRepository;
@BeforeEach
void setUp() {
Address mirpurBD = new Address();
mirpurBD.setAddressId(1);
Address parkStreetSingapore = new Address();
parkStreetSingapore.setAddressId(2);
Mockito.when(addressService.findByAddressIdAndIsDeletedFalse(
mirpurBD.getAddressId())).thenReturn(mirpurBD);
Mockito.when(addressService.save(parkStreetSingapore)).thenReturn(parkStreetSingapore);
Mockito.when(addressService.findByAddressIdAndIsDeletedFalse(4)).thenReturn(null);
}
@Test
public void givenAnExistingAddressReturnAddress() {
Address mirpurBD = new Address();
mirpurBD.setAddressId(1);
Address output = addressService.findByAddressIdAndIsDeletedFalse(mirpurBD.getAddressId());
assertEquals(mirpurBD, output);
}
@Test
public void givenAnNonExistingAddressReturnNull() {
Address output = addressService.findByAddressIdAndIsDeletedFalse(4);
assertEquals(null, output);
}
@Test
public void save() {
Address parkStreetSingapore = new Address();
parkStreetSingapore.setAddressId(2);
Address found = addressService.save(parkStreetSingapore);
assertEquals(parkStreetSingapore, found);
}
} |
3e15d1d1874ffff991c0d27c7bda44a38bc9a585 | 1,142 | java | Java | Main/src/org/linkedin/schema/ThreePositions.java | skela/linkedin-java | 21aa63887664f482bb109146391c3f18d9452d3f | [
"MIT"
] | 6 | 2015-08-06T14:13:44.000Z | 2017-12-22T06:16:55.000Z | Main/src/org/linkedin/schema/ThreePositions.java | skela/linkedin-java | 21aa63887664f482bb109146391c3f18d9452d3f | [
"MIT"
] | 2 | 2015-05-06T23:05:36.000Z | 2017-11-18T12:34:03.000Z | Main/src/org/linkedin/schema/ThreePositions.java | skela/linkedin-java | 21aa63887664f482bb109146391c3f18d9452d3f | [
"MIT"
] | 6 | 2015-03-29T13:21:17.000Z | 2019-04-23T03:30:25.000Z | 21.54717 | 88 | 0.587566 | 9,275 | package org.linkedin.schema;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class ThreePositions
{
@SerializedName("_total")
public long total;
public List<Position>values;
/**
* Gets the value of the positionList property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the positionList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPositionList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Position }
*
*
*/
public List<Position> getPositionList()
{
return values;
}
/**
* Gets the value of the total property.
*
* @return
* possible object is
* {@link String }
*
*/
public long getTotal()
{
return total;
}
}
|
3e15d1d26e84d693331c1c66c37094d2de45c34a | 3,313 | java | Java | 06-Multiplayer Client/Jetris/src/multiplayer/server/MultiplayerServiceImpl.java | Christian1984/FUN-mit-FOPT | c15dbcb7fa3bc29228f83eefe2b4422f8ae1003a | [
"MIT"
] | 1 | 2017-01-23T17:25:11.000Z | 2017-01-23T17:25:11.000Z | 06-Multiplayer Client/Jetris/src/multiplayer/server/MultiplayerServiceImpl.java | Christian1984/FUN-mit-FOPT | c15dbcb7fa3bc29228f83eefe2b4422f8ae1003a | [
"MIT"
] | null | null | null | 06-Multiplayer Client/Jetris/src/multiplayer/server/MultiplayerServiceImpl.java | Christian1984/FUN-mit-FOPT | c15dbcb7fa3bc29228f83eefe2b4422f8ae1003a | [
"MIT"
] | null | null | null | 28.316239 | 134 | 0.603079 | 9,276 | package multiplayer.server;
import multiplayer.JetrisGameMultiplayer;
import multiplayer.JetrisGameMultiplayerImpl;
import multiplayer.Player;
import multiplayer.PlayerDump;
import java.lang.reflect.Array;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
/**
* Created by chris on 07.04.16.
*/
public class MultiplayerServiceImpl extends UnicastRemoteObject implements MultiplayerService {
private ArrayList<Player> players;
public MultiplayerServiceImpl() throws RemoteException {
players = new ArrayList<Player>();
}
@Override
public synchronized boolean join(JetrisGameMultiplayer game, String name) throws RemoteException {
//make sure not to add the same player twice
for (Player p : players) {
if (p.ownsGame(game)) {
System.out.println("WARNING: Player cannot join! Already in list!");
return false;
}
}
//add player
players.add(new Player(name, game));
System.out.println("INFO: Player joined");
//update all clients with new stats
ArrayList<PlayerDump> dump = buildPlayerDumpList();
for (Player p : players) {
RMIDispatcherServer.sendStats(p.getGame(), dump);
}
//report success
return true;
}
@Override
public synchronized boolean leave(JetrisGameMultiplayer game) throws RemoteException {
Player pRemove = null;
//find player to remove
for (Player p : players) {
if (p.ownsGame(game)) {
pRemove = p;
break;
}
}
//remove player if found
if (pRemove != null) {
players.remove(pRemove);
System.out.println("INFO: Player " + pRemove.getName() + " left!");
return true;
}
//report that player could not be removed
System.out.println("WARNING: Player trying to leave is unknown!");
return false;
}
@Override
public synchronized void update(JetrisGameMultiplayer game, int newScore, int newLevel, int linesCleared) throws RemoteException {
//update stats
updateOwnerOfGame(game, newScore, newLevel);
//build dump
ArrayList<PlayerDump> pDump = buildPlayerDumpList();
//update clients
for (Player p : players) {
JetrisGameMultiplayer g = p.getGame();
//send stats
RMIDispatcherServer.sendStats(g, pDump);
//send rows to all player except rows' sender
if (linesCleared > 1 && !p.ownsGame(game)) {
RMIDispatcherServer.sendRows(g, linesCleared - 1);
}
}
}
//private methods
private ArrayList<PlayerDump> buildPlayerDumpList() {
ArrayList dump = new ArrayList<PlayerDump>();
for (Player p : players) {
dump.add((PlayerDump) p);
}
return dump;
}
private void updateOwnerOfGame(JetrisGameMultiplayer game, int newScore, int newLevel) {
for (Player p : players) {
if (p.ownsGame(game)) {
p.setScore(newScore);
p.setLevel(newLevel);
return;
}
}
}
}
|
3e15d230d0441cfcda0fb231072ae9938dd94a06 | 8,057 | java | Java | spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java | yangfancoming/spring-5.1.x | db4c2cbcaf8ba58f43463eff865d46bdbd742064 | [
"Apache-2.0"
] | null | null | null | spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java | yangfancoming/spring-5.1.x | db4c2cbcaf8ba58f43463eff865d46bdbd742064 | [
"Apache-2.0"
] | null | null | null | spring-web/src/main/java/org/springframework/http/codec/json/AbstractJackson2Encoder.java | yangfancoming/spring-5.1.x | db4c2cbcaf8ba58f43463eff865d46bdbd742064 | [
"Apache-2.0"
] | 1 | 2021-06-05T07:25:05.000Z | 2021-06-05T07:25:05.000Z | 34.285106 | 114 | 0.753134 | 9,277 |
package org.springframework.http.codec.json;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.exc.InvalidDefinitionException;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.core.codec.CodecException;
import org.springframework.core.codec.EncodingException;
import org.springframework.core.codec.Hints;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.log.LogFormatUtils;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageEncoder;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.MimeType;
/**
* Base class providing support methods for Jackson 2.9 encoding. For non-streaming use
* cases, {@link Flux} elements are collected into a {@link List} before serialization for
* performance reason.
*
* @author Sebastien Deleuze
* @author Arjen Poutsma
* @since 5.0
*/
public abstract class AbstractJackson2Encoder extends Jackson2CodecSupport implements HttpMessageEncoder<Object> {
private static final byte[] NEWLINE_SEPARATOR = {'\n'};
private static final Map<MediaType, byte[]> STREAM_SEPARATORS;
static {
STREAM_SEPARATORS = new HashMap<>();
STREAM_SEPARATORS.put(MediaType.APPLICATION_STREAM_JSON, NEWLINE_SEPARATOR);
STREAM_SEPARATORS.put(MediaType.parseMediaType("application/stream+x-jackson-smile"), new byte[0]);
}
private final List<MediaType> streamingMediaTypes = new ArrayList<>(1);
/**
* Constructor with a Jackson {@link ObjectMapper} to use.
*/
protected AbstractJackson2Encoder(ObjectMapper mapper, MimeType... mimeTypes) {
super(mapper, mimeTypes);
}
/**
* Configure "streaming" media types for which flushing should be performed
* automatically vs at the end of the stream.
* By default this is set to {@link MediaType#APPLICATION_STREAM_JSON}.
* @param mediaTypes one or more media types to add to the list
* @see HttpMessageEncoder#getStreamingMediaTypes()
*/
public void setStreamingMediaTypes(List<MediaType> mediaTypes) {
this.streamingMediaTypes.clear();
this.streamingMediaTypes.addAll(mediaTypes);
}
@Override
public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
Class<?> clazz = elementType.toClass();
return supportsMimeType(mimeType) && (Object.class == clazz ||
(!String.class.isAssignableFrom(elementType.resolve(clazz)) && getObjectMapper().canSerialize(clazz)));
}
@Override
public Flux<DataBuffer> encode(Publisher<?> inputStream, DataBufferFactory bufferFactory,
ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
Assert.notNull(inputStream, "'inputStream' must not be null");
Assert.notNull(bufferFactory, "'bufferFactory' must not be null");
Assert.notNull(elementType, "'elementType' must not be null");
JsonEncoding encoding = getJsonEncoding(mimeType);
if (inputStream instanceof Mono) {
return Mono.from(inputStream).map(value ->
encodeValue(value, mimeType, bufferFactory, elementType, hints, encoding)).flux();
}
else {
return this.streamingMediaTypes.stream()
.filter(mediaType -> mediaType.isCompatibleWith(mimeType))
.findFirst()
.map(mediaType -> {
byte[] separator = STREAM_SEPARATORS.getOrDefault(mediaType, NEWLINE_SEPARATOR);
return Flux.from(inputStream).map(value -> {
DataBuffer buffer = encodeValue(
value, mimeType, bufferFactory, elementType, hints, encoding);
if (separator != null) {
buffer.write(separator);
}
return buffer;
});
})
.orElseGet(() -> {
ResolvableType listType = ResolvableType.forClassWithGenerics(List.class, elementType);
return Flux.from(inputStream).collectList().map(list ->
encodeValue(list, mimeType, bufferFactory, listType, hints, encoding)).flux();
});
}
}
private DataBuffer encodeValue(Object value, @Nullable MimeType mimeType, DataBufferFactory bufferFactory,
ResolvableType elementType, @Nullable Map<String, Object> hints, JsonEncoding encoding) {
if (!Hints.isLoggingSuppressed(hints)) {
LogFormatUtils.traceDebug(logger, traceOn -> {
String formatted = LogFormatUtils.formatValue(value, !traceOn);
return Hints.getLogPrefix(hints) + "Encoding [" + formatted + "]";
});
}
JavaType javaType = getJavaType(elementType.getType(), null);
Class<?> jsonView = (hints != null ? (Class<?>) hints.get(Jackson2CodecSupport.JSON_VIEW_HINT) : null);
ObjectWriter writer = (jsonView != null ?
getObjectMapper().writerWithView(jsonView) : getObjectMapper().writer());
if (javaType.isContainerType()) {
writer = writer.forType(javaType);
}
writer = customizeWriter(writer, mimeType, elementType, hints);
DataBuffer buffer = bufferFactory.allocateBuffer();
boolean release = true;
OutputStream outputStream = buffer.asOutputStream();
try {
JsonGenerator generator = getObjectMapper().getFactory().createGenerator(outputStream, encoding);
writer.writeValue(generator, value);
generator.flush();
release = false;
}
catch (InvalidDefinitionException ex) {
throw new CodecException("Type definition error: " + ex.getType(), ex);
}
catch (JsonProcessingException ex) {
throw new EncodingException("JSON encoding error: " + ex.getOriginalMessage(), ex);
}
catch (IOException ex) {
throw new IllegalStateException("Unexpected I/O error while writing to data buffer",
ex);
}
finally {
if (release) {
DataBufferUtils.release(buffer);
}
}
return buffer;
}
protected ObjectWriter customizeWriter(ObjectWriter writer, @Nullable MimeType mimeType,
ResolvableType elementType, @Nullable Map<String, Object> hints) {
return writer;
}
/**
* Determine the JSON encoding to use for the given mime type.
* @param mimeType the mime type as requested by the caller
* @return the JSON encoding to use (never {@code null})
* @since 5.0.5
*/
protected JsonEncoding getJsonEncoding(@Nullable MimeType mimeType) {
if (mimeType != null && mimeType.getCharset() != null) {
Charset charset = mimeType.getCharset();
for (JsonEncoding encoding : JsonEncoding.values()) {
if (charset.name().equals(encoding.getJavaName())) {
return encoding;
}
}
}
return JsonEncoding.UTF8;
}
// HttpMessageEncoder...
@Override
public List<MimeType> getEncodableMimeTypes() {
return getMimeTypes();
}
@Override
public List<MediaType> getStreamingMediaTypes() {
return Collections.unmodifiableList(this.streamingMediaTypes);
}
@Override
public Map<String, Object> getEncodeHints(@Nullable ResolvableType actualType, ResolvableType elementType,
@Nullable MediaType mediaType, ServerHttpRequest request, ServerHttpResponse response) {
return (actualType != null ? getHints(actualType) : Hints.none());
}
// Jackson2CodecSupport ...
@Override
protected <A extends Annotation> A getAnnotation(MethodParameter parameter, Class<A> annotType) {
return parameter.getMethodAnnotation(annotType);
}
}
|
3e15d23a37ec17da87682008a1bc8d3813293321 | 304 | java | Java | deep-framework/src/main/java/com/deep/framework/lang/annotation/Operator.java | senseas/deep-learning | 592e5d8c128683c6d6f6f01f2df293f3bd79bdd4 | [
"MIT"
] | 1 | 2019-11-09T06:20:39.000Z | 2019-11-09T06:20:39.000Z | deep-framework/src/main/java/com/deep/framework/lang/annotation/Operator.java | senseas/deep-learning | 592e5d8c128683c6d6f6f01f2df293f3bd79bdd4 | [
"MIT"
] | 6 | 2021-01-30T00:28:00.000Z | 2021-08-25T12:15:26.000Z | deep-framework/src/main/java/com/deep/framework/lang/annotation/Operator.java | senseas/deep-learning | 592e5d8c128683c6d6f6f01f2df293f3bd79bdd4 | [
"MIT"
] | null | null | null | 25.333333 | 44 | 0.825658 | 9,278 | package com.deep.framework.lang.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Operator {
} |
3e15d2d41d000f3ef27e392ef5bd03c7798c3bae | 1,361 | java | Java | rest-driver-shared/src/main/java/com/github/restdriver/exception/RuntimeJsonTypeMismatchException.java | smil2k/rest-driver | 63ed14ea2ca7fc72d265e7e223cf624a89d36109 | [
"Apache-2.0"
] | 93 | 2015-01-07T17:33:39.000Z | 2021-12-02T11:46:44.000Z | rest-driver-shared/src/main/java/com/github/restdriver/exception/RuntimeJsonTypeMismatchException.java | smil2k/rest-driver | 63ed14ea2ca7fc72d265e7e223cf624a89d36109 | [
"Apache-2.0"
] | 37 | 2015-04-29T21:19:57.000Z | 2021-09-07T12:38:35.000Z | rest-driver-shared/src/main/java/com/github/restdriver/exception/RuntimeJsonTypeMismatchException.java | smil2k/rest-driver | 63ed14ea2ca7fc72d265e7e223cf624a89d36109 | [
"Apache-2.0"
] | 40 | 2015-03-08T06:45:11.000Z | 2021-08-18T09:07:30.000Z | 28.354167 | 91 | 0.683321 | 9,279 | /**
* Copyright © 2010-2011 Nokia
*
* 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.restdriver.exception;
/**
* Runtime Exception class for errors when JSONpath returns a result of an unexpected type.
*/
public class RuntimeJsonTypeMismatchException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 5947827084788598073L;
/**
* Constructor.
*
* @param message The message.
* @param ex The ClassCastException which we're wrapping.
*/
public RuntimeJsonTypeMismatchException(String message, ClassCastException ex) {
super(message, ex);
}
/**
* Constructor.
*
* @param message The message.
*/
public RuntimeJsonTypeMismatchException(String message) {
super(message);
}
}
|
3e15d2efa8cd1150dd1be23b7635e5d60275594b | 1,001 | java | Java | android/playground/app/src/androidTest/java/com/alibaba/weex/uitest/TC_AG/AG_Border_Switch_Border_Top_Right_Radius.java | 42Vision/incubator-weex | 66e1b5a395c91ee98ba039e335f2e92fdcd1cb54 | [
"Apache-2.0"
] | 1 | 2019-12-02T10:52:27.000Z | 2019-12-02T10:52:27.000Z | android/playground/app/src/androidTest/java/com/alibaba/weex/uitest/TC_AG/AG_Border_Switch_Border_Top_Right_Radius.java | 42Vision/incubator-weex | 66e1b5a395c91ee98ba039e335f2e92fdcd1cb54 | [
"Apache-2.0"
] | 1 | 2020-09-03T23:55:57.000Z | 2020-09-03T23:55:57.000Z | android/playground/app/src/androidTest/java/com/alibaba/weex/uitest/TC_AG/AG_Border_Switch_Border_Top_Right_Radius.java | liuxuanhai/weex-example | 43b01a91163f958ea73e4247c5ccee60169b1c07 | [
"Apache-2.0"
] | 1 | 2019-12-02T10:52:14.000Z | 2019-12-02T10:52:14.000Z | 25.025 | 79 | 0.731269 | 9,280 | package com.alibaba.weex.uitest.TC_AG;
import com.alibaba.weex.WXPageActivity;
import com.alibaba.weex.util.TestFlow;
import java.util.TreeMap;
import org.junit.Before;
import org.junit.Test;
public class AG_Border_Switch_Border_Top_Right_Radius extends TestFlow {
public AG_Border_Switch_Border_Top_Right_Radius() {
super(WXPageActivity.class);
}
@Before
public void setUp() throws InterruptedException {
super.setUp();
TreeMap testMap = new <String, Object> TreeMap();
testMap.put("testComponet", "AG_Border");
testMap.put("testChildCaseInit", "AG_Border_Switch_Border_Top_Right_Radius");
testMap.put("step1",new TreeMap(){
{
put("click", "10");
put("screenshot", "AG_Border_Switch_Border_Top_Right_Radius_01_10");
}
});
testMap.put("step2",new TreeMap(){
{
put("click", "20");
put("screenshot", "AG_Border_Switch_Border_Top_Right_Radius_02_20");
}
});
super.setTestMap(testMap);
}
@Test
public void doTest(){
super.testByTestMap();
}
}
|
3e15d30ab893d73ff8abb3368f9ea683c9f79b09 | 3,724 | java | Java | src/main/java/com/github/richardflee/voyager/enums/MatchersTypeEnum.java | richardflee/jlogviewer | 8cb122fe2e67d61d43edc8c63b31f4e73161cab8 | [
"MIT"
] | null | null | null | src/main/java/com/github/richardflee/voyager/enums/MatchersTypeEnum.java | richardflee/jlogviewer | 8cb122fe2e67d61d43edc8c63b31f4e73161cab8 | [
"MIT"
] | null | null | null | src/main/java/com/github/richardflee/voyager/enums/MatchersTypeEnum.java | richardflee/jlogviewer | 8cb122fe2e67d61d43edc8c63b31f4e73161cab8 | [
"MIT"
] | null | null | null | 38 | 143 | 0.719925 | 9,281 | package com.github.richardflee.voyager.enums;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
/**
* Maps text color to message type in Voyager log summary
*/
public enum MatchersTypeEnum {
TIMESTAMP(Color.LIGHT_GRAY), INFO(Color.GREEN), EVENT(Color.PINK),
WARNING(Color.YELLOW), EMERGENCY(Color.ORANGE), CRITICAL(Color.RED),
HIGHLIGHT(Color.WHITE), COMMENT(Color.LIGHT_GRAY),
METRIC_F(Color.CYAN), METRIC_G(Color.CYAN), METRIC_P(Color.CYAN);
private Color color = null;
private static final Map<String, MatchersTypeEnum> map = new HashMap<>();
public boolean isWarning() {
return this.equals(CRITICAL) || this.equals(EMERGENCY) || (this.equals(WARNING));
}
public boolean isMetric() {
return this.equals(METRIC_F) || this.equals(METRIC_G) || (this.equals(METRIC_P));
}
// public boolean notWarning() {
// return !this.isWarning();
// }
MatchersTypeEnum(Color color) {
this.color = color;
}
// get color for this enum
public Color getColor() {
return this.color;
}
// class method, returns color for enum string value
public static Color getColor(String strVal) {
return getEnum(strVal).getColor();
}
public String getStrVal() {
return this.toString();
}
// Returns enum for messageType input; invalid defaults to MessageTypesEnum.INFO.INFO if input is invalid
public static MatchersTypeEnum getEnum(String messageType) {
MatchersTypeEnum en = map.containsKey(messageType) ? map.get(messageType) : MatchersTypeEnum.INFO;
return en;
}
// compiles map with key, value pairs comprising enum string value and enum value respectively
static {
for (final var en : MatchersTypeEnum.values()) {
map.put(en.toString(), en);
}
}
public static void main(String[] args) {
System.out.println(String.format("Match INFO: %b", getEnum("INFO") == MatchersTypeEnum.INFO));
System.out.println(String.format("Match EMERGENCY: %b", getEnum("EMERGENCY") == MatchersTypeEnum.EMERGENCY));
System.out.println(String.format("INFO color = GREEN %b: ", MatchersTypeEnum.INFO.getColor()));
for (var x : MatchersTypeEnum.values()) {
System.out.println(x.toString());
}
var info_ = "INFO_";
var x = getEnum(info_);
System.out.println(x.toString());
System.out.println(String.format("Invalid enum match defaults to INFO: %b",
getEnum("INFO_") == MatchersTypeEnum.INFO));
System.out.println(String.format("String 'INFO' color GREEN: %b", MatchersTypeEnum.getColor("INFO")));
System.out.println(String.format("String 'INFO_' color GREEN: %b", MatchersTypeEnum.getColor("INFO_")));
System.out.println(String.format("\nIs WARNING: %s => %b", MatchersTypeEnum.WARNING.toString(), MatchersTypeEnum.WARNING.isWarning()));
System.out.println(String.format("Is WARNING: %s => %b", MatchersTypeEnum.EMERGENCY.toString(), MatchersTypeEnum.EMERGENCY.isWarning()));
System.out.println(String.format("Is WARNING: %s => %b", MatchersTypeEnum.CRITICAL.toString(), MatchersTypeEnum.CRITICAL.isWarning()));
System.out.println(String.format("Is WARNING: %s => %b", MatchersTypeEnum.INFO.toString(), MatchersTypeEnum.INFO.isWarning()));
// System.out.println(String.format("\nNot WARNING: %s => %b", MatchersTypeEnum.WARNING.toString(), MatchersTypeEnum.WARNING.notWarning()));
// System.out.println(String.format("Not WARNING: %s => %b", MatchersTypeEnum.EMERGENCY.toString(), MatchersTypeEnum.EMERGENCY.notWarning()));
// System.out.println(String.format("Not WARNING: %s => %b", MatchersTypeEnum.CRITICAL.toString(), MatchersTypeEnum.CRITICAL.notWarning()));
// System.out.println(String.format("Not WARNING: %s => %b", MatchersTypeEnum.INFO.toString(), MatchersTypeEnum.INFO.notWarning()));
}
}
|
3e15d37c80e6e794d72d6b3aadf44840e3b4e376 | 3,586 | java | Java | A_Team-finalproject-3c34732ca41925ce8300b7051cc05707ac4c330d/src/net/sf/freecol/client/control/InputHandler.java | bangra1/final | 2ab596f78072bb8daa1689774d5b687668494aee | [
"MIT"
] | 1 | 2017-05-16T19:29:52.000Z | 2017-05-16T19:29:52.000Z | A_Team-finalproject-3c34732ca41925ce8300b7051cc05707ac4c330d/src/net/sf/freecol/client/control/InputHandler.java | bangra1/final | 2ab596f78072bb8daa1689774d5b687668494aee | [
"MIT"
] | null | null | null | A_Team-finalproject-3c34732ca41925ce8300b7051cc05707ac4c330d/src/net/sf/freecol/client/control/InputHandler.java | bangra1/final | 2ab596f78072bb8daa1689774d5b687668494aee | [
"MIT"
] | null | null | null | 27.79845 | 88 | 0.623815 | 9,282 | /**
* Copyright (C) 2002-2015 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.client.control;
import java.util.logging.Logger;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.common.networking.MessageHandler;
import org.w3c.dom.Element;
/**
* Provides common methods for input handlers.
*/
abstract class InputHandler implements MessageHandler {
private static final Logger logger = Logger.getLogger(InputHandler.class.getName());
/** The main FreeCol client object. */
private final FreeColClient freeColClient;
/**
* The constructor to use.
*
* @param freeColClient The <code>FreeColClient</code> for the game.
*/
InputHandler(FreeColClient freeColClient) {
this.freeColClient = freeColClient;
}
/**
* Gets the main freecol client object.
*
* @return The main freecol client object.
*/
protected FreeColClient getFreeColClient() {
return freeColClient;
}
/**
* Gets the GUI.
*
* @return The GUI.
*/
protected GUI getGUI() {
return freeColClient.getGUI();
}
/**
* Gets the Game.
*
* @return The <code>Game</code>.
*/
protected Game getGame() {
return freeColClient.getGame();
}
/**
* Deals with incoming messages that have just been received.
*
* @param connection The <code>Connection</code> the message was
* received on.
* @param element The root <code>Element</code> of the message.
* @return The reply.
*/
@Override
public abstract Element handle(Connection connection, Element element);
// Useful handlers
/**
* Handles a "disconnect"-message.
*
* @param element The element (root element in a DOM-parsed XML tree) that
* holds all the information.
* @return Null.
*/
protected Element disconnect(Element element) {
// Updating the GUI should always be done in the EDT:
javax.swing.SwingUtilities.invokeLater(() -> {
if (getGUI().containsInGameComponents()) {
if (freeColClient.getFreeColServer() == null) {
getGUI().returnToTitle();
} else {
getGUI().removeInGameComponents();
}
}
});
return null;
}
/**
* Handles a message of unknown type.
*
* @param element The element (root element in a DOM-parsed XML tree) that
* holds all the information.
* @return Null.
*/
public Element unknown(Element element) {
logger.warning("Unknown message type: " + element.getTagName());
return null;
}
}
|
3e15d3be8653590dbf699a0a0c26255a3d8d1593 | 347 | java | Java | school-management/src/main/java/dev/schoolmanagement/exceptions/NonNullableException.java | 113-GittiGidiyor-Java-Spring-Bootcamp/fourth-homework-erhancavar | 184caf82cd96059bd34a90a8d55b520514266cd1 | [
"MIT"
] | null | null | null | school-management/src/main/java/dev/schoolmanagement/exceptions/NonNullableException.java | 113-GittiGidiyor-Java-Spring-Bootcamp/fourth-homework-erhancavar | 184caf82cd96059bd34a90a8d55b520514266cd1 | [
"MIT"
] | null | null | null | school-management/src/main/java/dev/schoolmanagement/exceptions/NonNullableException.java | 113-GittiGidiyor-Java-Spring-Bootcamp/fourth-homework-erhancavar | 184caf82cd96059bd34a90a8d55b520514266cd1 | [
"MIT"
] | 1 | 2021-09-29T20:15:18.000Z | 2021-09-29T20:15:18.000Z | 26.692308 | 69 | 0.73487 | 9,283 | package dev.schoolmanagement.exceptions;
/**
* Can be used for non-nullable fields or service layer null checks.
* It is thrown when the checked fields is passed with a "null" field
* at run time.
*/
public class NonNullableException extends RuntimeException{
public NonNullableException(String message) {
super(message);
}
}
|
3e15d3c3d5e70554777c5bbaeba02df769e183a0 | 1,992 | java | Java | DatBot.ProtocolBuilder/Utils/types/game/character/characteristic/CharacterSpellModification.java | ProjectBlackFalcon/DatBot | 8b2cc64af78757b832d8bc6a1373fb74b7a4316f | [
"MIT"
] | 7 | 2017-11-22T13:28:41.000Z | 2019-10-17T08:47:40.000Z | DatBot.ProtocolBuilder/Utils/types/game/character/characteristic/CharacterSpellModification.java | ProjectBlackFalcon/DatBot | 8b2cc64af78757b832d8bc6a1373fb74b7a4316f | [
"MIT"
] | 3 | 2018-10-07T15:59:34.000Z | 2019-01-15T11:56:18.000Z | DatBot.ProtocolBuilder/Utils/types/game/character/characteristic/CharacterSpellModification.java | ProjectBlackFalcon/DatBot | 8b2cc64af78757b832d8bc6a1373fb74b7a4316f | [
"MIT"
] | null | null | null | 31.125 | 105 | 0.788655 | 9,284 | package protocol.network.types.game.character.characteristic;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import protocol.utils.ProtocolTypeManager;
import protocol.network.util.types.BooleanByteWrapper;
import protocol.network.NetworkMessage;
import protocol.network.util.DofusDataReader;
import protocol.network.util.DofusDataWriter;
import protocol.network.Network;
import protocol.network.NetworkMessage;
import protocol.network.types.game.character.characteristic.CharacterBaseCharacteristic;
@SuppressWarnings("unused")
public class CharacterSpellModification extends NetworkMessage {
public static final int ProtocolId = 215;
private int modificationType;
private int spellId;
private CharacterBaseCharacteristic value;
public int getModificationType() { return this.modificationType; }
public void setModificationType(int modificationType) { this.modificationType = modificationType; };
public int getSpellId() { return this.spellId; }
public void setSpellId(int spellId) { this.spellId = spellId; };
public CharacterBaseCharacteristic getValue() { return this.value; }
public void setValue(CharacterBaseCharacteristic value) { this.value = value; };
public CharacterSpellModification(){
}
public CharacterSpellModification(int modificationType, int spellId, CharacterBaseCharacteristic value){
this.modificationType = modificationType;
this.spellId = spellId;
this.value = value;
}
@Override
public void Serialize(DofusDataWriter writer) {
try {
writer.writeByte(this.modificationType);
writer.writeVarShort(this.spellId);
value.Serialize(writer);
} catch (Exception e){
e.printStackTrace();
}
}
@Override
public void Deserialize(DofusDataReader reader) {
try {
this.modificationType = reader.readByte();
this.spellId = reader.readVarShort();
this.value = new CharacterBaseCharacteristic();
this.value.Deserialize(reader);
} catch (Exception e){
e.printStackTrace();
}
}
}
|
3e15d44f2a6ac9427e656d5cb11bd0c4bc42d195 | 2,053 | java | Java | bricks-maven-plugin/src/main/java/com/github/ingogriebsch/bricks/maven/plugin/analyzer/discovery/ReflectionsAnalyzerDiscovery.java | ingogriebsch/bricks | 1f9ad2ffd55f6f5800b5d056cb792f83aa6129b0 | [
"Apache-2.0"
] | null | null | null | bricks-maven-plugin/src/main/java/com/github/ingogriebsch/bricks/maven/plugin/analyzer/discovery/ReflectionsAnalyzerDiscovery.java | ingogriebsch/bricks | 1f9ad2ffd55f6f5800b5d056cb792f83aa6129b0 | [
"Apache-2.0"
] | 86 | 2019-01-31T09:04:44.000Z | 2021-01-21T00:43:22.000Z | bricks-maven-plugin/src/main/java/com/github/ingogriebsch/bricks/maven/plugin/analyzer/discovery/ReflectionsAnalyzerDiscovery.java | ingogriebsch/bricks | 1f9ad2ffd55f6f5800b5d056cb792f83aa6129b0 | [
"Apache-2.0"
] | 3 | 2019-02-23T09:41:18.000Z | 2019-03-21T18:49:25.000Z | 32.078125 | 105 | 0.724793 | 9,285 | /*-
* #%L
* Bricks Maven Plugin
* %%
* Copyright (C) 2018 - 2019 Ingo Griebsch
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.ingogriebsch.bricks.maven.plugin.analyzer.discovery;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.stream.Collectors;
import com.github.ingogriebsch.bricks.maven.plugin.analyzer.AnalyzerContext;
import com.github.ingogriebsch.bricks.maven.plugin.analyzer.MavenAnalyzer;
import com.google.common.base.Predicates;
import org.reflections.Reflections;
import lombok.NonNull;
import lombok.SneakyThrows;
/**
* AnalyzerDiscovery that uses "Reflections"-Framework to scan the classpath and
* return instances of all concrete subclasses of MavenAnalyzer
*
* @author doc
*
*/
public class ReflectionsAnalyzerDiscovery implements AnalyzerDiscovery {
@Override
public Collection<MavenAnalyzer> findEnabledAnalyzers(@NonNull AnalyzerContext ctx) {
ctx.log().info("Discovering Analyzers via 'Reflections'");
// do not use ctx.reflections here, as that one is intended to include
// project classes...
return new Reflections().getSubTypesOf(MavenAnalyzer.class).stream().map(this::tryCreateInstance)
.filter(Predicates.notNull()).collect(Collectors.toList());
}
@SneakyThrows
private <T> T tryCreateInstance(Class<T> c) {
if (c.isInterface() || Modifier.isAbstract(c.getModifiers()))
return null;
else
return c.newInstance();
}
}
|
3e15d4e10a951b9f3089ecccadfeb1ff7aa46427 | 520 | java | Java | Banking/database.java | KhaledK1123/project-0-banking-app | 7a567c438c654f6500cda662cb2b90e71f5bf646 | [
"Apache-2.0"
] | null | null | null | Banking/database.java | KhaledK1123/project-0-banking-app | 7a567c438c654f6500cda662cb2b90e71f5bf646 | [
"Apache-2.0"
] | null | null | null | Banking/database.java | KhaledK1123/project-0-banking-app | 7a567c438c654f6500cda662cb2b90e71f5bf646 | [
"Apache-2.0"
] | null | null | null | 20.8 | 82 | 0.742308 | 9,286 | package Banking;
import java.util.HashMap;
public class database implements java.io.Serializable{
public String name;
public String password;
public String accountType;
public double balance;
public static HashMap<String, Object> map = new HashMap<String, Object>();
public void map(String name, String password, String accountType, double balance)
{
database a = new database();
a.name=name;
a.password=password;
a.accountType=accountType;
a.balance=balance;
database.map.put(name, a);
}
}
|
3e15d5009e6e270bc2bc073c30681e5b8c66174d | 576 | java | Java | utilita/src/main/java/unoone/utilita/MobileConvalid.java | andyunoone/LogUtil-Android | 75335d2d06dff5e0f96ded03adf6226da1201800 | [
"MIT"
] | null | null | null | utilita/src/main/java/unoone/utilita/MobileConvalid.java | andyunoone/LogUtil-Android | 75335d2d06dff5e0f96ded03adf6226da1201800 | [
"MIT"
] | null | null | null | utilita/src/main/java/unoone/utilita/MobileConvalid.java | andyunoone/LogUtil-Android | 75335d2d06dff5e0f96ded03adf6226da1201800 | [
"MIT"
] | null | null | null | 18 | 59 | 0.453125 | 9,287 | package unoone.utilita;
import java.util.regex.Pattern;
/**
* Created by andreamolinari on 18/02/16.
*/
public class MobileConvalid {
public static boolean isValidMobile(String number)
{
boolean check;
if(!Pattern.matches("[a-zA-Z]+", number))
{
if(number.length() < 8 || number.length() > 13)
{
check = false;
}
else
{
check = true;
}
}
else
{
check=false;
}
return check;
}
}
|
3e15d522aa6544170d58a7f289e12adc881572f5 | 76 | java | Java | src/main/java/com/icthh/xm/tmf/ms/customer/domain/package-info.java | xm-online/tmf-xm-customer | 9527e792d63a30a54bb38e2a38e34f3ae4867c8d | [
"Apache-2.0"
] | 2 | 2019-02-20T07:48:13.000Z | 2021-01-27T09:25:08.000Z | src/main/java/com/icthh/xm/tmf/ms/customer/domain/package-info.java | xm-online/tmf-xm-customer | 9527e792d63a30a54bb38e2a38e34f3ae4867c8d | [
"Apache-2.0"
] | 6 | 2020-02-13T14:09:37.000Z | 2021-06-14T07:21:48.000Z | src/main/java/com/icthh/xm/tmf/ms/customer/domain/package-info.java | xm-online/tmf-xm-customer | 9527e792d63a30a54bb38e2a38e34f3ae4867c8d | [
"Apache-2.0"
] | 1 | 2021-01-27T10:26:02.000Z | 2021-01-27T10:26:02.000Z | 15.2 | 44 | 0.684211 | 9,288 | /**
* JPA domain objects.
*/
package com.icthh.xm.tmf.ms.customer.domain;
|
3e15d5d7c4c721b69b705d3fdb7e994dd9eb3c14 | 1,200 | java | Java | src/test/java/info/kfgodel/jspek/ClassOverriddenSpecTest.java | kfgodel/java-spec | 3a2c39c29242df83ce09a18db473e0a3a0425890 | [
"Apache-2.0"
] | 3 | 2018-03-23T12:24:47.000Z | 2019-06-04T00:59:16.000Z | src/test/java/info/kfgodel/jspek/ClassOverriddenSpecTest.java | kfgodel/JspeK | 3a2c39c29242df83ce09a18db473e0a3a0425890 | [
"Apache-2.0"
] | 1 | 2018-12-11T14:37:00.000Z | 2019-06-02T19:26:56.000Z | src/test/java/info/kfgodel/jspek/ClassOverriddenSpecTest.java | kfgodel/JspeK | 3a2c39c29242df83ce09a18db473e0a3a0425890 | [
"Apache-2.0"
] | 1 | 2019-03-10T16:02:27.000Z | 2019-03-10T16:02:27.000Z | 29.268293 | 84 | 0.664167 | 9,289 | package info.kfgodel.jspek;
import info.kfgodel.jspek.api.JavaSpec;
import info.kfgodel.jspek.api.JavaSpecRunner;
import info.kfgodel.jspek.api.contexts.ClassBasedTestContext;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* This type verifies that subject instances change if described class changes
* Created by kfgodel on 08/03/16.
*/
@RunWith(JavaSpecRunner.class)
public class ClassOverriddenSpecTest extends JavaSpec<ClassBasedTestContext<List>> {
@Override
public void define() {
describe("a context with one described class", () -> {
describe(ArrayList.class, () -> {
it("has instances of that class as subject", () -> {
assertThat(context().subject()).isInstanceOf(ArrayList.class);
});
describe("when class is redefined in a sub-context", () -> {
describe(LinkedList.class, () -> {
it("has instances of the new class as subject", () -> {
assertThat(context().subject()).isInstanceOf(LinkedList.class);
});
});
});
});
});
}
} |
3e15d6157c02ae8d300160cbf5a26ef5c8ffcb08 | 2,521 | java | Java | app/src/main/java/com/codepath/instagramclone/MainActivity.java | Glazzerino/InstagramClone | 9856efb6ac1092cad9e4aeb79ec6bfe9b85a019b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/codepath/instagramclone/MainActivity.java | Glazzerino/InstagramClone | 9856efb6ac1092cad9e4aeb79ec6bfe9b85a019b | [
"Apache-2.0"
] | 1 | 2021-07-10T07:12:40.000Z | 2021-07-10T07:12:40.000Z | app/src/main/java/com/codepath/instagramclone/MainActivity.java | Glazzerino/InstagramClone | 9856efb6ac1092cad9e4aeb79ec6bfe9b85a019b | [
"Apache-2.0"
] | null | null | null | 33.613333 | 116 | 0.670369 | 9,290 | package com.codepath.instagramclone;
import android.content.Context;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.codepath.instagramclone.fragments.ComposeFragment;
import com.codepath.instagramclone.fragments.HomeFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.parse.ParseUser;
import org.jetbrains.annotations.NotNull;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomMenu;
FragmentManager fragmentManager;
Fragment fragment;
ImageButton btnLogout;
ImageView ivTitle;
Context context;
public static final int POST_ACTIVITY_CODE = 1337;
public static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
btnLogout = findViewById(R.id.btnLogout);
ivTitle = findViewById(R.id.ivTitle);
bottomMenu = findViewById(R.id.bottomMenu);
// fragment manager
fragmentManager = getSupportFragmentManager();
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ParseUser.logOut();
finish();
}
});
fragment = HomeFragment.newInstance(context);
fragmentManager.beginTransaction().replace(R.id.flContainer, fragment).commit();
bottomMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
switch (item.getItemId()) {
case R.id.item_home:
fragment = HomeFragment.newInstance(context);
break;
case R.id.item_create:
fragment = ComposeFragment.newInstance(context);
break;
}
fragmentManager.beginTransaction().replace(R.id.flContainer, fragment).commit();
return true;
}
});
}
} |
3e15d81a7da06bd1124708b3bc4e3329f6807410 | 9,948 | java | Java | freeipa/src/main/java/com/sequenceiq/freeipa/service/freeipa/CleanupService.java | benyoka/cloudbreak | 48d26aa05c0133ebe6b4e5e606d89ec5ff09a15b | [
"Apache-2.0"
] | null | null | null | freeipa/src/main/java/com/sequenceiq/freeipa/service/freeipa/CleanupService.java | benyoka/cloudbreak | 48d26aa05c0133ebe6b4e5e606d89ec5ff09a15b | [
"Apache-2.0"
] | null | null | null | freeipa/src/main/java/com/sequenceiq/freeipa/service/freeipa/CleanupService.java | benyoka/cloudbreak | 48d26aa05c0133ebe6b4e5e606d89ec5ff09a15b | [
"Apache-2.0"
] | null | null | null | 50.242424 | 154 | 0.632288 | 9,291 | package com.sequenceiq.freeipa.service.freeipa;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.sequenceiq.freeipa.api.v1.freeipa.cleanup.CleanupRequest;
import com.sequenceiq.freeipa.api.v1.freeipa.cleanup.CleanupResponse;
import com.sequenceiq.freeipa.api.v1.kerberosmgmt.model.HostRequest;
import com.sequenceiq.freeipa.client.FreeIpaClient;
import com.sequenceiq.freeipa.client.FreeIpaClientException;
import com.sequenceiq.freeipa.client.model.Cert;
import com.sequenceiq.freeipa.client.model.DnsRecord;
import com.sequenceiq.freeipa.client.model.DnsZoneList;
import com.sequenceiq.freeipa.client.model.Host;
import com.sequenceiq.freeipa.client.model.Role;
import com.sequenceiq.freeipa.client.model.User;
import com.sequenceiq.freeipa.entity.FreeIpa;
import com.sequenceiq.freeipa.entity.Stack;
import com.sequenceiq.freeipa.kerberosmgmt.exception.DeleteException;
import com.sequenceiq.freeipa.kerberosmgmt.v1.KerberosMgmtV1Controller;
import com.sequenceiq.freeipa.service.stack.StackService;
@Service
public class CleanupService {
private static final Logger LOGGER = LoggerFactory.getLogger(CleanupService.class);
@Inject
private FreeIpaClientFactory freeIpaClientFactory;
@Inject
private StackService stackService;
@Inject
private FreeIpaService freeIpaService;
@Inject
private KerberosMgmtV1Controller kerberosMgmtV1Controller;
public CleanupResponse cleanup(String accountId, CleanupRequest request) throws FreeIpaClientException {
Optional<Stack> optionalStack = stackService.findByEnvironmentCrnAndAccountId(request.getEnvironmentCrn(), accountId);
CleanupResponse cleanupResponse = new CleanupResponse();
if (optionalStack.isPresent()) {
Stack stack = optionalStack.get();
FreeIpa freeIpa = freeIpaService.findByStack(stack);
FreeIpaClient client = freeIpaClientFactory.getFreeIpaClientForStack(stack);
if (!CollectionUtils.isEmpty(request.getHosts())) {
revokeCerts(client, request, cleanupResponse);
removeHosts(client, request, cleanupResponse);
removeDnsEntries(client, request, cleanupResponse, freeIpa.getDomain());
removeVaultEntries(client, request, cleanupResponse, stack.getEnvironmentCrn());
}
// TODO: https://jira.cloudera.com/browse/CB-3581
// if (!CollectionUtils.isEmpty(request.getUsers())) {
// removeUsers(client, request, cleanupResponse);
// }
// if (!CollectionUtils.isEmpty(request.getRoles())) {
// removeRoles(client, request, cleanupResponse);
// }
}
return cleanupResponse;
}
private void revokeCerts(FreeIpaClient client, CleanupRequest request, CleanupResponse cleanupResponse) throws FreeIpaClientException {
Set<Cert> certs = client.findAllCert();
certs.stream()
.filter(cert -> request.getHosts().contains(StringUtils.removeStart(cert.getSubject(), "CN=")))
.filter(cert -> !cert.isRevoked())
.forEach(cert -> {
try {
client.revokeCert(cert.getSerialNumber());
cleanupResponse.getCertCleanupSuccess().add(cert.getSubject());
} catch (FreeIpaClientException e) {
LOGGER.error("Couldn't revoke certificate: {}", cert, e);
cleanupResponse.getCertCleanupFailed().put(cert.getSubject(), e.getMessage());
}
});
}
private void removeDnsEntries(FreeIpaClient client, CleanupRequest request, CleanupResponse response, String domain) throws FreeIpaClientException {
Set<String> allDnsZoneName = client.findAllDnsZone().stream().map(DnsZoneList::getIdnsname).collect(Collectors.toSet());
for (String zone : allDnsZoneName) {
Set<DnsRecord> allDnsRecordInZone = client.findAllDnsRecordInZone(zone);
for (String host : request.getHosts()) {
if (!response.getHostCleanupFailed().containsKey(host)) {
allDnsRecordInZone.stream().filter(record -> record.isHostRelatedRecord(host, domain))
.forEach(record -> {
try {
client.deleteDnsRecord(record.getIdnsname(), zone);
response.getHostCleanupSuccess().add(host);
} catch (FreeIpaClientException e) {
LOGGER.info("DNS record delete in zone [{}] with name [{}] failed for host: {}", zone, record.getIdnsname(), host, e);
response.getHostCleanupFailed().put(host, e.getMessage());
response.getHostCleanupSuccess().remove(host);
}
});
}
}
}
}
private void removeHosts(FreeIpaClient client, CleanupRequest request, CleanupResponse response) throws FreeIpaClientException {
Set<String> existingHostFqdn = client.findAllHost().stream().map(Host::getFqdn).collect(Collectors.toSet());
Set<String> hostsToRemove = request.getHosts().stream()
.filter(existingHostFqdn::contains)
.filter(h -> !response.getHostCleanupFailed().keySet().contains(h))
.collect(Collectors.toSet());
LOGGER.debug("Hosts to delete: {}", hostsToRemove);
for (String host : hostsToRemove) {
try {
client.deleteHost(host);
response.getHostCleanupSuccess().add(host);
} catch (FreeIpaClientException e) {
LOGGER.info("Host delete failed for host: {}", host, e);
response.getHostCleanupFailed().put(host, e.getMessage());
response.getHostCleanupSuccess().remove(host);
}
}
removeHostRelatedServices(client, hostsToRemove);
}
private void removeHostRelatedServices(FreeIpaClient client, Set<String> hostsToRemove) throws FreeIpaClientException {
Map<String, String> principalCanonicalMap = client.findAllService().stream()
.collect(Collectors.toMap(com.sequenceiq.freeipa.client.model.Service::getKrbprincipalname,
com.sequenceiq.freeipa.client.model.Service::getKrbcanonicalname));
for (String host : hostsToRemove) {
Set<String> services = principalCanonicalMap.entrySet().stream().filter(e -> e.getKey().contains(host))
.map(Map.Entry::getValue).collect(Collectors.toSet());
LOGGER.debug("Services to delete: {}", services);
for (String service : services) {
try {
client.deleteService(service);
} catch (FreeIpaClientException e) {
LOGGER.info("Service delete failed for service: {}", service, e);
}
}
}
}
private void removeUsers(FreeIpaClient client, CleanupRequest request, CleanupResponse response) throws FreeIpaClientException {
Set<String> usersUid = client.userFindAll().stream().map(User::getUid).collect(Collectors.toSet());
request.getUsers().stream().filter(usersUid::contains).forEach(userUid -> {
try {
LOGGER.debug("Delete user: {}", userUid);
client.deleteUser(userUid);
response.getUserCleanupSuccess().add(userUid);
} catch (FreeIpaClientException e) {
LOGGER.info("User delete failed for user: {}", userUid, e);
response.getUserCleanupFailed().put(userUid, e.getMessage());
response.getUserCleanupSuccess().remove(userUid);
}
});
}
private void removeRoles(FreeIpaClient client, CleanupRequest request, CleanupResponse response) throws FreeIpaClientException {
Set<String> roleNames = client.findAllRole().stream().map(Role::getCn).collect(Collectors.toSet());
request.getRoles().stream().filter(roleNames::contains).forEach(role -> {
try {
LOGGER.debug("Delete role: {}", role);
client.deleteRole(role);
response.getRoleCleanupSuccess().add(role);
} catch (FreeIpaClientException e) {
LOGGER.info("Role delete failed for role: {}", role, e);
response.getRoleCleanupFailed().put(role, e.getMessage());
response.getRoleCleanupSuccess().remove(role);
}
});
}
private void removeVaultEntries(FreeIpaClient client, CleanupRequest request, CleanupResponse response, String environmentCrn) {
for (String host : request.getHosts()) {
if (!response.getHostCleanupFailed().containsKey(host)) {
try {
HostRequest hostRequst = new HostRequest();
hostRequst.setEnvironmentCrn(environmentCrn);
hostRequst.setServerHostName(host);
kerberosMgmtV1Controller.deleteHost(hostRequst);
response.getHostCleanupSuccess().add(host);
} catch (DeleteException | FreeIpaClientException e) {
LOGGER.info("Vault secret cleanup failed for host: {}", host, e);
response.getHostCleanupFailed().put(host, e.getMessage());
response.getHostCleanupSuccess().remove(host);
}
}
}
}
} |
3e15d88cb9104e45a958e995f68dcb39293db462 | 974 | java | Java | src/ooga/engine/triggerHandler/EntityStatusTriggerHandler.java | alexqxu/java-game-development-environment | 9c0efa46aa0d3dacca1f0b79411a9f08ad5f0542 | [
"MIT"
] | null | null | null | src/ooga/engine/triggerHandler/EntityStatusTriggerHandler.java | alexqxu/java-game-development-environment | 9c0efa46aa0d3dacca1f0b79411a9f08ad5f0542 | [
"MIT"
] | null | null | null | src/ooga/engine/triggerHandler/EntityStatusTriggerHandler.java | alexqxu/java-game-development-environment | 9c0efa46aa0d3dacca1f0b79411a9f08ad5f0542 | [
"MIT"
] | null | null | null | 32.466667 | 92 | 0.741273 | 9,292 | package ooga.engine.triggerHandler;
import ooga.engine.helperObjects.Action;
import ooga.engine.helperObjects.Trigger;
import ooga.model.Entity;
import ooga.model.backEndEntities.PlayerEntity;
import ooga.parser.components.GeneralInfoParser;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class EntityStatusTriggerHandler extends TriggerHandler{
public List<Trigger> getTriggers(List<PlayerEntity> players, String currentGameFileDir){
List<Trigger> statusTriggers = new ArrayList<>();
GeneralInfoParser scoreThresholdFinder = new GeneralInfoParser(currentGameFileDir);
int scoreMaxThreshold = scoreThresholdFinder.getThreshold();
for(PlayerEntity player : players){
if(player.getEntityGameStatus().getValue().getScore() >= scoreMaxThreshold){
statusTriggers.add(new Trigger(player, "GameClear"));
}
}
return statusTriggers;
}
}
|
3e15d8bd0fd2d1502d6c98e9fdc0217e5b9a2f64 | 4,194 | java | Java | CateMenu/app/src/main/java/com/example/administrator/catemenu/activity/MineActivity.java | hkl778250693/MyCateMenu | 5b8ac8f81e315dbc26dddb2d2dce5bcaae282967 | [
"Apache-2.0"
] | null | null | null | CateMenu/app/src/main/java/com/example/administrator/catemenu/activity/MineActivity.java | hkl778250693/MyCateMenu | 5b8ac8f81e315dbc26dddb2d2dce5bcaae282967 | [
"Apache-2.0"
] | null | null | null | CateMenu/app/src/main/java/com/example/administrator/catemenu/activity/MineActivity.java | hkl778250693/MyCateMenu | 5b8ac8f81e315dbc26dddb2d2dce5bcaae282967 | [
"Apache-2.0"
] | null | null | null | 39.566038 | 91 | 0.610873 | 9,293 | package com.example.administrator.catemenu.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.catemenu.R;
/**
* Created by Administrator on 2016/11/7.
*/
public class MineActivity extends Activity {
ImageView mineBackBtn;
TextView sixinTextview;
TextView settingBtn;
TextView passwordChangeTv;
TextView todaySigninTv;
TextView collectTv;
TextView shareTv;
TextView attentionTv;
TextView uploadTv;
TextView orderTv;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mine);
//找到对应控件id
mineBackBtn = (ImageView) findViewById(R.id.mine_back_btn);
sixinTextview = (TextView) findViewById(R.id.sixin_textview);
settingBtn = (TextView) findViewById(R.id.setting_btn);
passwordChangeTv = (TextView) findViewById(R.id.password_change_tv);
todaySigninTv = (TextView) findViewById(R.id.today_signin_tv);
collectTv = (TextView) findViewById(R.id.collect_tv);
shareTv = (TextView) findViewById(R.id.share_tv);
attentionTv = (TextView) findViewById(R.id.attention_tv);
uploadTv = (TextView) findViewById(R.id.upload_tv);
orderTv = (TextView) findViewById(R.id.order_tv);
//设置点击事件
mineBackBtn.setOnClickListener(clickListener);
sixinTextview.setOnClickListener(clickListener);
settingBtn.setOnClickListener(clickListener);
passwordChangeTv.setOnClickListener(clickListener);
todaySigninTv.setOnClickListener(clickListener);
collectTv.setOnClickListener(clickListener);
shareTv.setOnClickListener(clickListener);
attentionTv.setOnClickListener(clickListener);
uploadTv.setOnClickListener(clickListener);
orderTv.setOnClickListener(clickListener);
}
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.mine_back_btn:
intent = new Intent(MineActivity.this,HomePageActivity.class);
startActivity(intent);
break;
case R.id.sixin_textview:
intent = new Intent(MineActivity.this,MinePrivateLetterActivity.class);
startActivity(intent);
break;
case R.id.setting_btn:
intent = new Intent(MineActivity.this,PersonalSettingsActivity.class);
startActivity(intent);
break;
case R.id.password_change_tv:
intent = new Intent(MineActivity.this,ChangePasswordActivity.class);
startActivity(intent);
break;
case R.id.today_signin_tv:
intent = new Intent(MineActivity.this,SigninActivity.class);
startActivity(intent);
break;
case R.id.collect_tv:
intent = new Intent(MineActivity.this,CollectActivity.class);
startActivity(intent);
break;
case R.id.share_tv:
intent = new Intent(MineActivity.this,ShareActivity.class);
startActivity(intent);
break;
case R.id.attention_tv:
intent = new Intent(MineActivity.this,AttentionActivity.class);
startActivity(intent);
break;
case R.id.upload_tv:
intent = new Intent(MineActivity.this,UploadActivity.class);
startActivity(intent);
break;
case R.id.order_tv:
intent = new Intent(MineActivity.this,MyFoodOrderActivity.class);
startActivity(intent);
break;
}
}
};
}
|
3e15da213a8f9b635edecbc82f392da98d812741 | 1,542 | java | Java | webconsole-plugins/ds/src/main/java/org/apache/felix/webconsole/plugins/ds/internal/MetatypeSupport.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 73 | 2020-02-28T19:50:03.000Z | 2022-03-31T14:40:18.000Z | webconsole-plugins/ds/src/main/java/org/apache/felix/webconsole/plugins/ds/internal/MetatypeSupport.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 50 | 2020-03-02T10:53:06.000Z | 2022-03-25T13:23:51.000Z | webconsole-plugins/ds/src/main/java/org/apache/felix/webconsole/plugins/ds/internal/MetatypeSupport.java | chrisr3/felix-dev | f3597cc709d1469d36314b3bff9cb1e609b6cdab | [
"Apache-2.0"
] | 97 | 2020-03-02T10:40:18.000Z | 2022-03-25T01:13:32.000Z | 36.714286 | 90 | 0.708171 | 9,294 | /*
* 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.felix.webconsole.plugins.ds.internal;
import org.osgi.framework.Bundle;
import org.osgi.service.metatype.MetaTypeInformation;
import org.osgi.service.metatype.MetaTypeService;
public class MetatypeSupport
{
public boolean check(final Object obj, final Bundle providingBundle, final String pid)
{
final MetaTypeService mts = (MetaTypeService)obj;
final MetaTypeInformation mti = mts.getMetaTypeInformation(providingBundle);
if (mti != null)
{
try {
return mti.getObjectClassDefinition(pid, null) != null;
} catch (final IllegalArgumentException e) {
return false;
}
}
return false;
}
} |
3e15dab00109b1a4e1f1eb6de464ff4f36d976c1 | 1,247 | java | Java | src/main/java/com/simplegame/server/stage/service/IStageService.java | zuesgooogle/game-server | ec25cecb6601e5ba0a0531d6ebb96d2cbb5b865a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/simplegame/server/stage/service/IStageService.java | zuesgooogle/game-server | ec25cecb6601e5ba0a0531d6ebb96d2cbb5b865a | [
"Apache-2.0"
] | null | null | null | src/main/java/com/simplegame/server/stage/service/IStageService.java | zuesgooogle/game-server | ec25cecb6601e5ba0a0531d6ebb96d2cbb5b865a | [
"Apache-2.0"
] | null | null | null | 20.85 | 90 | 0.632294 | 9,295 | package com.simplegame.server.stage.service;
import com.simplegame.server.stage.model.core.stage.IStage;
import com.simplegame.server.stage.model.core.stage.Point;
/**
*
* @Author ychag@example.com
* @sine 2015年7月17日 上午11:11:09
*
*/
public interface IStageService {
/**
* 角色离开场景
*
* @param stageId
* @param roleId
* @return
*/
public void roleLeaveStage(String stageId, String roleId);
/**
* 角色进入场景
*
* @param stageId
* @param roleId
* @param mapId
* @param x
* @param y
* @return
*/
public void roleEnterStage(String stageId, String roleId, String mapId, int x, int y);
public IStage getStage(String stageId);
public void removeStage(String stageId);
public boolean exist(String stageId);
public boolean checkAndCreateStage(String stageId, String mapId);
public boolean stageCanEnter(String stageId);
/**
* 角色是否可以切换地图
*
* @param roleId
* @param stageId
* @return
*/
public boolean roleCanChangeMap(String roleId, String stageId);
public Point getPosition(String stageId, String roleId);
public void addStageCopy(IStage stageCopy);
}
|
3e15db30b3b7b02498d93d972a2eaf8e431e4643 | 8,393 | java | Java | client-adapter/launcher/src/main/java/com/alibaba/otter/canal/adapter/launcher/common/SyncSwitch.java | AlighieriD/canal | 04f7028d2ae1a5c31dae6d4cbf7ee6d452785d23 | [
"Apache-2.0"
] | 23,220 | 2015-01-04T13:48:17.000Z | 2022-03-31T15:38:51.000Z | client-adapter/launcher/src/main/java/com/alibaba/otter/canal/adapter/launcher/common/SyncSwitch.java | Pay-Baymax/canal | f9e88bc4747085ab28dfba481b5376e4970f69eb | [
"Apache-2.0"
] | 3,863 | 2015-01-04T12:13:41.000Z | 2022-03-31T11:06:07.000Z | client-adapter/launcher/src/main/java/com/alibaba/otter/canal/adapter/launcher/common/SyncSwitch.java | Pay-Baymax/canal | f9e88bc4747085ab28dfba481b5376e4970f69eb | [
"Apache-2.0"
] | 7,006 | 2015-01-04T10:06:29.000Z | 2022-03-31T07:25:23.000Z | 35.563559 | 116 | 0.536876 | 9,296 | package com.alibaba.otter.canal.adapter.launcher.common;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.stereotype.Component;
import com.alibaba.otter.canal.adapter.launcher.config.AdapterCanalConfig;
import com.alibaba.otter.canal.adapter.launcher.config.CuratorClient;
import com.alibaba.otter.canal.common.utils.BooleanMutex;
/**
* 同步开关
*
* @author rewerma @ 2018-10-20
* @version 1.0.0
*/
@Component
public class SyncSwitch {
private static final String SYN_SWITCH_ZK_NODE = "/sync-switch/";
private static final Map<String, BooleanMutex> LOCAL_LOCK = new ConcurrentHashMap<>();
private static final Map<String, BooleanMutex> DISTRIBUTED_LOCK = new ConcurrentHashMap<>();
private Mode mode = Mode.LOCAL;
@Resource
private AdapterCanalConfig adapterCanalConfig;
@Resource
private CuratorClient curatorClient;
@PostConstruct
public void init() {
CuratorFramework curator = curatorClient.getCurator();
if (curator != null) {
mode = Mode.DISTRIBUTED;
DISTRIBUTED_LOCK.clear();
for (String destination : adapterCanalConfig.DESTINATIONS) {
// 对应每个destination注册锁
BooleanMutex mutex = new BooleanMutex(true);
initMutex(curator, destination, mutex);
DISTRIBUTED_LOCK.put(destination, mutex);
startListen(destination, mutex);
}
} else {
mode = Mode.LOCAL;
LOCAL_LOCK.clear();
for (String destination : adapterCanalConfig.DESTINATIONS) {
// 对应每个destination注册锁
LOCAL_LOCK.put(destination, new BooleanMutex(true));
}
}
}
public synchronized void refresh() {
for (String destination : adapterCanalConfig.DESTINATIONS) {
BooleanMutex booleanMutex;
if (mode == Mode.DISTRIBUTED) {
CuratorFramework curator = curatorClient.getCurator();
booleanMutex = DISTRIBUTED_LOCK.get(destination);
if (booleanMutex == null) {
BooleanMutex mutex = new BooleanMutex(true);
initMutex(curator, destination, mutex);
DISTRIBUTED_LOCK.put(destination, mutex);
startListen(destination, mutex);
}
} else {
booleanMutex = LOCAL_LOCK.get(destination);
if (booleanMutex == null) {
LOCAL_LOCK.put(destination, new BooleanMutex(true));
}
}
}
}
@SuppressWarnings("resource")
private synchronized void startListen(String destination, BooleanMutex mutex) {
try {
String path = SYN_SWITCH_ZK_NODE + destination;
CuratorFramework curator = curatorClient.getCurator();
NodeCache nodeCache = new NodeCache(curator, path);
nodeCache.start();
nodeCache.getListenable().addListener(() -> initMutex(curator, destination, mutex));
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
private synchronized void initMutex(CuratorFramework curator, String destination, BooleanMutex mutex) {
try {
String path = SYN_SWITCH_ZK_NODE + destination;
Stat stat = curator.checkExists().forPath(path);
if (stat == null) {
if (!mutex.state()) {
mutex.set(true);
}
} else {
String data = new String(curator.getData().forPath(path), StandardCharsets.UTF_8);
if ("on".equals(data)) {
if (!mutex.state()) {
mutex.set(true);
}
} else {
if (mutex.state()) {
mutex.set(false);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public synchronized void off(String destination) {
if (mode == Mode.LOCAL) {
BooleanMutex mutex = LOCAL_LOCK.get(destination);
if (mutex != null && mutex.state()) {
mutex.set(false);
}
} else {
try {
String path = SYN_SWITCH_ZK_NODE + destination;
try {
curatorClient.getCurator()
.create()
.creatingParentContainersIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, "off".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
curatorClient.getCurator().setData().forPath(path, "off".getBytes(StandardCharsets.UTF_8));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public synchronized void on(String destination) {
if (mode == Mode.LOCAL) {
BooleanMutex mutex = LOCAL_LOCK.get(destination);
if (mutex != null && !mutex.state()) {
mutex.set(true);
}
} else {
try {
String path = SYN_SWITCH_ZK_NODE + destination;
try {
curatorClient.getCurator()
.create()
.creatingParentContainersIfNeeded()
.withMode(CreateMode.PERSISTENT)
.forPath(path, "on".getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
curatorClient.getCurator().setData().forPath(path, "on".getBytes(StandardCharsets.UTF_8));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public synchronized void release(String destination) {
if (mode == Mode.LOCAL) {
BooleanMutex mutex = LOCAL_LOCK.get(destination);
if (mutex != null && !mutex.state()) {
mutex.set(true);
}
}
if (mode == Mode.DISTRIBUTED) {
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
if (mutex != null && !mutex.state()) {
mutex.set(true);
}
}
}
public boolean status(String destination) {
if (mode == Mode.LOCAL) {
BooleanMutex mutex = LOCAL_LOCK.get(destination);
if (mutex != null) {
return mutex.state();
} else {
return false;
}
} else {
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
if (mutex != null) {
return mutex.state();
} else {
return false;
}
}
}
public void get(String destination) throws InterruptedException {
if (mode == Mode.LOCAL) {
BooleanMutex mutex = LOCAL_LOCK.get(destination);
if (mutex != null) {
mutex.get();
}
} else {
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
if (mutex != null) {
mutex.get();
}
}
}
public void get(String destination, long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
if (mode == Mode.LOCAL) {
BooleanMutex mutex = LOCAL_LOCK.get(destination);
if (mutex != null) {
mutex.get(timeout, unit);
}
} else {
BooleanMutex mutex = DISTRIBUTED_LOCK.get(destination);
if (mutex != null) {
mutex.get(timeout, unit);
}
}
}
}
|
3e15db318a3c1ca8cfb9d1604292d1e6ec87ad36 | 6,119 | java | Java | client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 1,125 | 2016-09-11T17:27:35.000Z | 2022-03-29T13:41:58.000Z | client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 346 | 2016-12-03T18:37:07.000Z | 2022-03-29T08:33:04.000Z | client/rest-high-level/src/main/java/org/elasticsearch/client/ccr/FollowInfoResponse.java | abdulazizali77/elasticsearch | 19dfa7be9e163b50a042358246cdbc4e45d2d797 | [
"Apache-2.0"
] | 190 | 2016-12-15T13:46:19.000Z | 2022-03-04T05:17:11.000Z | 34.184358 | 122 | 0.637686 | 9,297 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.client.ccr;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;
import java.util.List;
import java.util.Objects;
public final class FollowInfoResponse {
static final ParseField FOLLOWER_INDICES_FIELD = new ParseField("follower_indices");
private static final ConstructingObjectParser<FollowInfoResponse, Void> PARSER = new ConstructingObjectParser<>(
"indices",
true,
args -> {
@SuppressWarnings("unchecked")
List<FollowerInfo> infos = (List<FollowerInfo>) args[0];
return new FollowInfoResponse(infos);
});
static {
PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), FollowerInfo.PARSER, FOLLOWER_INDICES_FIELD);
}
public static FollowInfoResponse fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
private final List<FollowerInfo> infos;
FollowInfoResponse(List<FollowerInfo> infos) {
this.infos = infos;
}
public List<FollowerInfo> getInfos() {
return infos;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FollowInfoResponse that = (FollowInfoResponse) o;
return infos.equals(that.infos);
}
@Override
public int hashCode() {
return Objects.hash(infos);
}
public static final class FollowerInfo {
static final ParseField FOLLOWER_INDEX_FIELD = new ParseField("follower_index");
static final ParseField REMOTE_CLUSTER_FIELD = new ParseField("remote_cluster");
static final ParseField LEADER_INDEX_FIELD = new ParseField("leader_index");
static final ParseField STATUS_FIELD = new ParseField("status");
static final ParseField PARAMETERS_FIELD = new ParseField("parameters");
private static final ConstructingObjectParser<FollowerInfo, Void> PARSER = new ConstructingObjectParser<>(
"follower_info",
true,
args -> {
return new FollowerInfo((String) args[0], (String) args[1], (String) args[2],
Status.fromString((String) args[3]), (FollowConfig) args[4]);
});
static {
PARSER.declareString(ConstructingObjectParser.constructorArg(), FOLLOWER_INDEX_FIELD);
PARSER.declareString(ConstructingObjectParser.constructorArg(), REMOTE_CLUSTER_FIELD);
PARSER.declareString(ConstructingObjectParser.constructorArg(), LEADER_INDEX_FIELD);
PARSER.declareString(ConstructingObjectParser.constructorArg(), STATUS_FIELD);
PARSER.declareObject(ConstructingObjectParser.optionalConstructorArg(),
(p, c) -> FollowConfig.fromXContent(p), PARAMETERS_FIELD);
}
private final String followerIndex;
private final String remoteCluster;
private final String leaderIndex;
private final Status status;
private final FollowConfig parameters;
FollowerInfo(String followerIndex, String remoteCluster, String leaderIndex, Status status,
FollowConfig parameters) {
this.followerIndex = followerIndex;
this.remoteCluster = remoteCluster;
this.leaderIndex = leaderIndex;
this.status = status;
this.parameters = parameters;
}
public String getFollowerIndex() {
return followerIndex;
}
public String getRemoteCluster() {
return remoteCluster;
}
public String getLeaderIndex() {
return leaderIndex;
}
public Status getStatus() {
return status;
}
public FollowConfig getParameters() {
return parameters;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FollowerInfo that = (FollowerInfo) o;
return Objects.equals(followerIndex, that.followerIndex) &&
Objects.equals(remoteCluster, that.remoteCluster) &&
Objects.equals(leaderIndex, that.leaderIndex) &&
status == that.status &&
Objects.equals(parameters, that.parameters);
}
@Override
public int hashCode() {
return Objects.hash(followerIndex, remoteCluster, leaderIndex, status, parameters);
}
}
public enum Status {
ACTIVE("active"),
PAUSED("paused");
private final String name;
Status(String name) {
this.name = name;
}
public String getName() {
return name;
}
public static Status fromString(String value) {
switch (value) {
case "active":
return Status.ACTIVE;
case "paused":
return Status.PAUSED;
default:
throw new IllegalArgumentException("unexpected status value [" + value + "]");
}
}
}
}
|
3e15dbbcfa81d928742b2146beefdfecf1ddf124 | 1,205 | java | Java | user-service/src/main/java/io/example/UserController.java | rayvaz/event-sourcing-microservices-example | 8d5cc39a752a38cd0e738922e2432ce08afccdae | [
"Apache-2.0"
] | 1 | 2019-02-10T18:05:02.000Z | 2019-02-10T18:05:02.000Z | user-service/src/main/java/io/example/UserController.java | rayvaz/event-sourcing-microservices-example | 8d5cc39a752a38cd0e738922e2432ce08afccdae | [
"Apache-2.0"
] | null | null | null | user-service/src/main/java/io/example/UserController.java | rayvaz/event-sourcing-microservices-example | 8d5cc39a752a38cd0e738922e2432ce08afccdae | [
"Apache-2.0"
] | 2 | 2019-02-10T18:05:08.000Z | 2019-07-30T22:50:05.000Z | 29.390244 | 89 | 0.727801 | 9,298 | package io.example;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.util.logging.Logger;
/**
* Controller for the {@link User} API.
*
* @author Kenny Bastani
*/
@RestController
@RequestMapping("/v1")
@Transactional
public class UserController {
private final UserRepository userRepository;
private final Source source;
private final Logger log = Logger.getLogger(UserController.class.getName());
public UserController(UserRepository userRepository, Source source) {
this.userRepository = userRepository;
this.source = source;
}
@PostMapping(path = "/users")
public Mono<User> createUser(@RequestBody User user) {
User userResult = userRepository.save(user).block();
log.info("User created: " + user.toString());
source.output().send(MessageBuilder
.withPayload(new UserEvent(userResult, EventType.USER_CREATED)).build());
return Mono.justOrEmpty(userResult);
}
}
|
3e15dbe7aae7095cd66297f0ca28dbdfc79640c8 | 203 | java | Java | app/src/main/java/com/blockchain/store/playmarket/data/entities/IpfsVersionResponse.java | vikulin/PlayMarket-2.0-App | 32a8f0e033889b8e61eb3da664c2fe346b9d2afc | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/blockchain/store/playmarket/data/entities/IpfsVersionResponse.java | vikulin/PlayMarket-2.0-App | 32a8f0e033889b8e61eb3da664c2fe346b9d2afc | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/blockchain/store/playmarket/data/entities/IpfsVersionResponse.java | vikulin/PlayMarket-2.0-App | 32a8f0e033889b8e61eb3da664c2fe346b9d2afc | [
"Apache-2.0"
] | null | null | null | 22.555556 | 54 | 0.793103 | 9,299 | package com.blockchain.store.playmarket.data.entities;
import com.google.gson.annotations.SerializedName;
public class IpfsVersionResponse {
@SerializedName("Version")
public String version;
}
|
3e15dbf5fbce4dd1474130008c1e6e826a4aa18b | 5,880 | java | Java | cdap-app-fabric/src/test/java/co/cask/cdap/runtime/WorkflowTest.java | cybervisiontech/cdap | 2d63aaf615794a4dc20906b5d440dc8e741d8b9c | [
"Apache-2.0"
] | null | null | null | cdap-app-fabric/src/test/java/co/cask/cdap/runtime/WorkflowTest.java | cybervisiontech/cdap | 2d63aaf615794a4dc20906b5d440dc8e741d8b9c | [
"Apache-2.0"
] | null | null | null | cdap-app-fabric/src/test/java/co/cask/cdap/runtime/WorkflowTest.java | cybervisiontech/cdap | 2d63aaf615794a4dc20906b5d440dc8e741d8b9c | [
"Apache-2.0"
] | null | null | null | 35.636364 | 117 | 0.711735 | 9,300 | /*
* Copyright © 2014 Cask Data, 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 co.cask.cdap.runtime;
import co.cask.cdap.OneActionWorkflowApp;
import co.cask.cdap.WorkflowApp;
import co.cask.cdap.app.program.Program;
import co.cask.cdap.app.runtime.ProgramOptions;
import co.cask.cdap.app.runtime.ProgramRunner;
import co.cask.cdap.internal.app.deploy.pipeline.ApplicationWithPrograms;
import co.cask.cdap.internal.app.runtime.AbstractListener;
import co.cask.cdap.internal.app.runtime.BasicArguments;
import co.cask.cdap.internal.app.runtime.ProgramRunnerFactory;
import co.cask.cdap.internal.app.runtime.SimpleProgramOptions;
import co.cask.cdap.proto.ProgramType;
import co.cask.cdap.test.XSlowTests;
import co.cask.cdap.test.internal.AppFabricTestHelper;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterators;
import com.google.common.util.concurrent.SettableFuture;
import org.apache.twill.common.Threads;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
*
*/
@Category(XSlowTests.class)
public class WorkflowTest {
private static final Logger LOG = LoggerFactory.getLogger(WorkflowTest.class);
@ClassRule
public static TemporaryFolder tmpFolder = new TemporaryFolder();
private static final Supplier<File> TEMP_FOLDER_SUPPLIER = new Supplier<File>() {
@Override
public File get() {
try {
return tmpFolder.newFolder();
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
};
@Test(timeout = 120 * 1000L)
public void testWorkflow() throws Exception {
final ApplicationWithPrograms app = AppFabricTestHelper.deployApplicationWithManager(WorkflowApp.class,
TEMP_FOLDER_SUPPLIER);
ProgramRunnerFactory runnerFactory = AppFabricTestHelper.getInjector().getInstance(ProgramRunnerFactory.class);
ProgramRunner programRunner = runnerFactory.create(ProgramRunnerFactory.Type.WORKFLOW);
Program program = Iterators.filter(app.getPrograms().iterator(), new Predicate<Program>() {
@Override
public boolean apply(Program input) {
return input.getType() == ProgramType.WORKFLOW;
}
}).next();
String inputPath = createInput();
String outputPath = new File(tmpFolder.newFolder(), "output").getAbsolutePath();
BasicArguments userArgs = new BasicArguments(ImmutableMap.of("inputPath", inputPath, "outputPath", outputPath));
ProgramOptions options = new SimpleProgramOptions(program.getName(), new BasicArguments(), userArgs);
final SettableFuture<String> completion = SettableFuture.create();
programRunner.run(program, options).addListener(new AbstractListener() {
@Override
public void stopped() {
LOG.info("Stopped");
completion.set("Completed");
}
@Override
public void error(Throwable cause) {
LOG.info("Error", cause);
completion.setException(cause);
}
}, Threads.SAME_THREAD_EXECUTOR);
completion.get();
}
@Test(timeout = 120 * 1000L)
public void testOneActionWorkflow() throws Exception {
final ApplicationWithPrograms app = AppFabricTestHelper.deployApplicationWithManager(OneActionWorkflowApp.class,
TEMP_FOLDER_SUPPLIER);
ProgramRunnerFactory runnerFactory = AppFabricTestHelper.getInjector().getInstance(ProgramRunnerFactory.class);
ProgramRunner programRunner = runnerFactory.create(ProgramRunnerFactory.Type.WORKFLOW);
Program program = Iterators.filter(app.getPrograms().iterator(), new Predicate<Program>() {
@Override
public boolean apply(Program input) {
return input.getType() == ProgramType.WORKFLOW;
}
}).next();
ProgramOptions options = new SimpleProgramOptions(program.getName(), new BasicArguments(), new BasicArguments());
final SettableFuture<String> completion = SettableFuture.create();
programRunner.run(program, options).addListener(new AbstractListener() {
@Override
public void stopped() {
LOG.info("Stopped");
completion.set("Completed");
}
@Override
public void error(Throwable cause) {
LOG.info("Error", cause);
completion.setException(cause);
}
}, Threads.SAME_THREAD_EXECUTOR);
String run = completion.get();
Assert.assertEquals("Completed", run);
}
private String createInput() throws IOException {
File inputDir = tmpFolder.newFolder();
File inputFile = new File(inputDir.getPath() + "/words.txt");
inputFile.deleteOnExit();
BufferedWriter writer = new BufferedWriter(new FileWriter(inputFile));
try {
writer.write("this text has");
writer.newLine();
writer.write("two words text inside");
} finally {
writer.close();
}
return inputDir.getAbsolutePath();
}
}
|
3e15dbfa0e8d88ac523393df0911c6fa01fbe13b | 77 | java | Java | hutool-http/src/main/java/cn/hutool/http/body/package-info.java | fengbugou/hutool | 1b8e921ab2c515b8b47d0660f45a3107435e1b55 | [
"MulanPSL-1.0"
] | 3 | 2021-01-06T13:47:59.000Z | 2021-05-17T15:08:45.000Z | hutool-http/src/main/java/cn/hutool/http/body/package-info.java | xiaomeng96-coding/hutool | 181b83a75eabb966ce17eb1ddee3a82059515e7a | [
"MulanPSL-1.0"
] | 11 | 2020-10-14T00:22:37.000Z | 2022-03-31T21:06:06.000Z | hutool-http/src/main/java/cn/hutool/http/body/package-info.java | xiaomeng96-coding/hutool | 181b83a75eabb966ce17eb1ddee3a82059515e7a | [
"MulanPSL-1.0"
] | 1 | 2021-08-18T08:08:38.000Z | 2021-08-18T08:08:38.000Z | 11 | 28 | 0.532468 | 9,301 | /**
* 请求体封装实现
*
* @author looly
*
*/
package cn.hutool.http.body; |
3e15dc13f52a3223ebe2aeba5d043e3e5b2697e9 | 891 | java | Java | src/main/java/net/minecraft/entity/monster/EntityGiantZombie.java | inklesspen1scripter/ultramine_core | 4a7939114c4b61dd3c603302f087004c093101af | [
"WTFPL"
] | null | null | null | src/main/java/net/minecraft/entity/monster/EntityGiantZombie.java | inklesspen1scripter/ultramine_core | 4a7939114c4b61dd3c603302f087004c093101af | [
"WTFPL"
] | null | null | null | src/main/java/net/minecraft/entity/monster/EntityGiantZombie.java | inklesspen1scripter/ultramine_core | 4a7939114c4b61dd3c603302f087004c093101af | [
"WTFPL"
] | 1 | 2020-02-02T15:45:30.000Z | 2020-02-02T15:45:30.000Z | 30.724138 | 85 | 0.796857 | 9,302 | package net.minecraft.entity.monster;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.world.World;
public class EntityGiantZombie extends EntityMob
{
private static final String __OBFID = "CL_00001690";
public EntityGiantZombie(World p_i1736_1_)
{
super(p_i1736_1_);
this.yOffset *= 6.0F;
this.setSize(this.width * 6.0F, this.height * 6.0F);
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(100.0D);
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5D);
this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(50.0D);
}
public float getBlockPathWeight(int p_70783_1_, int p_70783_2_, int p_70783_3_)
{
return this.worldObj.getLightBrightness(p_70783_1_, p_70783_2_, p_70783_3_) - 0.5F;
}
} |
3e15dcc00fe0b524a49b896eaf22356a15f1c140 | 267 | java | Java | src/main/java/com/alternate/clinicmanagement/domain/Doctor.java | randilfernando/clinic-management | 952daba5b3d3b067577d6e2e08bbf3fcab30d994 | [
"MIT"
] | null | null | null | src/main/java/com/alternate/clinicmanagement/domain/Doctor.java | randilfernando/clinic-management | 952daba5b3d3b067577d6e2e08bbf3fcab30d994 | [
"MIT"
] | null | null | null | src/main/java/com/alternate/clinicmanagement/domain/Doctor.java | randilfernando/clinic-management | 952daba5b3d3b067577d6e2e08bbf3fcab30d994 | [
"MIT"
] | 1 | 2018-02-08T07:08:27.000Z | 2018-02-08T07:08:27.000Z | 20.538462 | 60 | 0.707865 | 9,303 | package com.alternate.clinicmanagement.domain;
import java.io.Serializable;
/**
* Created by Randil Fernando on 11/5/2016.
*/
public class Doctor extends Person implements Serializable {
public Doctor(String name, int age) {
super(name, age);
}
}
|
3e15de116b6829aebb628f6cedcc3b1c8ac4b3ec | 8,264 | java | Java | src/com/lpii/evma/model/EventsAdapter.java | alouanemed/EvGuide | 11e69b073f27283441fe064f9498cfad90eaa2fc | [
"Apache-2.0"
] | 1 | 2021-11-06T11:42:29.000Z | 2021-11-06T11:42:29.000Z | src/com/lpii/evma/model/EventsAdapter.java | alouanemed/EvGuide | 11e69b073f27283441fe064f9498cfad90eaa2fc | [
"Apache-2.0"
] | null | null | null | src/com/lpii/evma/model/EventsAdapter.java | alouanemed/EvGuide | 11e69b073f27283441fe064f9498cfad90eaa2fc | [
"Apache-2.0"
] | 1 | 2018-09-25T05:09:48.000Z | 2018-09-25T05:09:48.000Z | 37.563636 | 160 | 0.647386 | 9,304 | package com.lpii.evma.model;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ami.fundapter.interfaces.DynamicImageLoader;
import com.lpii.evma.EvmaApp;
import com.lpii.evma.R;
import com.lpii.evma.controller.EventsController;
import com.lpii.evma.controller.ForfaitController;
import com.squareup.picasso.Picasso;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class EventsAdapter extends BaseAdapter {
// private ArrayList<EventPack> productsList;
ArrayList<HashMap<String, String>> HashMapList;
private Activity activity;
private final Typeface tf;
EventsController mEventsController;
public EventsAdapter(Activity context,
ArrayList<HashMap<String, String>> mHashMapList, Typeface tfBold, EventsController xmEventsController) {
super();
this.HashMapList = mHashMapList;
activity = context;
this.tf = tfBold;
this.mEventsController = xmEventsController;
}
/**
* Define the ViewHolder for our adapter
*/
public static class ViewHolder {
public TextView EvTitle;
public TextView card_event_description;
public TextView event_description_date;
public TextView event_xdescription_dateFIN;
public TextView Ev_Idx;
public TextView Ev_Start_Pricex;
public TextView EvDateMonth;
public TextView EvDateDay;
public ImageView imgThumbnail;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// ---------------
// Boilerplate view inflation and ViewHolder code
// ---------------
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_event_item2, null);
holder = new ViewHolder();
holder.EvTitle = (TextView) v.findViewById(R.id.EvTitle);
holder.card_event_description = (TextView) v.findViewById(R.id.card_event_description);
holder.event_description_date = (TextView) v.findViewById(R.id.event_description_date);
holder.event_xdescription_dateFIN = (TextView) v.findViewById(R.id.event_xdescription_dateFIN);
holder.Ev_Idx = (TextView) v.findViewById(R.id.Ev_Idx);
holder.Ev_Start_Pricex = (TextView) v.findViewById(R.id.Ev_Start_Pricex);
holder.EvDateMonth = (TextView) v.findViewById(R.id.EvDateMonth);
holder.EvDateDay = (TextView) v.findViewById(R.id.EvDateDay);
//holder.price = (TextView) v.findViewById(R.id.price);
holder.imgThumbnail = (ImageView) v.findViewById(R.id.imgThumbnail);
v.setTag(holder);
} else holder = (ViewHolder) v.getTag();
// ------------------------------------------
Event ev = new Event(Integer.valueOf(HashMapList.get(position).get(EventsController.TAG_ID)), HashMapList.get(position).get(EventsController.TAG_NAME),
Integer.valueOf(HashMapList.get(position).get(EventsController.TAG_user_id)), HashMapList.get(position).get(EventsController.TAG_dateTime),
HashMapList.get(position).get(EventsController.TAG_dateTime_fin), HashMapList.get(position).get(EventsController.TAG_event_Statut),
HashMapList.get(position).get(EventsController.TAG_event_Description), HashMapList.get(position).get(EventsController.TAG_event_cover),
Boolean.valueOf(HashMapList.get(position).get(EventsController.TAG_visible)));
System.out.println(ev.toString());
if (ev != null) {
// pack title
if (!TextUtils.isEmpty(ev.getTitle())) {
holder.EvTitle.setText(ev.getTitle());
holder.EvTitle.setTypeface(tf);
holder.EvTitle.setVisibility(View.VISIBLE);
} else {
holder.EvTitle.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(ev.getEventID()+"")) {
holder.Ev_Idx.setText(ev.getEventID()+"");
holder.Ev_Idx.setTypeface(tf);
} else {
holder.Ev_Idx.setVisibility(View.GONE);
}
// pack title
if (!TextUtils.isEmpty(ev.getEvent_Description())) {
holder.card_event_description.setText(ev.getEvent_Description());
holder.card_event_description.setTypeface(tf);
} else {
holder.card_event_description.setVisibility(View.GONE);
}
// pack title
if (!TextUtils.isEmpty(ev.getDateTime())) {
holder.event_description_date.setText(ev.getDateTime());
holder.event_description_date.setTypeface(tf);
} else {
holder.event_description_date.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(ev.getDateTimeFin())) {
holder.event_xdescription_dateFIN.setText(ev.getDateTimeFin());
holder.event_xdescription_dateFIN.setTypeface(tf);
} else {
holder.event_xdescription_dateFIN.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(HashMapList.get(position).get(EventsController.TAG_event_MinPrice))) {
holder.Ev_Start_Pricex.setText(HashMapList.get(position).get(EventsController.TAG_event_MinPrice));
holder.Ev_Start_Pricex.setTypeface(tf);
} else {
holder.Ev_Start_Pricex.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(HashMapList.get(position).get(EventsController.TAG_dateTime_day))) {
holder.EvDateDay.setText(HashMapList.get(position).get(EventsController.TAG_dateTime_day));
holder.EvDateDay.setTypeface(tf);
} else {
holder.EvDateDay.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(HashMapList.get(position).get(EventsController.TAG_dateTime_month))) {
holder.EvDateMonth.setText(HashMapList.get(position).get(EventsController.TAG_dateTime_month));
holder.EvDateMonth.setTypeface(tf);
} else {
holder.EvDateMonth.setVisibility(View.GONE);
}
String urldisplay = EvmaApp.EventCoverUrl + HashMapList.get(position).get(EventsController.TAG_event_cover);
Picasso.with(activity).load(urldisplay).placeholder(R.drawable.defaultcoverx).into(holder.imgThumbnail);
//Picasso.with(context).load("http://postimg.org/image/wjidfl5pd/").into(imageView);
//new DownloadImageTask(holder.imgThumbnail).execute(urldisplay);
}
return v;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
// ---------------
// More boilerplate methods
// ---------------
@Override
public int getCount() {
return HashMapList == null ? 0 : HashMapList.size();
}
@Override
public Object getItem(int position) {
return HashMapList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
|
3e15de751dc6537fae50604cd31deeb5da262a0b | 15,740 | java | Java | src/Vista/Solicitudes.java | KevinJp21/Tienda | 95e0b4899f5eeecb4baa2743883baf6643832c7b | [
"Apache-2.0"
] | null | null | null | src/Vista/Solicitudes.java | KevinJp21/Tienda | 95e0b4899f5eeecb4baa2743883baf6643832c7b | [
"Apache-2.0"
] | null | null | null | src/Vista/Solicitudes.java | KevinJp21/Tienda | 95e0b4899f5eeecb4baa2743883baf6643832c7b | [
"Apache-2.0"
] | 1 | 2021-11-09T19:16:51.000Z | 2021-11-09T19:16:51.000Z | 51.103896 | 158 | 0.57859 | 9,305 | package Vista;
import java.awt.Color;
public class Solicitudes extends javax.swing.JDialog {
public Solicitudes(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
clearTableSolicitud();
JTableSolicitud.setVisible(false);
JTableSolicitud.setEnabled(false);
}
public static void clearTableSolicitud() {
for (int i = 0; i < JTableSolicitud.getRowCount(); i++) {
for (int j = 0; j < JTableSolicitud.getColumnCount(); j++) {
JTableSolicitud.setValueAt("", i, j);
}
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
TXTUser = new javax.swing.JLabel();
JBAceptar = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
JTableSolicitud = new javax.swing.JTable();
TXTTotalSolicitud = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
TXTUser.setBackground(new java.awt.Color(0, 0, 0));
TXTUser.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N
TXTUser.setForeground(new java.awt.Color(0, 0, 0));
TXTUser.setText("Por el momento no se encuentra ninguna solicitud disponible...");
JBAceptar.setBackground(new java.awt.Color(0, 156, 222));
JBAceptar.setFont(new java.awt.Font("Century Gothic", 1, 18)); // NOI18N
JBAceptar.setForeground(new java.awt.Color(255, 255, 255));
JBAceptar.setText("Aceptar");
JBAceptar.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
JBAceptar.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
JBAceptarMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
JBAceptarMouseExited(evt);
}
});
JBAceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JBAceptarActionPerformed(evt);
}
});
jScrollPane2.setAutoscrolls(true);
jScrollPane2.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
JTableSolicitud.setAutoCreateRowSorter(true);
JTableSolicitud.setFont(new java.awt.Font("Century Gothic", 1, 16)); // NOI18N
JTableSolicitud.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null},
{null, null, null, null, null, null}
},
new String [] {
"ID", "Articulo", "Precio", "Stock", "Cantidad", "Subtotal"
}
) {
boolean[] canEdit = new boolean [] {
false, false, false, false, false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
JTableSolicitud.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
JTableSolicitud.setSelectionBackground(new java.awt.Color(60, 63, 65));
JTableSolicitud.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
JTableSolicitudMouseClicked(evt);
}
});
jScrollPane2.setViewportView(JTableSolicitud);
TXTTotalSolicitud.setFont(new java.awt.Font("Century Gothic", 1, 24)); // NOI18N
TXTTotalSolicitud.setForeground(new java.awt.Color(255, 0, 0));
TXTTotalSolicitud.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
TXTTotalSolicitud.setText(" ");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(TXTUser, javax.swing.GroupLayout.PREFERRED_SIZE, 568, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(TXTTotalSolicitud, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 865, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(331, 331, 331)
.addComponent(JBAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(28, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(TXTUser, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(TXTTotalSolicitud))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 42, Short.MAX_VALUE)
.addComponent(JBAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void JBAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JBAceptarActionPerformed
this.dispose();
}//GEN-LAST:event_JBAceptarActionPerformed
private void JTableSolicitudMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JTableSolicitudMouseClicked
}//GEN-LAST:event_JTableSolicitudMouseClicked
private void JBAceptarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JBAceptarMouseEntered
JBAceptar.setBackground(new Color(0, 156, 222));
}//GEN-LAST:event_JBAceptarMouseEntered
private void JBAceptarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JBAceptarMouseExited
JBAceptar.setBackground(new Color(0, 134, 190));
}//GEN-LAST:event_JBAceptarMouseExited
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Solicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Solicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Solicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Solicitudes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Solicitudes dialog = new Solicitudes(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton JBAceptar;
public static javax.swing.JTable JTableSolicitud;
public static javax.swing.JLabel TXTTotalSolicitud;
public static javax.swing.JLabel TXTUser;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
|
3e15df345fa1343160635f5177573c085497bb4e | 1,738 | java | Java | core/src/main/java/net/mabako/steamgifts/tasks/LogoutTask.java | chickdan/SteamGifts | ecd5095449a55c10a902378726413e0fa02c6ea9 | [
"MIT"
] | 75 | 2016-02-06T20:19:53.000Z | 2022-03-01T20:30:58.000Z | core/src/main/java/net/mabako/steamgifts/tasks/LogoutTask.java | chickdan/SteamGifts | ecd5095449a55c10a902378726413e0fa02c6ea9 | [
"MIT"
] | 43 | 2016-02-17T15:59:49.000Z | 2022-02-09T11:52:11.000Z | core/src/main/java/net/mabako/steamgifts/tasks/LogoutTask.java | chickdan/SteamGifts | ecd5095449a55c10a902378726413e0fa02c6ea9 | [
"MIT"
] | 25 | 2016-02-06T20:19:58.000Z | 2021-07-01T14:45:43.000Z | 28.032258 | 71 | 0.646145 | 9,306 | package net.mabako.steamgifts.tasks;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import net.mabako.Constants;
import net.mabako.steamgifts.activities.MainActivity;
import org.jsoup.Jsoup;
import java.io.IOException;
public class LogoutTask extends AsyncTask<Void, Void, Boolean> {
private static final String TAG = LogoutTask.class.getSimpleName();
private final Activity activity;
private ProgressDialog progressDialog;
private final String sessionId;
public LogoutTask(MainActivity activity, String sessionId) {
this.activity = activity;
this.sessionId = sessionId;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Logging out...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected Boolean doInBackground(Void... params) {
// Mostly irrelevant since we clear the stored session id...
try {
Jsoup.connect("https://www.steamgifts.com/?logout")
.userAgent(Constants.JSOUP_USER_AGENT)
.timeout(Constants.JSOUP_TIMEOUT)
.cookie("PHPSESSID", sessionId)
.get();
Log.i(TAG, "Successfully logged out");
return true;
}
catch(IOException e) {
Log.e(TAG, "Failed to log out", e);
return false;
}
}
@Override
protected void onPostExecute(Boolean aBoolean) {
progressDialog.dismiss();
}
}
|
3e15df3e3adf798bb347783c814b629c37ee2a77 | 30,807 | java | Java | src/main/java/moe/gensoukyo/mcgproject/common/feature/rsgauges/blocks/BlockAutoSwitch.java | Chloe-koopa/MCGProject | cfbe67c291b605e5dc72f56408b3dc51b917d3de | [
"MIT"
] | 5 | 2020-03-10T03:09:12.000Z | 2020-07-18T06:29:34.000Z | src/main/java/moe/gensoukyo/mcgproject/common/feature/rsgauges/blocks/BlockAutoSwitch.java | Chloe-koopa/MCGProject | cfbe67c291b605e5dc72f56408b3dc51b917d3de | [
"MIT"
] | 2 | 2020-04-27T04:01:43.000Z | 2020-05-27T08:42:01.000Z | src/main/java/moe/gensoukyo/mcgproject/common/feature/rsgauges/blocks/BlockAutoSwitch.java | Chloe-koopa/MCGProject | cfbe67c291b605e5dc72f56408b3dc51b917d3de | [
"MIT"
] | 5 | 2020-03-10T03:09:37.000Z | 2020-06-29T08:11:36.000Z | 44.326619 | 269 | 0.632356 | 9,307 | /*
* @file BlockAutoSwitch.java
* @author Stefan Wilhelm (wile)
* @copyright (C) 2018 Stefan Wilhelm
* @license MIT (see https://opensource.org/licenses/MIT)
*
* Basic class for blocks representing redstone signal sources, like
* the vanilla lever or button.
*/
package moe.gensoukyo.mcgproject.common.feature.rsgauges.blocks;
import moe.gensoukyo.mcgproject.common.feature.rsgauges.detail.ModAuxiliaries;
import moe.gensoukyo.mcgproject.common.feature.rsgauges.detail.ModConfig;
import moe.gensoukyo.mcgproject.common.feature.rsgauges.detail.ModResources;
import moe.gensoukyo.mcgproject.common.feature.rsgauges.items.ItemSwitchLinkPearl;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityVillager;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class BlockAutoSwitch extends BlockSwitch
{
public BlockAutoSwitch(String registryName, AxisAlignedBB unrotatedBB, long config, @Nullable ModResources.BlockSoundEvent powerOnSound, @Nullable ModResources.BlockSoundEvent powerOffSound, @Nullable Material material)
{ super(registryName, unrotatedBB, null, config, powerOnSound, powerOffSound, material); }
public BlockAutoSwitch(String registryName, AxisAlignedBB unrotatedBB, long config, @Nullable ModResources.BlockSoundEvent powerOnSound, @Nullable ModResources.BlockSoundEvent powerOffSound)
{ super(registryName, unrotatedBB, null, config, powerOnSound, powerOffSound, null); }
@Override
public boolean onLinkRequest(final ItemSwitchLinkPearl.SwitchLink link, long req, final World world, final BlockPos pos, @Nullable final EntityPlayer player)
{
if((world==null) || ((config & (SWITCH_CONFIG_LINK_TARGET_SUPPORT))==0) || (world.isRemote)) return false;
if((config & (SWITCH_CONFIG_TIMER_INTERVAL))==0) return false; // only interval timer can be a link target
IBlockState state = world.getBlockState(pos);
if((state == null) || (!(state.getBlock() instanceof BlockAutoSwitch))) return false;
TileEntityAutoSwitch te = getTe(world, pos);
if((te==null) || (!te.check_link_request(link))) return false;
te.updateSwitchState(state, this, !state.getValue(POWERED), 0);
return true;
}
@Override
public void updateTick(World world, BlockPos pos, IBlockState state, Random rand)
{}
@Override
public TileEntity createTileEntity(World world, IBlockState state)
{
if((config & (SWITCH_CONFIG_SENSOR_VOLUME|SWITCH_CONFIG_SENSOR_LINEAR))!=0) {
return new TileEntityDetectorSwitch();
} else if((config & (SWITCH_CONFIG_SENSOR_ENVIRONMENTAL))!=0) {
return new TileEntityEnvironmentalSensorSwitch();
} else if((config & (SWITCH_CONFIG_TIMER_INTERVAL))!=0) {
return new TileEntityIntervalTimerSwitch();
} else {
return new TileEntityAutoSwitch();
}
}
@Override
public TileEntityAutoSwitch getTe(IBlockAccess world, BlockPos pos)
{
TileEntity te = world.getTileEntity(pos);
if((!(te instanceof TileEntityAutoSwitch))) return null;
return (TileEntityAutoSwitch)te;
}
/**
* Tile entity base
*/
public static class TileEntityAutoSwitch extends TileEntitySwitch
{
protected final void updateSwitchState(IBlockState state, BlockAutoSwitch block, boolean active, int hold_time)
{
if(active) {
on_timer_reset(hold_time);
if(!state.getValue(POWERED)) {
if(this instanceof TileEntityIntervalTimerSwitch) ((TileEntityIntervalTimerSwitch)this).restart();
world.setBlockState(pos, (state=state.withProperty(POWERED, true)), 1|2);
block.power_on_sound.play(world, pos);
world.notifyNeighborsOfStateChange(pos, block, false);
world.notifyNeighborsOfStateChange(pos.offset(state.getValue(FACING).getOpposite()), block, false);
if((block.config & BlockSwitch.SWITCH_CONFIG_LINK_SOURCE_SUPPORT)!=0) {
if(!activate_links(ItemSwitchLinkPearl.SwitchLink.SWITCHLINK_RELAY_ACTIVATE)) {
ModResources.BlockSoundEvents.SWITCHLINK_LINK_PEAL_USE_FAILED.play(world, pos);
}
}
}
} else if(state.getValue(POWERED)) {
if((hold_time<=0) || (on_time_remaining() <= 0)) {
world.setBlockState(pos, (state=state.withProperty(POWERED, false)));
block.power_off_sound.play(world, pos);
world.notifyNeighborsOfStateChange(pos, block, false);
world.notifyNeighborsOfStateChange(pos.offset(state.getValue(FACING).getOpposite()), block, false);
if((block.config & BlockSwitch.SWITCH_CONFIG_LINK_SOURCE_SUPPORT)!=0) {
if(!activate_links(ItemSwitchLinkPearl.SwitchLink.SWITCHLINK_RELAY_DEACTIVATE)) {
ModResources.BlockSoundEvents.SWITCHLINK_LINK_PEAL_USE_FAILED.play(world, pos);
}
}
}
}
}
}
/**
* Tile entity for entity detection based auto switches
*/
public static class TileEntityDetectorSwitch extends TileEntityAutoSwitch implements ITickable
{
public static final Class<?> filter_classes[] = { EntityLivingBase.class, EntityPlayer.class, EntityMob.class, EntityAnimal.class, EntityVillager.class, EntityItem.class, Entity.class };
public static final String filter_class_names[] = { "creatures", "players", "mobs", "animals", "villagers", "objects", "everything" };
private static final int max_sensor_range_ = 16;
private int sensor_entity_count_threshold_ = 1;
private int sensor_range_ = 5;
private int filter_ = 0;
private AxisAlignedBB area_ = null;
private int update_interval_ = 8;
private int update_timer_ = 0;
public int filter()
{ return filter_; }
public void filter(int sel)
{ filter_ = (sel<0) ? 0 : (sel >= filter_classes.length) ? (filter_classes.length-1) : sel; }
public Class<?> filter_class()
{ return (filter_<=0) ? (filter_classes[0]) : ((filter_ >= filter_classes.length) ? (filter_classes[filter_classes.length-1]) : filter_classes[filter_]); }
public void sensor_entity_threshold(int count)
{ sensor_entity_count_threshold_ = (count < 1) ? 1 : count; }
public int sensor_entity_threshold()
{ return sensor_entity_count_threshold_; }
public void sensor_range(int r)
{ sensor_range_ = (r<1) ? (1) : ((r>max_sensor_range_) ? max_sensor_range_ : r); }
public int sensor_range()
{ return sensor_range_; }
@Override
public void writeNbt(NBTTagCompound nbt, boolean updatePacket)
{
super.writeNbt(nbt, updatePacket);
nbt.setInteger("range", sensor_range_);
nbt.setInteger("entitythreshold", sensor_entity_count_threshold_);
nbt.setInteger("filter", filter_);
}
@Override
public void readNbt(NBTTagCompound nbt, boolean updatePacket)
{
super.readNbt(nbt, updatePacket);
sensor_range(nbt.getInteger("range"));
sensor_entity_threshold(nbt.getInteger("entitythreshold"));
filter(nbt.getInteger("filter"));
}
@Override
public void reset()
{ super.reset(); update_timer_=0; area_=null; sensor_range_=5; filter_=0; }
@Override
public boolean activation_config(IBlockState state, @Nullable EntityPlayer player, double x, double y)
{
if(state == null) return false;
final int direction = (y >= 12) ? (1) : ((y <= 5) ? (-1) : (0));
final int field = ((x>=2) && (x<=3.95)) ? (1) : (
((x>=4.25) && (x<=7)) ? (2) : (
((x>=8) && (x<=10)) ? (3) : (
((x>=11) && (x<=13)) ? (4) : (0)
)));
if((direction==0) || (field==0)) return false;
switch(field) {
case 1: {
sensor_range(sensor_range()+direction);
area_ = null;
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.detector.sensor_range", TextFormatting.BLUE, new Object[]{sensor_range()}));
break;
}
case 2: {
sensor_entity_threshold(sensor_entity_threshold() + direction);
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.detector.entity_threshold", TextFormatting.YELLOW, new Object[]{sensor_entity_threshold()}));
break;
}
case 3: {
filter(filter() + direction);
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.detector.entity_filter", TextFormatting.DARK_GREEN, new Object[]{new TextComponentTranslation("rsgauges.switchconfig.detector.entity_filter."+filter_class_names[filter()])}));
break;
}
case 4: {
on_power(on_power() + direction);
if(on_power() < 1) on_power(1);
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.detector.output_power", TextFormatting.RED, new Object[]{on_power()}));
break;
}
}
markDirty();
return true;
}
@Override
public void update()
{
if(ModConfig.zmisc.without_detector_switch_update) return;
if((getWorld().isRemote) || (--update_timer_ > 0)) return;
update_timer_ = update_interval_;
IBlockState state = getWorld().getBlockState(getPos());
if((state==null) || (!(state.getBlock() instanceof BlockAutoSwitch))) return;
BlockAutoSwitch block = (BlockAutoSwitch)(state.getBlock());
// initialisations
if(update_interval_==0) {
if((block.config & SWITCH_CONFIG_SENSOR_LINEAR) != 0) {
update_interval_ = ModConfig.tweaks.autoswitch_linear_update_interval;
} else {
update_interval_ = ModConfig.tweaks.autoswitch_volumetric_update_interval;
}
}
if(area_ == null) {
int size = sensor_range();
AxisAlignedBB range_bb;
if((block.config & SWITCH_CONFIG_SENSOR_VOLUME) != 0) {
range_bb = new AxisAlignedBB(0,-2,-size, size,2,size);
} else if((block.config & SWITCH_CONFIG_SENSOR_LINEAR) != 0) {
range_bb = new AxisAlignedBB(-0.5,-0.5,-0.5, size,0.5,0.5);
} else {
range_bb = new AxisAlignedBB(0,0,0, 1,0,0);
}
EnumFacing facing = state.getValue(FACING);
AxisAlignedBB bb = ModAuxiliaries.transform_forward(range_bb, facing).offset(getPos()).expand(1,1,1);
area_ = new AxisAlignedBB(bb.minX, bb.minY, bb.minZ, bb.maxX, bb.maxY, bb.maxZ);
}
// measurement
boolean active = false;
@SuppressWarnings("unchecked")
List<Entity> hits = world.getEntitiesWithinAABB((Class<Entity>)filter_class(), area_);
if(hits.size() >= sensor_entity_count_threshold_) {
int num_seen = 0;
final Vec3d switch_position = new Vec3d((double)getPos().getX()+.5, (double)getPos().getY()+.5, (double)getPos().getZ()+.5);
for(Entity e:hits) {
if(
(world.rayTraceBlocks(new Vec3d(e.posX-0.2,e.posY+e.getEyeHeight(),e.posZ-0.2), switch_position, true, false, false) == null) ||
(world.rayTraceBlocks(new Vec3d(e.posX+0.2,e.posY+e.getEyeHeight(),e.posZ+0.2), switch_position, true, false, false) == null)
) {
double v = e.motionX * e.motionX + e.motionY * e.motionY + e.motionZ * e.motionZ;
if (((block.config & SWITCH_CONFIG_SENSOR_VOLUME) != 0 && v > 0.001) ||
(block.config & SWITCH_CONFIG_SENSOR_LINEAR) != 0) // TODO: 添加这个判断使得 *红外传感器* 可以检测运动
if(++num_seen >= sensor_entity_count_threshold_) {
active = true;
break;
}
}
}
}
// state setting
updateSwitchState(state, block, active, configured_on_time());
}
}
/**
* Tile entity for environmental and time sensor based switches
*/
public static class TileEntityEnvironmentalSensorSwitch extends TileEntityAutoSwitch implements ITickable
{
protected static final int debounce_max = 10;
protected int update_interval_ = 10;
protected double threshold0_on_ = 0;
protected double threshold0_off_ = 0;
protected int debounce_ = 0;
protected int update_timer_ = 0;
protected int debounce_counter_ = 0;
public double threshold0_on()
{ return threshold0_on_; }
public double threshold0_off()
{ return threshold0_off_; }
public int debounce()
{ return debounce_; }
public void threshold0_on(double v)
{ threshold0_on_ = (v<0) ? (0) : ((v>15.0) ? (15.0) : (v)); }
public void threshold0_off(double v)
{ threshold0_off_ = (v<0) ? (0) : ((v>15.0) ? (15.0) : (v)); }
public void debounce(int v)
{ debounce_ = (v<0) ? (0) : ((v>debounce_max) ? (debounce_max) : (v)); }
@Override
public void writeNbt(NBTTagCompound nbt, boolean updatePacket)
{
super.writeNbt(nbt, updatePacket);
nbt.setDouble("threshold0_on", threshold0_on());
nbt.setDouble("threshold0_off", threshold0_off());
nbt.setInteger("debounce", debounce());
}
@Override
public void readNbt(NBTTagCompound nbt, boolean updatePacket)
{
super.readNbt(nbt, updatePacket);
threshold0_on(nbt.getDouble("threshold0_on"));
threshold0_off(nbt.getDouble("threshold0_off"));
debounce(nbt.getInteger("debounce"));
}
@Override
public boolean activation_config(IBlockState state, @Nullable EntityPlayer player, double x, double y)
{
if(state == null) return false;
final BlockSwitch block = (BlockSwitch)state.getBlock();
// @TODO: Construction time list or lambla for field assignment.
final int direction = (y >= 13) ? (1) : ((y <= 2) ? (-1) : (0));
final int field = ((x>=2) && (x<=3.95)) ? (1) : (
((x>=4.25) && (x<=7)) ? (2) : (
((x>=8) && (x<=10)) ? (3) : (
((x>=11) && (x<=13)) ? (4) : (0)
)));
if((direction==0) || (field==0)) return false;
if((block.config & SWITCH_CONFIG_SENSOR_LIGHT)!=0) {
switch(field) {
case 1: {
threshold0_on(threshold0_on()+direction);
if(threshold0_off() > threshold0_on()) threshold0_off(threshold0_on());
break;
}
case 2: {
threshold0_off(threshold0_off()+direction);
if(threshold0_on() < threshold0_off()) threshold0_on(threshold0_off());
break;
}
case 3: { debounce(debounce()+direction); break; }
case 4: { on_power(on_power() + direction); break; }
}
if(threshold0_on() < 1) threshold0_on(1);
if(on_power() < 1) on_power(1);
{
ArrayList<Object> tr = new ArrayList<>();
final TextComponentTranslation trunit = ModAuxiliaries.localizable("switchconfig.lightsensor.lightunit", null);
TextComponentString separator = (new TextComponentString(" | ")); separator.getStyle().setColor(TextFormatting.GRAY);
tr.add(ModAuxiliaries.localizable("switchconfig.lightsensor.threshold_on", TextFormatting.BLUE, new Object[]{(int)threshold0_on(), trunit}));
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.lightsensor.threshold_off", TextFormatting.YELLOW, new Object[]{(int)threshold0_off(), trunit})));
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.lightsensor.output_power", TextFormatting.RED, new Object[]{on_power()})));
if(debounce()>0) {
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.lightsensor.debounce", TextFormatting.DARK_GREEN, new Object[]{debounce()})));
} else {
tr.add(new TextComponentString(""));
}
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.lightsensor", TextFormatting.RESET, tr.toArray()));
}
} else if((block.config & (SWITCH_CONFIG_TIMER_DAYTIME))!=0) {
final double time_scaling = 15.0d * 500.0d / 24000.0d; // 1/2h
switch(field) {
case 1: {
double v = threshold0_on()+(time_scaling*direction);
if(v < 0) v += 15.0; else if(v > 15) v = 0;
threshold0_on(v);
break;
}
case 2: {
double v = threshold0_off()+(time_scaling*direction);
if(v < 0) v += 15.0; else if(v > 15) v = 0;
threshold0_off(v);
break;
}
case 3: { debounce(debounce()+direction); break; }
case 4: { on_power(on_power() + direction); break; }
}
if(on_power() < 1) on_power(1);
{
// @TODO: day time localisation: how the hack that, transfer long timestamp with tagging and localise on client or system time class?
TextComponentString separator = (new TextComponentString(" | ")); separator.getStyle().setColor(TextFormatting.GRAY);
ArrayList<Object> tr = new ArrayList<>();
tr.add(ModAuxiliaries.localizable("switchconfig.daytimerclock.daytime_on", TextFormatting.BLUE, new Object[]{ModAuxiliaries.daytimeToString((long)(threshold0_on()*24000.0/15.0))}));
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.daytimerclock.daytime_off", TextFormatting.YELLOW, new Object[]{ModAuxiliaries.daytimeToString((long)(threshold0_off()*24000.0/15.0))})));
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.daytimerclock.output_power", TextFormatting.RED, new Object[]{on_power()})));
if(debounce()>0) {
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.daytimerclock.random", TextFormatting.DARK_GREEN, new Object[]{debounce()}) ));
} else {
tr.add(new TextComponentString(""));
}
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.daytimerclock.output_power", TextFormatting.RED, new Object[]{on_power()})));
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.daytimerclock", TextFormatting.RESET, tr.toArray()));
}
} else if((block.config & (SWITCH_CONFIG_SENSOR_RAIN|SWITCH_CONFIG_SENSOR_LIGHTNING))!=0) {
switch(field) {
case 4: { on_power(on_power() + direction); break; }
}
if(on_power() < 1) on_power(1);
{
if((block.config & SWITCH_CONFIG_SENSOR_RAIN)!=0) {
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.rainsensor.output_power", TextFormatting.RED, new Object[]{on_power()}));
} else {
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.thundersensor.output_power", TextFormatting.RED, new Object[]{on_power()}));
}
}
}
markDirty();
return true;
}
@Override
public void update()
{
if(ModConfig.zmisc.without_environmental_switch_update) return;
if((!hasWorld()) || (getWorld().isRemote) || (--update_timer_ > 0)) return;
if(update_interval_ < 10) update_interval_ = 10;
update_timer_ = update_interval_ + (int)(Math.random()*5); // sensor timing noise using rnd
IBlockState state = getWorld().getBlockState(getPos());
if((state==null) || (!(state.getBlock() instanceof BlockAutoSwitch))) return;
BlockAutoSwitch block = (BlockAutoSwitch)(state.getBlock());
boolean active = state.getValue(POWERED);
if((block.config & SWITCH_CONFIG_TIMER_DAYTIME) != 0) {
long wt = world.getWorldTime() % 24000;
final double t = 15.0/24000.0 * wt;
boolean active_setpoint = false;
if(threshold0_on() == threshold0_off()) {
active_setpoint = false;
} else if(threshold0_on() < threshold0_off()) {
active_setpoint = (t >= threshold0_on()) && (t <= threshold0_off());
} else {
active_setpoint = ((t >= threshold0_on()) && (t <= 15.0)) || (t >= 0.0) && (t <= threshold0_off());
}
if(active != active_setpoint) {
if(debounce() <= 0) {
active = active_setpoint;
} else {
double d1 = (1.0d - ((double)(debounce()))/(debounce_max*0.9)) * 0.7;
d1 = d1 * d1;
if(Math.random() <= d1) active = active_setpoint;
}
}
} else if((block.config & SWITCH_CONFIG_SENSOR_LIGHT) != 0) {
if((threshold0_on()==0) && (threshold0_off()==0) ) {
threshold0_on(7);
threshold0_off(6);
} else {
// measurement
double value = getWorld().getLight(pos, false);
// switch value evaluation
int measurement = 0;
if(threshold0_off() >= threshold0_on()) {
// Use exact light value match
measurement += (value==threshold0_on()) ? 1 : -1;
} else {
// Standard balanced threshold switching.
if(value >= threshold0_on()) measurement = 1;
if(value <= threshold0_off()) measurement = -1; // priority off
}
if(debounce() <= 0) {
if(measurement!=0) active = (measurement>0);
debounce_counter_ = 0;
} else {
debounce_counter_ = debounce_counter_ + measurement;
if(debounce_counter_ <= 0) {
active = false; debounce_counter_ = 0;
} else if(debounce_counter_ >= debounce_) {
active = true; debounce_counter_ = debounce_;
}
}
}
} else if((block.config & SWITCH_CONFIG_SENSOR_RAIN)!=0) {
if((state.getValue(FACING)!=EnumFacing.UP) && (state.getValue(FACING)!=EnumFacing.DOWN)) {
debounce_counter_ += getWorld().isRainingAt(getPos().offset(EnumFacing.UP, 1)) ? 1 : -1;
if(debounce_counter_ <= 0) {
debounce_counter_ = 0;
active = false;
} else if(debounce_counter_ >= 4) {
debounce_counter_ = 4;
active = true;
}
}
} else if((block.config & SWITCH_CONFIG_SENSOR_LIGHTNING)!=0) {
debounce_counter_ += (getWorld().isThundering() && (getWorld().isRainingAt(getPos()) || getWorld().isRainingAt(getPos().offset(EnumFacing.UP, 20)) )) ? 1 : -1;
if(debounce_counter_ <= 0) {
debounce_counter_ = 0;
active = false;
} else if(debounce_counter_ >= 4) {
debounce_counter_ = 4;
active = true;
}
}
// state setting
updateSwitchState(state, block, active, configured_on_time());
}
}
/**
* Tile entity for timer interval based switches
*/
public static class TileEntityIntervalTimerSwitch extends TileEntityAutoSwitch implements ITickable
{
private static final int ramp_max = 5;
private static final int t_max = 20 * 60 * 10; // 10min @20clk/s
private static final int t_min = 5; // 0.25s @20clk/s
private int p_set_ = 15;
private int t_on_ = 20;
private int t_off_ = 20;
private int ramp_ = 0;
private int update_timer_ = 0;
private int p_ = 0;
private boolean s_ = false;
public TileEntityIntervalTimerSwitch()
{ super(); p_set(15); t_on(20); t_off(20); ramp(0); }
public void restart()
{ update_timer_=0; p_=0; s_=false; }
public int p_set()
{ return p_set_; }
public int t_on()
{ return t_on_; }
public int t_off()
{ return t_off_; }
public int ramp()
{ return ramp_; }
public void p_set(int v)
{ p_set_ = (v<1) ? (1) : ((v>15) ? (15) : (v)); }
public void t_on(int v)
{ t_on_ = (v<0) ? (0) : ((v>t_max) ? (t_max) : (v)); }
public void t_off(int v)
{ t_off_ = (v<0) ? (0) : ((v>t_max) ? (t_max) : (v)); }
public void ramp(int v)
{ ramp_ = (v<0) ? (0) : ((v>ramp_max) ? (ramp_max) : (v)); }
@Override
protected void setWorldCreate(World world)
{ super.setWorldCreate(world); p_set(15); t_on(20); t_off(20); ramp(0); }
@Override
public void writeNbt(NBTTagCompound nbt, boolean updatePacket)
{
super.writeNbt(nbt, updatePacket);
nbt.setInteger("pset", p_set());
nbt.setInteger("toff", t_off());
nbt.setInteger("ton", t_on());
nbt.setInteger("ramp", ramp());
}
@Override
public void readNbt(NBTTagCompound nbt, boolean updatePacket)
{
super.readNbt(nbt, updatePacket);
p_set(nbt.getInteger("pset"));
t_off(nbt.getInteger("toff"));
t_on(nbt.getInteger("ton"));
ramp(nbt.getInteger("ramp"));
}
private int next_higher_interval_setting(int ticks)
{
if (ticks < 100) ticks += 5; // 5s -> 0.25s steps
else if(ticks < 200) ticks += 10; // 10s -> 0.5s steps
else if(ticks < 400) ticks += 20; // 20s -> 1.0s steps
else if(ticks < 600) ticks += 40; // 30s -> 2.0s steps
else if(ticks < 800) ticks += 100; // 40s -> 5.0s steps
else if(ticks < 2400) ticks += 200; // 2min -> 10.0s steps
else ticks += 600; // 5min -> 30.0s steps
return (ticks > t_max) ? (t_max) : (ticks);
}
private int next_lower_interval_setting(int ticks)
{
if (ticks < 100) ticks -= 5; // 5s -> 0.25s steps
else if(ticks < 200) ticks -= 10; // 10s -> 0.5s steps
else if(ticks < 400) ticks -= 20; // 20s -> 1.0s steps
else if(ticks < 600) ticks -= 40; // 30s -> 2.0s steps
else if(ticks < 800) ticks -= 100; // 40s -> 5.0s steps
else if(ticks < 2400) ticks -= 200; // 2min -> 10.0s steps
else ticks -= 600; // 5min -> 30.0s steps
return (ticks < t_min) ? (t_min) : (ticks);
}
@Override
public boolean activation_config(IBlockState state, @Nullable EntityPlayer player, double x, double y)
{
if(state == null) return false;
final int direction = (y >= 13) ? (1) : ((y <= 2) ? (-1) : (0));
final int field = ((x>=2) && (x<=3.95)) ? (1) : (
((x>=4.25) && (x<=7)) ? (2) : (
((x>=8) && (x<=10)) ? (3) : (
((x>=11) && (x<=13)) ? (4) : (0)
)));
final boolean selected = ((direction!=0) && (field!=0));
if(selected) {
switch(field) {
case 1: t_on( (direction > 0) ? next_higher_interval_setting(t_on()) : next_lower_interval_setting(t_on()) ); break;
case 2: t_off( (direction > 0) ? next_higher_interval_setting(t_off()) : next_lower_interval_setting(t_off()) ); break;
case 3: ramp(ramp()+direction); break;
case 4: p_set( ((p_set()<=0) ? 15 : p_set()) + direction); break;
}
markDirty();
}
{
boolean switch_state = false;
try { switch_state = state.getValue(POWERED); } catch(Exception e) {}
if(!selected) switch_state = !switch_state; // will be switched in turn.
updateSwitchState(state, (BlockAutoSwitch) state.getBlock(), switch_state, 0);
{
TextComponentString separator = (new TextComponentString(" | ")); separator.getStyle().setColor(TextFormatting.GRAY);
ArrayList<Object> tr = new ArrayList<>();
tr.add(ModAuxiliaries.localizable("switchconfig.intervaltimer.t_on", TextFormatting.BLUE, new Object[]{ModAuxiliaries.ticksToSecondsString(t_on())}));
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.intervaltimer.t_off", TextFormatting.YELLOW, new Object[]{ModAuxiliaries.ticksToSecondsString(t_off())})));
tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.intervaltimer.output_power", TextFormatting.RED, new Object[]{p_set()})));
if(ramp()>0) tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.intervaltimer.ramp", TextFormatting.DARK_GREEN, new Object[]{ramp()})));
if(!switch_state) tr.add(separator.createCopy().appendSibling(ModAuxiliaries.localizable("switchconfig.intervaltimer.standby", TextFormatting.AQUA)));
while(tr.size() < 5) tr.add(new TextComponentString("")); // const lang file formatting arg count.
ModAuxiliaries.playerStatusMessage(player, ModAuxiliaries.localizable("switchconfig.intervaltimer", TextFormatting.RESET, tr.toArray()));
}
}
return selected; // false: Switches output on/off (blockstate) in caller
}
@Override
public int power(IBlockState state, boolean strong)
{ return (nooutput() || (!state.getValue(POWERED)) || ((strong && weak())) ? (0) : on_power()); }
@Override
public void update()
{
if(ModConfig.zmisc.without_timer_switch_update) return;
if((!hasWorld()) || (getWorld().isRemote) || (--update_timer_ > 0)) return;
int p = p_;
if((t_on()<=0) || (t_off()<=0) || (p_set() <= 0)) {
p_ = 0;
update_timer_ = 20;
} else if(!s_) {
// switching on
update_timer_ = t_on();
if((ramp() <= 0) || ((p_+=ramp()) >= p_set())) {
p_ = p_set();
s_ = true;
} else {
update_timer_ = 5; // ramping @ 0.25s
}
} else {
// switching off
update_timer_ = t_off();
if((ramp() <= 0) || ((p_-=ramp()) <= 0)) {
p_ = 0;
s_ = false;
} else {
update_timer_ = 5; // ramping @ 0.25s
}
}
if(p != p_) {
on_power((inverted() ? (15-p_) : (p_)));
IBlockState state = getWorld().getBlockState(getPos());
if((state==null) || (!(state.getBlock() instanceof BlockAutoSwitch)) || (!state.getValue(POWERED))) {
update_timer_ = 200 + ((int)(Math.random() * 10));
on_power(inverted() ? (15) : (0));
}
world.notifyNeighborsOfStateChange(pos, state.getBlock(), false);
world.notifyNeighborsOfStateChange(pos.offset(state.getValue(FACING).getOpposite()), state.getBlock(), false);
}
}
}
}
|
3e15e07adce1307040d3d69e8739e9be0e239b13 | 1,824 | java | Java | acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/client/DeleteGroupMembershipPage.java | sureshkrishnamoorthy/suresh-mifos | 88e7df964688ca3955b38125213090297d4171a4 | [
"Apache-2.0"
] | 7 | 2016-06-23T12:50:58.000Z | 2020-12-21T18:39:55.000Z | acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/client/DeleteGroupMembershipPage.java | sureshkrishnamoorthy/suresh-mifos | 88e7df964688ca3955b38125213090297d4171a4 | [
"Apache-2.0"
] | 8 | 2019-02-04T14:15:49.000Z | 2022-02-01T01:04:00.000Z | acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/client/DeleteGroupMembershipPage.java | sureshkrishnamoorthy/suresh-mifos | 88e7df964688ca3955b38125213090297d4171a4 | [
"Apache-2.0"
] | 20 | 2015-02-11T06:31:19.000Z | 2020-03-04T15:24:52.000Z | 30.915254 | 75 | 0.722588 | 9,308 | /*
* Copyright (c) 2005-2011 Grameen Foundation USA
* 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.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.test.acceptance.framework.client;
import org.mifos.test.acceptance.framework.MifosPage;
import com.thoughtworks.selenium.Selenium;
public class DeleteGroupMembershipPage extends MifosPage{
public DeleteGroupMembershipPage(Selenium selenium) {
super(selenium);
this.verifyPage("DeleteGroupMembership");
}
private void submit(){
selenium.click("deletegroupmembership.button.submit");
waitForPageToLoad();
}
private void setNote(String note){
selenium.type("deletegroupmembership.input.note", note);
}
public ClientViewDetailsPage confirmDeleteGroupMembership(){
submit();
return new ClientViewDetailsPage(selenium);
}
public ClientViewDetailsPage confirmDeleteGroupMembership(String note){
setNote(note);
submit();
return new ClientViewDetailsPage(selenium);
}
public DeleteGroupMembershipPage confirmDeleteGroupMembershipFail(){
submit();
return new DeleteGroupMembershipPage(selenium);
}
}
|
3e15e08b0e5951f82ef18581f10f09bce9086c0a | 681 | java | Java | pattern/src/main/java/org/biopax/paxtools/pattern/miner/ControlsPhosphorylationMiner.java | metincansiper/Paxtools | 2f93afa94426bf8b5afc2e0e61cd4b269a83288d | [
"MIT"
] | 20 | 2015-07-22T15:48:51.000Z | 2021-12-15T10:49:24.000Z | pattern/src/main/java/org/biopax/paxtools/pattern/miner/ControlsPhosphorylationMiner.java | metincansiper/Paxtools | 2f93afa94426bf8b5afc2e0e61cd4b269a83288d | [
"MIT"
] | 48 | 2015-08-04T13:58:19.000Z | 2021-12-15T19:43:14.000Z | pattern/src/main/java/org/biopax/paxtools/pattern/miner/ControlsPhosphorylationMiner.java | metincansiper/Paxtools | 2f93afa94426bf8b5afc2e0e61cd4b269a83288d | [
"MIT"
] | 10 | 2015-10-02T05:19:38.000Z | 2021-12-15T11:55:55.000Z | 21.28125 | 76 | 0.763583 | 9,309 | package org.biopax.paxtools.pattern.miner;
import org.biopax.paxtools.pattern.Pattern;
import org.biopax.paxtools.pattern.PatternBox;
/**
* Miner for the controls-phosphorylation pattern.
* @author Ozgun Babur
*/
public class ControlsPhosphorylationMiner extends ControlsStateChangeOfMiner
{
/**
* Constructor that sets the type.
*/
public ControlsPhosphorylationMiner()
{
super("phosphorylation",
SIFEnum.CONTROLS_PHOSPHORYLATION_OF.getDescription());
setType(SIFEnum.CONTROLS_PHOSPHORYLATION_OF);
}
/**
* Constructs the pattern.
* @return pattern
*/
@Override
public Pattern constructPattern()
{
return PatternBox.controlsPhosphorylation();
}
}
|
3e15e1453dc57ec42ee2f6db5faf5b2086b1fadd | 2,853 | java | Java | src/main/java/com/contrastsecurity/sarif/model/Notification.java | Contrast-Security-OSS/sarif-java | c3b604addfff0abc6fa1cd946254ad4233900c1a | [
"MIT"
] | null | null | null | src/main/java/com/contrastsecurity/sarif/model/Notification.java | Contrast-Security-OSS/sarif-java | c3b604addfff0abc6fa1cd946254ad4233900c1a | [
"MIT"
] | null | null | null | src/main/java/com/contrastsecurity/sarif/model/Notification.java | Contrast-Security-OSS/sarif-java | c3b604addfff0abc6fa1cd946254ad4233900c1a | [
"MIT"
] | null | null | null | 34.373494 | 100 | 0.76551 | 9,310 | package com.contrastsecurity.sarif.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import java.time.Instant;
import java.util.List;
import org.jetbrains.annotations.Nullable;
/**
* Describes a condition relevant to the tool itself, as opposed to being relevant to a target being
* analyzed by the tool.
*/
@AutoValue
public abstract class Notification {
/** The locations relevant to this notification. */
@JsonProperty("locations")
@Nullable
public abstract List<Location> locations();
/** A message that describes the condition that was encountered. */
@JsonProperty("message")
@Nullable
public abstract Message message();
/** A value specifying the severity level of the notification. */
@JsonProperty("level")
@Nullable
public abstract Level level();
/** The thread identifier of the code that generated the notification. */
@JsonProperty("threadId")
@Nullable
public abstract Integer threadId();
/**
* The Coordinated Universal Time (UTC) date and time at which the analysis tool generated the
* notification.
*/
@JsonProperty("timeUtc")
@Nullable
public abstract Instant timeUtc();
/** The runtime exception, if any, relevant to this notification. */
@JsonProperty("exception")
@Nullable
public abstract Exception exception();
/** A reference used to locate the descriptor relevant to this notification. */
@JsonProperty("descriptor")
@Nullable
public abstract ReportingDescriptorReference descriptor();
/** A reference used to locate the rule descriptor associated with this notification. */
@JsonProperty("associatedRule")
@Nullable
public abstract ReportingDescriptorReference associatedRule();
/** Key/value pairs that provide additional information about the notification. */
@JsonProperty("properties")
@Nullable
public abstract PropertyBag properties();
public static Notification.Builder builder() {
return new AutoValue_Notification.Builder();
}
@AutoValue.Builder
public abstract static class Builder {
public abstract Notification.Builder setLocations(List<Location> locations);
public abstract Notification.Builder setMessage(Message message);
public abstract Notification.Builder setLevel(Level level);
public abstract Notification.Builder setThreadId(Integer threadId);
public abstract Notification.Builder setTimeUtc(Instant timeUtc);
public abstract Notification.Builder setException(Exception exception);
public abstract Notification.Builder setDescriptor(ReportingDescriptorReference descriptor);
public abstract Notification.Builder setAssociatedRule(
ReportingDescriptorReference associatedRule);
public abstract Notification.Builder setProperties(PropertyBag properties);
public abstract Notification build();
}
}
|
3e15e2f31437fea86c05b4cab35e0cb8c1081288 | 254 | java | Java | src/main/java/io/choerodon/asgard/app/service/QuartzMethodService.java | readme1988/asgard-service | 8b827667e98e936743ce8fb79b4a87713219b2fd | [
"Apache-2.0"
] | 5 | 2018-08-28T10:00:03.000Z | 2020-07-09T09:38:11.000Z | src/main/java/io/choerodon/asgard/app/service/QuartzMethodService.java | readme1988/asgard-service | 8b827667e98e936743ce8fb79b4a87713219b2fd | [
"Apache-2.0"
] | 1 | 2019-07-11T11:15:00.000Z | 2019-07-18T03:39:25.000Z | src/main/java/io/choerodon/asgard/app/service/QuartzMethodService.java | readme1988/asgard-service | 8b827667e98e936743ce8fb79b4a87713219b2fd | [
"Apache-2.0"
] | 18 | 2018-09-22T00:43:32.000Z | 2020-09-05T16:18:21.000Z | 21.166667 | 89 | 0.807087 | 9,311 | package io.choerodon.asgard.app.service;
import io.choerodon.asgard.infra.dto.QuartzMethodDTO;
import java.util.List;
public interface QuartzMethodService {
void createMethodList(final String service, final List<QuartzMethodDTO> scanMethods);
}
|
3e15e34232c81928331dbe2652db4d25fa800141 | 1,375 | java | Java | odata_renderer/src/main/java/com/sdl/odata/unmarshaller/PropertyType.java | leviramsey/odata | 500cdb6dfa69197fb135867a7425cd3c85682bf9 | [
"Apache-2.0"
] | 140 | 2015-09-14T10:52:19.000Z | 2021-06-05T03:30:06.000Z | odata_renderer/src/main/java/com/sdl/odata/unmarshaller/PropertyType.java | adilakhter/odata | 96754a6df36e2849a0498f1111640bce515dfaaf | [
"Apache-2.0"
] | 139 | 2015-08-17T14:20:49.000Z | 2021-02-03T19:27:25.000Z | odata_renderer/src/main/java/com/sdl/odata/unmarshaller/PropertyType.java | adilakhter/odata | 96754a6df36e2849a0498f1111640bce515dfaaf | [
"Apache-2.0"
] | 56 | 2015-09-14T10:52:23.000Z | 2020-12-18T09:42:00.000Z | 27.5 | 117 | 0.672727 | 9,312 | /*
* Copyright (c) 2014-2021 All Rights Reserved by the RWS Group for and on behalf of its affiliates and subsidiaries.
*
* 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.sdl.odata.unmarshaller;
import com.sdl.odata.api.edm.model.Type;
/**
* The Property Type.
*/
public final class PropertyType {
private final Type type;
private final boolean collection;
public PropertyType(Type type, boolean collection) {
this.type = type;
this.collection = collection;
}
public Type getType() {
return type;
}
public boolean isCollection() {
return collection;
}
@Override
public String toString() {
if (collection) {
return "Collection(" + type.getFullyQualifiedName() + ")";
} else {
return type.getFullyQualifiedName();
}
}
}
|
3e15e35ece6572d344addb55eeb949e68b043890 | 2,637 | java | Java | Medicaments 2.0/src/java/Session/Utilisateur.java | AmineDjeghri/MedicaProd | bb585876db630e6f4bcc0bce7fb6eb35ebf5ea1d | [
"MIT"
] | 1 | 2020-07-22T09:49:21.000Z | 2020-07-22T09:49:21.000Z | Medicaments 2.0/src/java/Session/Utilisateur.java | AmineDjeghri/MedicaProd | bb585876db630e6f4bcc0bce7fb6eb35ebf5ea1d | [
"MIT"
] | null | null | null | Medicaments 2.0/src/java/Session/Utilisateur.java | AmineDjeghri/MedicaProd | bb585876db630e6f4bcc0bce7fb6eb35ebf5ea1d | [
"MIT"
] | null | null | null | 20.928571 | 169 | 0.611301 | 9,313 |
package Session;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
@Entity
public class Utilisateur implements Serializable{
@Id
@Column(unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
@Column(unique = true)
private String idUtilisateur;
@NotNull
private String mdp;
private String nom;
private String prenom;
@ManyToMany
private List<Role> profils;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getIdUtilisateur() {
return idUtilisateur;
}
public void setIdUtilisateur(String idUtilisateur) {
this.idUtilisateur = idUtilisateur;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getMdp() {
return mdp;
}
public void setMdp(String mdp) {
this.mdp = mdp;
}
public List<Role> getProfiles() {
return profils;
}
public void setProfiles(List<Role> profiles) {
this.profils = profiles;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + Objects.hashCode(this.id);
hash = 31 * hash + Objects.hashCode(this.idUtilisateur);
return hash;
}
public boolean equalsByIDU_MDP(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Utilisateur other = (Utilisateur) obj;
if (!Objects.equals(this.idUtilisateur, other.idUtilisateur)) {
return false;
}
if (!Objects.equals(this.mdp, other.mdp)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Utilisateur{" + "id=" + id + ", idUtilisateur=" + idUtilisateur + ", nom=" + nom + ", prenom=" + prenom + ", mdp=" + mdp + ", profiles=" + profils + '}';
}
}
|
3e15e3f0696bbe3535f0f42a9ebfb4799edf7d15 | 5,073 | java | Java | components/org.wso2.carbon.identity.webfinger/src/test/java/org/wso2/carbon/identity/webfinger/BackwordDefaultWebfingerProcessorTest.java | Migara-Pramod/identity-inbound-auth-oauth | 7286fdd575bb13de7cc382b1f3f7d774813e6d7e | [
"Apache-2.0"
] | 22 | 2016-11-22T06:54:22.000Z | 2022-03-30T01:09:31.000Z | components/org.wso2.carbon.identity.webfinger/src/test/java/org/wso2/carbon/identity/webfinger/BackwordDefaultWebfingerProcessorTest.java | Migara-Pramod/identity-inbound-auth-oauth | 7286fdd575bb13de7cc382b1f3f7d774813e6d7e | [
"Apache-2.0"
] | 553 | 2016-03-04T16:40:18.000Z | 2022-03-30T12:17:18.000Z | components/org.wso2.carbon.identity.webfinger/src/test/java/org/wso2/carbon/identity/webfinger/BackwordDefaultWebfingerProcessorTest.java | Migara-Pramod/identity-inbound-auth-oauth | 7286fdd575bb13de7cc382b1f3f7d774813e6d7e | [
"Apache-2.0"
] | 342 | 2016-03-02T09:58:46.000Z | 2022-03-31T10:35:18.000Z | 44.893805 | 119 | 0.733688 | 9,314 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.identity.webfinger;
import org.apache.commons.collections.iterators.IteratorEnumeration;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.wso2.carbon.identity.common.testng.WithCarbonHome;
import org.wso2.carbon.identity.common.testng.WithRealmService;
import org.wso2.carbon.identity.webfinger.internal.WebFingerServiceComponentHolder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;
/**
* Tests for DefaultWebFingerProcessor.
*/
@WithCarbonHome
@WithRealmService(injectToSingletons = { WebFingerServiceComponentHolder.class })
public class BackwordDefaultWebfingerProcessorTest {
@Test
public void testGetResponse() throws Exception {
DefaultWebFingerProcessor defaultWebFingerProcessor = DefaultWebFingerProcessor.getInstance();
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
final Map<String, String> parameterMap = new HashMap<>();
parameterMap.put(WebFingerConstants.RESOURCE, "TestResource1");
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return parameterMap.get(invocationOnMock.getArguments()[0]);
}
}).when(request).getParameter(Matchers.anyString());
Mockito.doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
return new IteratorEnumeration(parameterMap.keySet().iterator());
}
}).when(request).getParameterNames();
try {
WebFingerResponse response = defaultWebFingerProcessor.getResponse(request);
fail("WebFingerEndpointException should have been thrown");
} catch (WebFingerEndpointException e) {
//Expected exception
}
parameterMap.put(WebFingerConstants.REL, "TestRelates");
try {
WebFingerResponse response = defaultWebFingerProcessor.getResponse(request);
fail("WebFingerEndpointException should have been thrown");
} catch (WebFingerEndpointException e) {
//Expected exception
}
parameterMap.put(WebFingerConstants.RESOURCE, "http://test.t/TestResource1");
WebFingerResponse response = defaultWebFingerProcessor.getResponse(request);
assertNotNull(response);
}
@Test(dataProvider = "dataProviderForHandleError")
public void testHandleError(WebFingerEndpointException exception, int expectedCode) throws Exception {
DefaultWebFingerProcessor defaultWebFingerProcessor = DefaultWebFingerProcessor.getInstance();
assertEquals(defaultWebFingerProcessor.handleError(exception), expectedCode,
"Status Code must match for Exception Type: " + exception.getErrorCode());
}
@DataProvider
private Object[][] dataProviderForHandleError() {
return new Object[][] { { new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_INVALID_REQUEST,
WebFingerConstants.ERROR_CODE_INVALID_REQUEST), HttpServletResponse.SC_BAD_REQUEST },
{ new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_INVALID_RESOURCE,
WebFingerConstants.ERROR_CODE_INVALID_RESOURCE), HttpServletResponse.SC_NOT_FOUND },
{ new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_INVALID_TENANT,
WebFingerConstants.ERROR_CODE_INVALID_TENANT), HttpServletResponse.SC_INTERNAL_SERVER_ERROR },
{ new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_JSON_EXCEPTION,
WebFingerConstants.ERROR_CODE_JSON_EXCEPTION), HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE },
{ new WebFingerEndpointException(WebFingerConstants.ERROR_CODE_NO_WEBFINGER_CONFIG,
WebFingerConstants.ERROR_CODE_NO_WEBFINGER_CONFIG), HttpServletResponse.SC_NOT_FOUND } };
}
}
|
3e15e5b5abea637f1f14eb3702e087ae1d2a1eb2 | 10,939 | java | Java | src/main/java/dev/Hilligans/ourcraft/GameInstance.java | INeedAwesome1/Ourcraft | 91194f35c944ed4808963d0657078d794e9b48b5 | [
"MIT"
] | null | null | null | src/main/java/dev/Hilligans/ourcraft/GameInstance.java | INeedAwesome1/Ourcraft | 91194f35c944ed4808963d0657078d794e9b48b5 | [
"MIT"
] | null | null | null | src/main/java/dev/Hilligans/ourcraft/GameInstance.java | INeedAwesome1/Ourcraft | 91194f35c944ed4808963d0657078d794e9b48b5 | [
"MIT"
] | null | null | null | 38.114983 | 214 | 0.696499 | 9,315 | package dev.Hilligans.ourcraft;
import dev.Hilligans.ourcraft.Biome.Biome;
import dev.Hilligans.ourcraft.Block.Block;
import dev.Hilligans.ourcraft.Client.Audio.SoundBuffer;
import dev.Hilligans.ourcraft.Client.Rendering.Graphics.IGraphicsEngine;
import dev.Hilligans.ourcraft.Client.Rendering.ScreenBuilder;
import dev.Hilligans.ourcraft.Client.Rendering.Widgets.Widget;
import dev.Hilligans.ourcraft.Command.CommandHandler;
import dev.Hilligans.ourcraft.Container.Container;
import dev.Hilligans.ourcraft.Data.Descriptors.Tag;
import dev.Hilligans.ourcraft.Entity.Entity;
import dev.Hilligans.ourcraft.Entity.EntityFetcher;
import dev.Hilligans.ourcraft.Item.Data.ToolLevel;
import dev.Hilligans.ourcraft.Item.Data.ToolLevelList;
import dev.Hilligans.ourcraft.Item.Item;
import dev.Hilligans.ourcraft.ModHandler.Content.ContentPack;
import dev.Hilligans.ourcraft.ModHandler.Content.ModContent;
import dev.Hilligans.ourcraft.ModHandler.EventBus;
import dev.Hilligans.ourcraft.ModHandler.Events.Common.RegistryClearEvent;
import dev.Hilligans.ourcraft.ModHandler.ModLoader;
import dev.Hilligans.ourcraft.Network.PacketBase;
import dev.Hilligans.ourcraft.Network.Protocol;
import dev.Hilligans.ourcraft.Recipe.RecipeHelper.RecipeView;
import dev.Hilligans.ourcraft.Resource.DataLoader.DataLoader;
import dev.Hilligans.ourcraft.Resource.RegistryLoaders.RegistryLoader;
import dev.Hilligans.ourcraft.Resource.Loaders.ResourceLoader;
import dev.Hilligans.ourcraft.Resource.ResourceLocation;
import dev.Hilligans.ourcraft.Resource.ResourceManager;
import dev.Hilligans.ourcraft.Resource.UniversalResourceLoader;
import dev.Hilligans.ourcraft.Settings.Setting;
import dev.Hilligans.ourcraft.Util.ArgumentContainer;
import dev.Hilligans.ourcraft.Util.NamedThreadFactory;
import dev.Hilligans.ourcraft.Recipe.IRecipe;
import dev.Hilligans.ourcraft.Util.Registry.Registry;
import dev.Hilligans.ourcraft.Util.Side;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
public class GameInstance {
public final EventBus EVENT_BUS = new EventBus();
public final ModLoader MOD_LOADER = new ModLoader(this);
public final Logger LOGGER = Logger.getGlobal();
public final ExecutorService EXECUTOR = Executors.newFixedThreadPool(2,new NamedThreadFactory("random_executor"));
public final ResourceManager RESOURCE_MANAGER = new ResourceManager();
public final ModContent OURCRAFT = new ModContent("ourcraft",this).addClassLoader(new URLClassLoader(new URL[]{Ourcraft.class.getProtectionDomain().getCodeSource().getLocation()})).addMainClass(Ourcraft.class);
public final ContentPack CONTENT_PACK = new ContentPack(this);
public final AtomicBoolean REBUILDING = new AtomicBoolean(false);
public final UniversalResourceLoader RESOURCE_LOADER = new UniversalResourceLoader();
public final ArgumentContainer ARGUMENTS = new ArgumentContainer();
public final DataLoader DATA_LOADER = new DataLoader();
public Side side;
public final ToolLevelList MATERIAL_LIST = new ToolLevelList();
public GameInstance() {
REGISTRIES.put("ouracrft:blocks", BLOCKS);
REGISTRIES.put("ourcraft:items", ITEMS);
REGISTRIES.put("ourcraft:biomes", BIOMES);
REGISTRIES.put("ourcraft:tags", TAGS);
REGISTRIES.put("ourcraft:recipes", RECIPES);
REGISTRIES.put("ourcraft:recipe_views", RECIPE_VIEWS);
REGISTRIES.put("ourcraft:graphics_engines", GRAPHICS_ENGINES);
REGISTRIES.put("ourcraft:settings", SETTINGS);
REGISTRIES.put("ourcraft:protocols", PROTOCOLS);
REGISTRIES.put("ourcraft:commands", COMMANDS);
REGISTRIES.put("ourcraft:resource_loaders", RESOURCE_LOADERS);
REGISTRIES.put("ourcraft:sounds", SOUNDS);
REGISTRIES.put("ourcraft:entities", ENTITIES);
REGISTRIES.put("ourcraft:tool_materials", TOOL_MATERIALS);
}
public void loadContent() {
registerDefaultContent();
CONTENT_PACK.mods.put("ourcraft",OURCRAFT);
MOD_LOADER.loadDefaultMods();
CONTENT_PACK.buildVital();
CONTENT_PACK.mods.forEach((s, modContent) -> modContent.invokeRegistryLoaders());
CONTENT_PACK.generateData();
System.out.println("Registered " + BLOCKS.ELEMENTS.size() + " Blocks");
}
public String path = System.getProperty("user.dir");
public final Registry<Registry<?>> REGISTRIES = new Registry<>(this);
public final Registry<Block> BLOCKS = new Registry<>(this, Block.class);
public final Registry<Item> ITEMS = new Registry<>(this, Item.class);
public final Registry<Biome> BIOMES = new Registry<>(this, Biome.class);
public final Registry<Tag> TAGS = new Registry<>(this, Tag.class);
public final Registry<IRecipe<?>> RECIPES = new Registry<>(this, IRecipe.class);
public final Registry<RecipeView<?>> RECIPE_VIEWS = new Registry<>(this, RecipeView.class);
public final Registry<IGraphicsEngine<?,?>> GRAPHICS_ENGINES = new Registry<>(this, IGraphicsEngine.class);
public final Registry<CommandHandler> COMMANDS = new Registry<>(this, CommandHandler.class);
public final Registry<Protocol> PROTOCOLS = new Registry<>(this, Protocol.class);
public final Registry<Setting> SETTINGS = new Registry<>(this, Setting.class);
public final Registry<ResourceLoader<?>> RESOURCE_LOADERS = new Registry<>(this, ResourceLoader.class);
public final Registry<SoundBuffer> SOUNDS = new Registry<>(this, SoundBuffer.class);
public final Registry<EntityFetcher> ENTITIES = new Registry<>(this, EntityFetcher.class);
public final Registry<ToolLevel> TOOL_MATERIALS = new Registry<>(this, ToolLevel.class);
public final Registry<RegistryLoader> DATA_LOADERS = new Registry<>(this, RegistryLoader.class);
public final Registry<ScreenBuilder> SCREEN_BUILDERS = new Registry<>(this, ScreenBuilder.class);
public void clear() {
BLOCKS.clear();
ITEMS.clear();
TAGS.clear();
RECIPES.clear();
//TODO fix
PROTOCOLS.clear();
EVENT_BUS.postEvent(new RegistryClearEvent(this));
}
public Item getItem(int id) {
if(ITEMS.ELEMENTS.size() > id) {
return ITEMS.get(id);
}
return null;
}
public Item getItem(String name) {
return ITEMS.MAPPED_ELEMENTS.get(name);
}
public Block getBlockWithID(int id) {
return BLOCKS.get(id);
}
public Block getBlock(String id) {
return BLOCKS.MAPPED_ELEMENTS.get(id);
}
public ArrayList<Block> getBlocks() {
return BLOCKS.ELEMENTS;
}
public void registerBlock(Block... blocks) {
for(Block block : blocks) {
BLOCKS.put(block.getName(),block);
}
}
public void registerItem(Item... items) {
for(Item item : items) {
ITEMS.put(item.name,item);
}
}
public void registerBiome(Biome... biomes) {
for(Biome biome : biomes) {
BIOMES.put(biome.name, biome);
}
}
public void registerTag(Tag... tags) {
for(Tag tag : tags) {
TAGS.put(tag.type + ":" + tag.tagName,tag);
}
}
public void registerCommand(CommandHandler... commands) {
for(CommandHandler commandHandler : commands) {
COMMANDS.put(commandHandler.getRegistryName(),commandHandler);
}
}
public void registerSound(SoundBuffer... soundBuffers) {
for(SoundBuffer soundBuffer : soundBuffers) {
SOUNDS.put(soundBuffer.file, soundBuffer);
}
}
public void registerEntity(EntityFetcher entityFetcher) {
//ENTITIES.put(entityFetcher.);
}
public void registerEntities(EntityFetcher... entityFetchers) {
for(EntityFetcher entityFetcher : entityFetchers) {
registerEntity(entityFetcher);
}
}
public void registerToolLevels(ToolLevel... toolLevels) {
for(ToolLevel toolLevel : toolLevels) {
TOOL_MATERIALS.put(toolLevel.name.getName(), toolLevel);
}
}
public void registerRegistryLoader(RegistryLoader... loaders) {
for(RegistryLoader loader : loaders) {
DATA_LOADERS.put(loader.name.getName(),loader);
}
}
public void registerResourceLoader(ResourceLoader<?>... resourceLoaders) {
for(ResourceLoader<?> resourceLoader : resourceLoaders) {
RESOURCE_LOADERS.put(resourceLoader.name,resourceLoader);
}
}
public void registerProtocol(Protocol... protocols) {
for(Protocol protocol : protocols) {
PROTOCOLS.put(protocol.protocolName,protocol);
}
}
public void registerScreenBuilder(ScreenBuilder... screenBuilders) {
for(ScreenBuilder screenBuilder : screenBuilders) {
SCREEN_BUILDERS.put(screenBuilder.getResourceLocation(screenBuilder.modContent).toIdentifier(),screenBuilder);
}
}
public void register(String name, Object o) {
boolean put = false;
for(Registry<?> registry : REGISTRIES.ELEMENTS) {
if(registry.canPut(o)) {
registry.putUnchecked(name,o);
put = true;
}
}
if(!put) {
throw new RuntimeException("failed to put");
}
}
public void register(List<String> names, List<Object> objects) {
for(int x = 0; x < names.size(); x++) {
register(names.get(x), objects.get(x));
}
}
public void register(Collection<String> names, Collection<Object> objects) {
register(names.stream().toList(), objects.stream().toList());
}
public void register(String[] names, Object[] objects) {
for(int x = 0; x < names.length; x++) {
register(names[x], objects[x]);
}
}
public ByteBuffer getResource(ResourceLocation resourceLocation) {
return DATA_LOADER.get(resourceLocation);
}
public ByteBuffer getResourceDirect(ResourceLocation resourceLocation) {
return DATA_LOADER.getDirect(resourceLocation);
}
static short itemId = 0;
public short blockId = 0;
public static short getNextItemId() {
short val = itemId;
itemId++;
return val;
}
public short getNextBlockID() {
short val = blockId;
blockId++;
return val;
}
public void registerDefaultContent() {
Ourcraft.registerDefaultContent(OURCRAFT);
PacketBase.register();
Container.register();
//NBTTag.register();
Widget.register();
Entity.register();
}
public void handleArgs(String[] args) {
ARGUMENTS.handle(args);
}
}
|
3e15e64434b2043dc79c429d64df829bd15d4df6 | 1,135 | java | Java | src/main/java/com/phodu/naav/repository/data/EntityInfoDAO.java | ashishkumarshah/naav | 83f63865250bddede00b921ae023fa984dd3fa88 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/phodu/naav/repository/data/EntityInfoDAO.java | ashishkumarshah/naav | 83f63865250bddede00b921ae023fa984dd3fa88 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/phodu/naav/repository/data/EntityInfoDAO.java | ashishkumarshah/naav | 83f63865250bddede00b921ae023fa984dd3fa88 | [
"Apache-2.0"
] | null | null | null | 24.673913 | 79 | 0.760352 | 9,316 | package com.phodu.naav.repository.data;
import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import com.phodu.naav.core.EntityInfo;
public class EntityInfoDAO {
private EntityManager em = EntityManagerUtil.getEntityManager();
public EntityInfo load(String entityType) {
return em.find(EntityInfo.class, entityType);
}
public void create(EntityInfo entityInfo) {
executeInsideTransaction(entityManager -> entityManager.persist(entityInfo));
}
public EntityInfo update(EntityInfo entity) {
String entityType = entity.getType();
executeInsideTransaction(entityManager -> entityManager.merge(entity));
return load(entityType);
}
public void delete(String entityType) {
EntityInfo entity = load(entityType);
executeInsideTransaction(entityManager -> entityManager.remove(entity));
}
private void executeInsideTransaction(Consumer<EntityManager> action) {
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
action.accept(em);
tx.commit();
} catch (RuntimeException e) {
tx.rollback();
throw e;
}
}
}
|
3e15e6e954a5ef0d620ccb380e52a3b2c4bf80ad | 304 | java | Java | jcart-administration-back/src/main/java/io/sjh/jcartadministrationback/service/AddrsessService.java | SJH2000628/SmallFiveHomework | 0f08c032b51eebc7a98dd886dc99020b2768d523 | [
"Apache-2.0"
] | null | null | null | jcart-administration-back/src/main/java/io/sjh/jcartadministrationback/service/AddrsessService.java | SJH2000628/SmallFiveHomework | 0f08c032b51eebc7a98dd886dc99020b2768d523 | [
"Apache-2.0"
] | null | null | null | jcart-administration-back/src/main/java/io/sjh/jcartadministrationback/service/AddrsessService.java | SJH2000628/SmallFiveHomework | 0f08c032b51eebc7a98dd886dc99020b2768d523 | [
"Apache-2.0"
] | null | null | null | 23.384615 | 57 | 0.809211 | 9,317 | package io.sjh.jcartadministrationback.service;
import io.sjh.jcartadministrationback.po.Address;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface AddrsessService {
Address getById(Integer addressId);
List<Address> selectByCustomerId(Integer customerId);
}
|
3e15e6ec08866b08aedab3b947d74b0e16777230 | 576 | java | Java | src/test/java/com/android/tools/r8/memberrebinding/testclasses/MemberRebindingBridgeRemovalTestClasses.java | ganadist/r8 | 850b5a4725954b677103a3a575239d0f330c0b0f | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2020-05-09T14:41:22.000Z | 2021-02-18T08:47:48.000Z | src/test/java/com/android/tools/r8/memberrebinding/testclasses/MemberRebindingBridgeRemovalTestClasses.java | ganadist/r8 | 850b5a4725954b677103a3a575239d0f330c0b0f | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2020-01-27T22:30:05.000Z | 2020-07-31T20:58:15.000Z | src/test/java/com/android/tools/r8/memberrebinding/testclasses/MemberRebindingBridgeRemovalTestClasses.java | ganadist/r8 | 850b5a4725954b677103a3a575239d0f330c0b0f | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2020-01-27T19:45:35.000Z | 2020-07-06T10:11:59.000Z | 25.043478 | 77 | 0.734375 | 9,318 | // Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.memberrebinding.testclasses;
import com.android.tools.r8.NeverInline;
import com.android.tools.r8.NeverMerge;
public class MemberRebindingBridgeRemovalTestClasses {
@NeverMerge
static class A {
@NeverInline
public void m() {
System.out.println("Hello world!");
}
}
public static class B extends A {}
}
|
3e15e73c817bf62b9c772b67941bab776ebd3713 | 4,091 | java | Java | src/main/java/org/asciidoc/intellij/AsciiDocSpellcheckingStrategy.java | asciidoctor/asciidoctor-intellij-plugin | dfc03e010de78f9810ffa6d5b5d229dfd3e1666f | [
"Apache-2.0"
] | 282 | 2015-01-01T02:13:49.000Z | 2022-03-30T11:09:42.000Z | src/main/java/org/asciidoc/intellij/AsciiDocSpellcheckingStrategy.java | asciidoctor/asciidoctor-intellij-plugin | dfc03e010de78f9810ffa6d5b5d229dfd3e1666f | [
"Apache-2.0"
] | 822 | 2015-01-01T18:10:12.000Z | 2022-03-30T08:07:37.000Z | src/main/java/org/asciidoc/intellij/AsciiDocSpellcheckingStrategy.java | asciidoctor/asciidoctor-intellij-plugin | dfc03e010de78f9810ffa6d5b5d229dfd3e1666f | [
"Apache-2.0"
] | 130 | 2015-01-13T22:48:59.000Z | 2022-03-23T11:48:31.000Z | 36.607143 | 131 | 0.673902 | 9,319 | package org.asciidoc.intellij;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.spellchecker.inspections.PlainTextSplitter;
import com.intellij.spellchecker.tokenizer.SpellcheckingStrategy;
import com.intellij.spellchecker.tokenizer.TokenConsumer;
import com.intellij.spellchecker.tokenizer.Tokenizer;
import org.asciidoc.intellij.grazie.AsciiDocLanguageSupport;
import org.jetbrains.annotations.NotNull;
/**
* For given {@link PsiElement}s, check if they should be spell checked and run a tokenizer.
* This removes for example restricted formatting from the text (like <code>**E**quivalent</code>).
*
* @author yole
* @author Alexander Schwartz (dycjh@example.com)
*/
public class AsciiDocSpellcheckingStrategy extends SpellcheckingStrategy {
private final AsciiDocLanguageSupport languageSupport = new AsciiDocLanguageSupport();
/**
* Return a tokenizer it it is a file's top child, or if is a content root.
* If it is a context root, the tokenizer will analyze if text tokens are separated by non-printable tokens
* and will combine them to words.
*/
@SuppressWarnings("rawtypes")
@NotNull
@Override
public Tokenizer getTokenizer(PsiElement element) {
// run tokenizing on all top level elements in the file and those marked as root elements in the language support.
if (languageSupport.isMyContextRoot(element) || element.getParent() instanceof PsiFile) {
return new Tokenizer<>() {
@Override
public void tokenize(@NotNull PsiElement root, TokenConsumer consumer) {
TokenizingElementVisitor visitor = new TokenizingElementVisitor(root, consumer);
// if an element has children, run the tokenization on the children. Otherwise on the element itself.
if (root.getFirstChild() != null) {
root.acceptChildren(visitor);
} else {
root.accept(visitor);
}
visitor.flush();
}
};
}
return EMPTY_TOKENIZER;
}
/**
* After each word-separating token, flush the text contents to the token consumer.
*/
private class TokenizingElementVisitor extends PsiElementVisitor {
private final PsiElement root;
private final TokenConsumer consumer;
private int offset = 0, length = 0;
private final StringBuilder sb = new StringBuilder();
TokenizingElementVisitor(PsiElement root, TokenConsumer consumer) {
this.root = root;
this.consumer = consumer;
}
@Override
public void visitElement(@NotNull PsiElement child) {
AsciiDocLanguageSupport.Behavior elementBehavior = languageSupport.getElementBehavior(root, child);
switch (elementBehavior) {
case STEALTH:
case UNKNOWN:
case ABSORB:
length += child.getTextLength();
if (sb.length() == 0) {
offset += length;
length = 0;
}
break;
case SEPARATE:
case TEXT:
if (child instanceof PsiWhiteSpace || elementBehavior == AsciiDocLanguageSupport.Behavior.SEPARATE) {
flush();
length += child.getTextLength();
offset += length;
length = 0;
} else if (child.getFirstChild() != null) {
child.acceptChildren(this);
} else {
sb.append(child.getText());
length += child.getTextLength();
}
break;
default:
throw new IllegalStateException("Unexpected value: " + elementBehavior);
}
}
/**
* Flush the text collected so far to the splitter for spell checking.
* Ensure to call this method at the end of the cycle to flush the last bits of the content.
*/
public void flush() {
if (sb.length() > 0) {
consumer.consumeToken(root, sb.toString(), false, offset, TextRange.allOf(sb.toString()), PlainTextSplitter.getInstance());
sb.setLength(0);
}
}
}
}
|
3e15e772e418031d5cb1f80919137eaab63d0985 | 25,004 | java | Java | examples/ADContainerDemo/src/ADContainerDemo.java | DouglasWaterfall/dalsemi | 63c352257ee8ac948c2521d9c298e72b86aa196a | [
"OLDAP-2.2.1"
] | null | null | null | examples/ADContainerDemo/src/ADContainerDemo.java | DouglasWaterfall/dalsemi | 63c352257ee8ac948c2521d9c298e72b86aa196a | [
"OLDAP-2.2.1"
] | null | null | null | examples/ADContainerDemo/src/ADContainerDemo.java | DouglasWaterfall/dalsemi | 63c352257ee8ac948c2521d9c298e72b86aa196a | [
"OLDAP-2.2.1"
] | null | null | null | 35.316384 | 102 | 0.399216 | 9,320 |
/*---------------------------------------------------------------------------
* Copyright (C) 1999,2000 Dallas Semiconductor Corporation, All Rights Reserved.
*
* 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 DALLAS SEMICONDUCTOR 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.
*
* Except as contained in this notice, the name of Dallas Semiconductor
* shall not be used except as stated in the Dallas Semiconductor
* Branding Policy.
*---------------------------------------------------------------------------
*/
import java.io.*;
import java.util.*;
import com.dalsemi.onewire.*;
import com.dalsemi.onewire.adapter.*;
import com.dalsemi.onewire.container.*;
import com.dalsemi.onewire.utils.*;
/** menu driven program to test OneWireContainer with ADContainer interface */
public class ADContainerDemo
{
// user main option menu
static Hashtable hashMainMenu = new Hashtable();
static int mainMenuItemCount;
static DSPortAdapter adapter = null;
static int maxNumChan = 1; // maximum number of channel
static boolean chanSelected = false; // set to true if user has selected channels
static String ADUnit = " V"; // A/D unit
static BufferedReader dis = new BufferedReader(new InputStreamReader(System.in));
/**
* Method main
*
*
* @param args
*
*/
public static void main (String[] args)
{
OneWireContainer owc = null;
ADContainer adc = null;
// find and initialize the first OneWireContainer with
// ADContainer interface
owc = initContainer();
if (!(owc instanceof ADContainer))
{
cleanup();
System.out.println(
"*************************************************************************");
System.out.println("No ADContainer found. Exit program.");
System.out.println();
System.exit(0);
}
else
adc = ( ADContainer ) owc;
maxNumChan = adc.getNumberADChannels();
// array to determine whether a specific channel has been selected
boolean[] channel = new boolean [maxNumChan];
for (int i = 0; i < maxNumChan; i++) // default, no channel selected
channel [i] = false;
byte[] state = null; // data from device
double[] ranges = null; // A/D ranges
double alarmLow = 0; // alarm low value
double alarmHigh = 0; // alarm high value
boolean alarming;
// temporary storage for user input
int inputInt = 0;
double inputDouble = 0.0;
double inputLow = 0.0;
double inputHigh = 0.0;
String inputString = null;
boolean moreInput = true;
int curMenuChoice = 0;
initMenu();
while (true)
{
curMenuChoice = getMenuChoice(hashMainMenu, mainMenuItemCount);
try
{
switch (curMenuChoice)
{
case 0 : // Select Channel
System.out.println(
"*************************************************************************");
System.out.println(
"All previously selectd channels have been cleared.");
state = adc.readDevice();
for (int i = 0; i < maxNumChan; i++)
{
// clear all channel selection
channel [i] = false;
if (adc.hasADAlarms())
{
// disable alarms
adc.setADAlarmEnable(i, ADContainer.ALARM_LOW, false,
state);
adc.setADAlarmEnable(i, ADContainer.ALARM_HIGH,
false, state);
}
}
adc.writeDevice(state);
chanSelected = false;
state = adc.readDevice();
int count = 1;
moreInput = true;
while (moreInput && (count <= maxNumChan))
{
System.out.print("Please enter channel # " + count
+ " ( Enter -1 if no more): ");
inputInt = ( int ) getNumber();
if (inputInt == -1)
{
moreInput = false;
}
else
{
if (isChannelValid(inputInt))
{
channel [inputInt] = true;
count++;
chanSelected = true;
if (adc.hasADAlarms())
{
// enable alarms
adc.setADAlarmEnable(inputInt,
ADContainer.ALARM_LOW,
true, state);
adc.setADAlarmEnable(inputInt,
ADContainer.ALARM_HIGH,
true, state);
}
}
}
} // while (moreInput && (count <= maxNumChan))
adc.writeDevice(state);
System.out.print(" Channels to monitor = ");
if (count == 1)
System.out.println("NONE");
else
{
for (int i = 0; i < maxNumChan; i++)
if (channel [i])
System.out.print(i + " ");
System.out.println();
}
break;
case 1 : // Get A/D Once
getVoltage(adc, channel, 1);
break;
case 2 : // Get A/D Multiple Time
System.out.print("Please enter number of times: ");
inputInt = ( int ) getNumber();
getVoltage(adc, channel, inputInt);
break;
case 3 : // Get A/D ranges
if (!chanSelected)
{
System.out.println(
"No channel selected yet. Cannot get A/D ranges.");
}
else
{
state = adc.readDevice();
for (int i = 0; i < maxNumChan; i++)
{
if (channel [i])
{
ranges = adc.getADRanges(i);
System.out.print("Ch " + i + " - Available: "
+ ranges [0] + ADUnit);
for (int j = 1; j < ranges.length; j++)
System.out.print(", " + ranges [j] + ADUnit);
System.out.println(". Current: "
+ adc.getADRange(i, state)
+ ADUnit);
}
}
}
break;
case 4 : // Set A/D ranges
System.out.println(
"*************************************************************************");
state = adc.readDevice();
moreInput = true;
while (moreInput)
{
System.out.print("Please enter channel number: ");
inputInt = ( int ) getNumber();
if (isChannelValid(inputInt))
{
System.out.print("Please enter range value: ");
inputDouble = getNumber();
adc.setADRange(inputInt, inputDouble, state);
adc.writeDevice(state);
state = adc.readDevice();
System.out.println(" Ch" + inputInt
+ " A/D Ranges set to: "
+ adc.getADRange(inputInt, state));
System.out.print("Set more A/D ranges (Y/N)? ");
inputString = dis.readLine();
if (!inputString.trim().toUpperCase().equals("Y"))
moreInput = false;
}
} // while(moreInput)
break;
case 5 : // Get High and Low Alarms
if (!adc.hasADAlarms())
{
System.out.println("A/D alarms not supported");
}
else if (!chanSelected)
{
System.out.println(
"No channel selected yet. Cannot get high and low alarms.");
}
else
{
state = adc.readDevice();
for (int i = 0; i < maxNumChan; i++)
{
if (channel [i])
{
alarmLow =
adc.getADAlarm(i, ADContainer.ALARM_LOW, state);
alarmHigh =
adc.getADAlarm(i, ADContainer.ALARM_HIGH,
state);
// show results up to 2 decimal places
System.out.println(
"Ch " + i + " Alarm: High = "
+ (( int ) (alarmHigh * 100)) / 100.0 + ADUnit
+ ", Low = "
+ (( int ) (alarmLow * 100)) / 100.0 + ADUnit);
}
} // for
}
break;
case 6 : // Set High and Low Alarms
if (!adc.hasADAlarms())
{
System.out.println("A/D alarms not supported");
}
else
{
System.out.println(
"*************************************************************************");
state = adc.readDevice();
moreInput = true;
while (moreInput)
{
System.out.print("Please enter channel number: ");
inputInt = ( int ) getNumber();
if (isChannelValid(inputInt))
{
boolean inputValid = false;
while (!inputValid)
{
System.out.print(
"Please enter alarm high value: ");
inputHigh = getNumber();
if (inputHigh > adc.getADRange(inputInt, state))
System.out.println(
"Current A/D range is: "
+ adc.getADRange(inputInt, state)
+ ADUnit + ". Invalid alarm high value.");
else
inputValid = true;
}
System.out.print("Please enter alarm low value: ");
inputLow = getNumber();
adc.setADAlarm(inputInt, ADContainer.ALARM_LOW,
inputLow, state);
adc.setADAlarm(inputInt, ADContainer.ALARM_HIGH,
inputHigh, state);
adc.writeDevice(state);
state = adc.readDevice();
// show results up to 2 decimal places
System.out.println(
" Set Ch" + inputInt + " Alarm: High = "
+ (( int ) (adc.getADAlarm(
inputInt, ADContainer.ALARM_HIGH,
state) * 100)) / 100.0 + ADUnit + ", Low = "
+ (( int ) (adc.getADAlarm(
inputInt,
ADContainer.ALARM_LOW,
state) * 100)) / 100.0 + ADUnit);
System.out.print("Set more A/D alarms (Y/N)? ");
inputString = dis.readLine();
if (!inputString.trim().toUpperCase().equals("Y"))
moreInput = false;
}
} // while(moreInput)
}
break;
case 7 : // hasADAlarmed
if (!adc.hasADAlarms())
{
System.out.println("A/D alarms not supported");
}
else
{
alarming = owc.isAlarming();
if (alarming)
{
System.out.print(" Alarms: ");
state = adc.readDevice();
for (int i = 0; i < maxNumChan; i++)
{
if (channel [i])
{
if (adc.hasADAlarmed(i, ADContainer.ALARM_HIGH,
state))
System.out.print("Ch" + i
+ " alarmed high; ");
if (adc.hasADAlarmed(i, ADContainer.ALARM_LOW,
state))
System.out.print("Ch" + i
+ " alarmed low; ");
}
}
System.out.println();
}
else
System.out.println(" Not Alarming");
}
break;
case 8 :
cleanup();
System.exit(0);
break;
}
}
catch (Exception e)
{
printException(e);
}
} // while
}
// find the first OneWireContainer with ADContainer interface
// if found, initialize the container
static OneWireContainer initContainer ()
{
byte[] state = null;
OneWireContainer owc = null;
ADContainer adc = null;
try
{
adapter = OneWireAccessProvider.getDefaultAdapter();
// get exclusive use of adapter
adapter.beginExclusive(true);
adapter.setSearchAllDevices();
adapter.targetAllFamilies();
adapter.setSpeed(adapter.SPEED_REGULAR);
// enumerate through all the One Wire device found
for (Enumeration owc_enum = adapter.getAllDeviceContainers();
owc_enum.hasMoreElements(); )
{
// get the next owc
owc = ( OneWireContainer ) owc_enum.nextElement();
// check for One Wire device that implements ADCotainer interface
if (owc instanceof ADContainer)
{
adc = ( ADContainer ) owc;
// access One Wire device
state = adc.readDevice();
double[] range = null;
double[] resolution = null;
// set resolution
for (int channel = 0; channel < adc.getNumberADChannels();
channel++)
{
range = adc.getADRanges(channel);
resolution = adc.getADResolutions(channel, range [0]);
// set to largest range
adc.setADRange(channel, range [0], state);
// set to highest resolution
adc.setADResolution(channel,
resolution [resolution.length - 1],
state);
if (adc.hasADAlarms())
{
// disable all alarms
adc.setADAlarmEnable(channel, ADContainer.ALARM_LOW,
false, state);
adc.setADAlarmEnable(channel, ADContainer.ALARM_HIGH,
false, state);
}
}
adc.writeDevice(state);
// print device information
System.out.println();
System.out.println(
"*************************************************************************");
System.out.println("* 1-Wire Device Name: " + owc.getName());
System.out.println("* 1-Wire Device Other Names: "
+ owc.getAlternateNames());
System.out.println("* 1-Wire Device Address: "
+ owc.getAddressAsString());
System.out.println(
"* 1-Wire Device Max speed: "
+ ((owc.getMaxSpeed() == DSPortAdapter.SPEED_OVERDRIVE)
? "Overdrive"
: "Normal"));
System.out.println("* 1-Wire Device Number of Channels: "
+ adc.getNumberADChannels());
System.out.println("* 1-Wire Device Can Read MultiChannels: "
+ adc.canADMultiChannelRead());
System.out.println("* 1-Wire Device Description: "
+ owc.getDescription());
System.out.println(
"*************************************************************************");
System.out.println(" Hit ENTER to continue...");
dis.readLine();
break;
}
} // enum all owc
}
catch (Exception e)
{
printException(e);
}
return owc;
}
// read A/D from device
static void getVoltage (ADContainer adc, boolean[] channel, int trial)
throws OneWireException, OneWireIOException
{
byte[] state;
double[] curVoltage = new double [channel.length];
if (!chanSelected)
{
System.out.println(
"No channel selected yet. Cannot get voltage reading.");
return;
}
while (trial-- > 0)
{
state = adc.readDevice();
if (adc.canADMultiChannelRead())
{
// do all channels together
adc.doADConvert(channel, state);
curVoltage = adc.getADVoltage(state);
}
else
{
// do one channel at a time;
for (int i = 0; i < maxNumChan; i++)
{
if (channel [i])
{
adc.doADConvert(i, state);
curVoltage [i] = adc.getADVoltage(i, state);
}
}
}
System.out.print(" Voltage Reading:");
for (int i = 0; i < maxNumChan; i++)
{
if (channel [i]) // show value up to 2 decimal places
System.out.print(" Ch" + i + " = "
+ (( int ) (curVoltage [i] * 10000)) / 10000.0
+ ADUnit);
}
System.out.println();
}
}
/** initialize menu choices */
static void initMenu ()
{
hashMainMenu.put(new Integer(0), "Select Channel");
hashMainMenu.put(new Integer(1), "Get Voltage Once");
hashMainMenu.put(new Integer(2), "Get Voltage Multiple Time");
hashMainMenu.put(new Integer(3), "Get A/D Ranges");
hashMainMenu.put(new Integer(4), "Set A/D Ranges");
hashMainMenu.put(new Integer(5), "Get High and Low A/D Alarms");
hashMainMenu.put(new Integer(6), "Set High and Low A/D Alarms");
hashMainMenu.put(new Integer(7), "hasADAlarmed");
hashMainMenu.put(new Integer(8), "Quit");
mainMenuItemCount = 9;
return;
}
/** getMenuChoice - retrieve menu choice from the user */
static int getMenuChoice (Hashtable menu, int count)
{
int choice = 0;
while (true)
{
System.out.println(
"*************************************************************************");
for (int i = 0; i < count; i++)
System.out.println(i + ". " + menu.get(new Integer(i)));
System.out.print("Please enter your choice: ");
// change input into integer number
choice = ( int ) getNumber();
if (menu.get(new Integer(choice)) == null)
{
System.out.println("Invalid menu choice");
}
else
break;
}
return choice;
}
/** check for valid channel number input */
static boolean isChannelValid (int channel)
{
if ((channel < 0) || (channel >= maxNumChan))
{
System.out.println("Channel number has to be between 0 and "
+ (maxNumChan - 1));
return false;
}
else
return true;
}
/**
* Retrieve user input from the console.
*
* @return numberic value entered from the console.
*
*/
static double getNumber ()
{
double value = -1;
String input;
while (true)
{
try
{
input = dis.readLine();
value = Double.valueOf(input).doubleValue();
break;
}
catch (NumberFormatException e)
{
System.out.println("Invalid Numeric Value: " + e.toString());
System.out.print("Please enter value again: ");
}
catch (java.io.IOException e)
{
System.out.println("Error in reading from console: " + e);
}
catch (Exception e)
{
printException(e);
}
}
return value;
}
/** print out Exception stack trace */
static void printException (Exception e)
{
System.out.println("***** EXCEPTION *****");
e.printStackTrace();
}
/** clean up before exiting program */
static void cleanup ()
{
try
{
if (adapter != null)
{
adapter.endExclusive(); // end exclusive use of adapter
adapter.freePort(); // free port used by adapter
}
}
catch (Exception e)
{
printException(e);
}
return;
}
}
|
3e15e84251d8b6e9c43f70de199640f7bd410018 | 4,394 | java | Java | src/main/java/mekanism/common/inventory/container/ContainerMetallurgicInfuser.java | Mrkwtkr/Mekanism | 372705a44886d0c9a3b00bf8da092866bb719710 | [
"MIT",
"Unlicense"
] | 1 | 2015-06-02T07:32:01.000Z | 2015-06-02T07:32:01.000Z | src/main/java/mekanism/common/inventory/container/ContainerMetallurgicInfuser.java | Mrkwtkr/Mekanism | 372705a44886d0c9a3b00bf8da092866bb719710 | [
"MIT",
"Unlicense"
] | null | null | null | src/main/java/mekanism/common/inventory/container/ContainerMetallurgicInfuser.java | Mrkwtkr/Mekanism | 372705a44886d0c9a3b00bf8da092866bb719710 | [
"MIT",
"Unlicense"
] | null | null | null | 24.685393 | 143 | 0.681611 | 9,321 | package mekanism.common.inventory.container;
import mekanism.api.infuse.InfuseRegistry;
import mekanism.api.infuse.InfusionInput;
import mekanism.common.inventory.slot.SlotEnergy.SlotDischarge;
import mekanism.common.inventory.slot.SlotMachineUpgrade;
import mekanism.common.inventory.slot.SlotOutput;
import mekanism.common.item.ItemMachineUpgrade;
import mekanism.common.recipe.RecipeHandler;
import mekanism.common.recipe.RecipeHandler.Recipe;
import mekanism.common.tile.TileEntityMetallurgicInfuser;
import mekanism.common.util.ChargeUtils;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
public class ContainerMetallurgicInfuser extends Container
{
private TileEntityMetallurgicInfuser tileEntity;
public ContainerMetallurgicInfuser(InventoryPlayer inventory, TileEntityMetallurgicInfuser tentity)
{
tileEntity = tentity;
addSlotToContainer(new SlotMachineUpgrade(tentity, 0, 180, 11));
addSlotToContainer(new Slot(tentity, 1, 17, 35));
addSlotToContainer(new Slot(tentity, 2, 51, 43));
addSlotToContainer(new SlotOutput(tentity, 3, 109, 43));
addSlotToContainer(new SlotDischarge(tentity, 4, 143, 35));
int slotX;
for(slotX = 0; slotX < 3; ++slotX)
{
for(int slotY = 0; slotY < 9; ++slotY)
{
addSlotToContainer(new Slot(inventory, slotY + slotX * 9 + 9, 8 + slotY * 18, 84 + slotX * 18));
}
}
for(slotX = 0; slotX < 9; ++slotX)
{
addSlotToContainer(new Slot(inventory, slotX, 8 + slotX * 18, 142));
}
tileEntity.open(inventory.player);
tileEntity.openInventory();
}
@Override
public void onContainerClosed(EntityPlayer entityplayer)
{
super.onContainerClosed(entityplayer);
tileEntity.close(entityplayer);
tileEntity.closeInventory();
}
@Override
public boolean canInteractWith(EntityPlayer entityplayer)
{
return tileEntity.isUseableByPlayer(entityplayer);
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int slotID)
{
ItemStack stack = null;
Slot currentSlot = (Slot)inventorySlots.get(slotID);
if(currentSlot != null && currentSlot.getHasStack())
{
ItemStack slotStack = currentSlot.getStack();
stack = slotStack.copy();
if(slotID != 0 && slotID != 1 && slotID != 2 && slotID != 3 && slotID != 4)
{
if(InfuseRegistry.getObject(slotStack) != null && (tileEntity.type == null || tileEntity.type == InfuseRegistry.getObject(slotStack).type))
{
if(!mergeItemStack(slotStack, 1, 2, false))
{
return null;
}
}
else if(slotStack.getItem() instanceof ItemMachineUpgrade)
{
if(!mergeItemStack(slotStack, 0, 1, false))
{
return null;
}
}
else if(ChargeUtils.canBeDischarged(slotStack))
{
if(!mergeItemStack(slotStack, 4, 5, false))
{
return null;
}
}
else if(isInputItem(slotStack))
{
if(!mergeItemStack(slotStack, 2, 3, false))
{
return null;
}
}
else {
if(slotID >= 5 && slotID <= 31)
{
if(!mergeItemStack(slotStack, 32, inventorySlots.size(), false))
{
return null;
}
}
else if(slotID > 31)
{
if(!mergeItemStack(slotStack, 5, 31, false))
{
return null;
}
}
else {
if(!mergeItemStack(slotStack, 5, inventorySlots.size(), true))
{
return null;
}
}
}
}
else {
if(!mergeItemStack(slotStack, 5, inventorySlots.size(), true))
{
return null;
}
}
if(slotStack.stackSize == 0)
{
currentSlot.putStack((ItemStack)null);
}
else {
currentSlot.onSlotChanged();
}
if(slotStack.stackSize == stack.stackSize)
{
return null;
}
currentSlot.onPickupFromSlot(player, slotStack);
}
return stack;
}
public boolean isInputItem(ItemStack itemStack)
{
if(tileEntity.type != null)
{
if(RecipeHandler.getMetallurgicInfuserOutput(InfusionInput.getInfusion(tileEntity.type, tileEntity.infuseStored, itemStack), false) != null)
{
return true;
}
}
else {
for(Object obj : Recipe.METALLURGIC_INFUSER.get().keySet())
{
InfusionInput input = (InfusionInput)obj;
if(input.inputStack.isItemEqual(itemStack))
{
return true;
}
}
}
return false;
}
}
|
3e15e862973cb3573b3aa95c6b43a58294920dae | 324 | java | Java | springboot-transaction-aop/src/main/java/com/yan/springboot/tx/MainApplication.java | yankj12/spring-boot-demos | 3c5b61da1daff3325061ed899a6acfffd6e6d476 | [
"MIT"
] | null | null | null | springboot-transaction-aop/src/main/java/com/yan/springboot/tx/MainApplication.java | yankj12/spring-boot-demos | 3c5b61da1daff3325061ed899a6acfffd6e6d476 | [
"MIT"
] | 2 | 2020-12-28T12:20:46.000Z | 2021-01-09T09:13:12.000Z | springboot-transaction-aop/src/main/java/com/yan/springboot/tx/MainApplication.java | yankj12/spring-boot-demos | 3c5b61da1daff3325061ed899a6acfffd6e6d476 | [
"MIT"
] | null | null | null | 24.923077 | 68 | 0.799383 | 9,322 | package com.yan.springboot.tx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
|
3e15e916e113f4a051a690880afcfb967996abae | 1,099 | java | Java | app/src/main/java/org/pocketworkstation/pckeyboard/KeyStrokeData.java | Johnler/keylogger-hackerskeyboard | fad443ff1fab30283fa7f6191ed71dbdeae5d49a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/pocketworkstation/pckeyboard/KeyStrokeData.java | Johnler/keylogger-hackerskeyboard | fad443ff1fab30283fa7f6191ed71dbdeae5d49a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/org/pocketworkstation/pckeyboard/KeyStrokeData.java | Johnler/keylogger-hackerskeyboard | fad443ff1fab30283fa7f6191ed71dbdeae5d49a | [
"Apache-2.0"
] | null | null | null | 29.702703 | 70 | 0.690628 | 9,323 | package org.pocketworkstation.pckeyboard;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.widget.TextView;
import java.util.ArrayList;
public class KeyStrokeData extends Activity {
TextView txtLogs;
DBHelper myDB = new DBHelper(this);
ArrayList<String> dataStroke = new ArrayList<String>();
String[] dataStrok;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.keystroke_data);
String setTime = getIntent().getExtras().getString("getTime");
txtLogs = findViewById(R.id.txtKeylogs);
Cursor data = myDB.getAllDataByTime(setTime);
StringBuffer stringBuffer = new StringBuffer();
if(data!=null && data.getCount()>0){
while (data.moveToNext()){
stringBuffer.append(data.getString(0));
}
}
txtLogs.setText(Html.fromHtml(stringBuffer.toString()));
}
} |
3e15e9f080c69bfe9251353756d5cf7ba5f69d7c | 2,115 | java | Java | src/main/java/com/idealista/configuration/combiner/PropertiesMergerService.java | idealista/property-merger | 5dd06793de865f28261aa4b36408d35b323a3130 | [
"Apache-2.0"
] | 1 | 2020-10-23T12:15:12.000Z | 2020-10-23T12:15:12.000Z | src/main/java/com/idealista/configuration/combiner/PropertiesMergerService.java | idealista/property-merger | 5dd06793de865f28261aa4b36408d35b323a3130 | [
"Apache-2.0"
] | 1 | 2020-10-23T12:25:20.000Z | 2021-01-28T13:43:51.000Z | src/main/java/com/idealista/configuration/combiner/PropertiesMergerService.java | idealista/property-merger | 5dd06793de865f28261aa4b36408d35b323a3130 | [
"Apache-2.0"
] | null | null | null | 49.186047 | 134 | 0.770213 | 9,324 | package com.idealista.configuration.combiner;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
public class PropertiesMergerService {
private ConfigurationMerger configurationMerger;
private PropertiesConfigurationWriter propertiesConfigurationWriter;
private PropertiesConfigurationReader propertiesConfigurationReader;
public PropertiesMergerService(ConfigurationMerger configurationMerger,
PropertiesConfigurationWriter propertiesConfigurationWriter,
PropertiesConfigurationReader propertiesConfigurationReader) {
this.configurationMerger = configurationMerger;
this.propertiesConfigurationReader = propertiesConfigurationReader;
this.propertiesConfigurationWriter = propertiesConfigurationWriter;
}
public void merge(String baseFilePath, String otherFilePath, String mergeResultPath, MergeOptions mergeOptions) {
if(StringUtils.isBlank(baseFilePath)) throw new IllegalArgumentException("base File Path cannot be null or empty");
if(StringUtils.isBlank(otherFilePath)) throw new IllegalArgumentException("other File Path cannot be null or empty");
if(StringUtils.isBlank(mergeResultPath)) throw new IllegalArgumentException("merge result File Path cannot be null or empty");
if(mergeOptions == null) throw new IllegalArgumentException("merge options cannot be null");
PropertiesConfiguration baseConfiguration = read(baseFilePath);
PropertiesConfiguration otherConfiguration = read(otherFilePath);
PropertiesConfiguration mergeResult = configurationMerger.merge(baseConfiguration, otherConfiguration, mergeOptions);
write(mergeResultPath, mergeResult);
}
private void write(String fileName, PropertiesConfiguration configuration) {
propertiesConfigurationWriter.write(fileName, configuration);
}
private PropertiesConfiguration read(String fileName) {
return propertiesConfigurationReader.read(fileName);
}
} |
3e15ea0f35e7e6445c7dcb1c951128fc00014505 | 6,293 | java | Java | src/IU/JDiGeneral.java | CarlosValerio02/PasswordControl | d6ebfef9663f98274219972f1250b2d383be1e35 | [
"MIT"
] | null | null | null | src/IU/JDiGeneral.java | CarlosValerio02/PasswordControl | d6ebfef9663f98274219972f1250b2d383be1e35 | [
"MIT"
] | null | null | null | src/IU/JDiGeneral.java | CarlosValerio02/PasswordControl | d6ebfef9663f98274219972f1250b2d383be1e35 | [
"MIT"
] | null | null | null | 39.578616 | 121 | 0.629588 | 9,325 | package IU;
import Controladores.Registro;
import IU.Paneles.JPaNuevo;
import javax.swing.JFrame;
/**
* @author Carlos Daniel
*/
public class JDiGeneral extends javax.swing.JDialog {
// ========================== Variables =============================
private static JDiGeneral jDiGeneral;
private static boolean esExistente = false;
private static boolean esEdicion = false;
private static String contraseniaEdicion = "";
// ==================================================================
// ========================== Métodos =============================
public static JDiGeneral getJDiGeneral(JFrame parent) {
if (jDiGeneral == null) {
jDiGeneral = new JDiGeneral(parent, true);
}
JPaNuevo panelContenido = JPaNuevo.getJPaNuevo(jDiGeneral);
if (!esEdicion) {
JPaNuevo.setEsEdicion(false);
panelContenido.getTxtContrasenia().setText(Registro.generarContrasenia());
contraseniaEdicion = "";
} else {
JPaNuevo.setEsEdicion(true);
panelContenido.getTxtContrasenia().setText(contraseniaEdicion);
panelContenido.getTxtContrasenia().setEditable(true);
}
Globales.Metodos.agregarPanel(jPaContenedor, panelContenido);
return jDiGeneral;
}
private JDiGeneral(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
this.setLocationRelativeTo(null);
this.setTitle("Nueva Contraseña - " + Globales.Variables.getTITULO());
this.setIconImage(Globales.Variables.getICONO());
this.setResizable(false);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPaContenedor = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(370, 400));
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
javax.swing.GroupLayout jPaContenedorLayout = new javax.swing.GroupLayout(jPaContenedor);
jPaContenedor.setLayout(jPaContenedorLayout);
jPaContenedorLayout.setHorizontalGroup(
jPaContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 365, Short.MAX_VALUE)
);
jPaContenedorLayout.setVerticalGroup(
jPaContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
getContentPane().add(jPaContenedor, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
JPaNuevo panelContenido = JPaNuevo.getJPaNuevo(jDiGeneral);
panelContenido.getTxtSitioWeb().setText("");
panelContenido.getTxtUsuario().setText("");
panelContenido.getCbxExistente().setSelected(false);
panelContenido.getTxtContrasenia().setText("");
panelContenido.getJlbError().setText("");
}//GEN-LAST:event_formWindowClosing
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(JDiGeneral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JDiGeneral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JDiGeneral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JDiGeneral.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the dialog */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JDiGeneral dialog = new JDiGeneral(new javax.swing.JFrame(), true);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
//<--- Getters && Setters --->
public static boolean isEsExistente() {
return esExistente;
}
public static boolean isEsEdicion() {
return esEdicion;
}
public static void setEsExistente(boolean esExistente) {
JDiGeneral.esExistente = esExistente;
}
public static void setEsEdicion(boolean esEdicion) {
JDiGeneral.esEdicion = esEdicion;
}
public static String getContraseniaEdicion() {
return contraseniaEdicion;
}
public static void setContraseniaEdicion(String contraseniaEdicion) {
JDiGeneral.contraseniaEdicion = contraseniaEdicion;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private static javax.swing.JPanel jPaContenedor;
// End of variables declaration//GEN-END:variables
}
|
3e15ea76b86415d40220a4aa647f7da41e2f58e5 | 145 | java | Java | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_452.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | 1 | 2016-01-18T17:57:21.000Z | 2016-01-18T17:57:21.000Z | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_452.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | null | null | null | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/Class_452.java | lesaint/experimenting-annotation-processing | 1e9692ceb0d3d2cda709e06ccc13290262f51b39 | [
"Apache-2.0"
] | null | null | null | 18.125 | 51 | 0.827586 | 9,326 | package fr.javatronic.blog.massive.annotation1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_452 {
}
|
3e15eba03458bc7bb428d0863fbdc48f0bf6a47f | 574 | java | Java | study/src/main/java/com/myzuji/study/java/thread/syn/Synch.java | mestarshine/myzuji | a7ccca932f4b9794adbb6b345eb19ce04f319890 | [
"MIT"
] | null | null | null | study/src/main/java/com/myzuji/study/java/thread/syn/Synch.java | mestarshine/myzuji | a7ccca932f4b9794adbb6b345eb19ce04f319890 | [
"MIT"
] | null | null | null | study/src/main/java/com/myzuji/study/java/thread/syn/Synch.java | mestarshine/myzuji | a7ccca932f4b9794adbb6b345eb19ce04f319890 | [
"MIT"
] | null | null | null | 22.076923 | 56 | 0.547038 | 9,327 | package com.myzuji.study.java.thread.syn;
/**
* 说明
*
* @author shine
* @date 2020/02/01
*/
public class Synch {
public static void main(String[] args) {
CallMe target = new CallMe();
Caller ob1 = new Caller("Hello", target);
Caller ob2 = new Caller("Synchronized", target);
Caller ob3 = new Caller("Word", target);
try {
ob1.thread.join();
ob2.thread.join();
ob3.thread.join();
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
|
3e15ed92a014e04c57af86ed4e895da6c2db5bce | 845 | java | Java | app/src/main/java/me/vebbo/android/utils/CommaCounter.java | Dev-Geek/Video-Live-Streaming-Platform-Android | f89478afc6178962ed0c7301ecd4fde2093ee654 | [
"MIT"
] | 1 | 2021-10-16T02:20:48.000Z | 2021-10-16T02:20:48.000Z | app/src/main/java/me/vebbo/android/utils/CommaCounter.java | Dev-Geek/Video-Live-Streaming-Platform-Android | f89478afc6178962ed0c7301ecd4fde2093ee654 | [
"MIT"
] | null | null | null | app/src/main/java/me/vebbo/android/utils/CommaCounter.java | Dev-Geek/Video-Live-Streaming-Platform-Android | f89478afc6178962ed0c7301ecd4fde2093ee654 | [
"MIT"
] | null | null | null | 29.137931 | 83 | 0.559763 | 9,328 | package me.vebbo.android.utils;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
public class CommaCounter {
public String getFormattedValue(int num){
DecimalFormat formatter = new DecimalFormat("#,###,###,###,###,###");
return formatter.format(num);
}
//===================================================
public String getFormattedAmount(int amount){
return NumberFormat.getNumberInstance(Locale.US).format(amount);
}
//===================================================
public String getFormattedNumber(String number){
if(!number.isEmpty()) {
double val = Double.parseDouble(number);
return NumberFormat.getNumberInstance(Locale.getDefault()).format(val);
}else{
return "0";
}
}
}
|
3e15edbf0090d2c4616873887e472f083dc6b520 | 211 | java | Java | core/bootstrap/src/main/java/org/qi4j/bootstrap/ObjectAssembly.java | arvidhuss/qi4j-sdk | b49eca6201e702ebcdae810c45fe0bcba3a74773 | [
"Apache-2.0"
] | 1 | 2017-08-08T03:09:29.000Z | 2017-08-08T03:09:29.000Z | core/bootstrap/src/main/java/org/qi4j/bootstrap/ObjectAssembly.java | bwzhang2011/qi4j-sdk | be5f91e61a3b02e21f8f236fbaf85747f7f993ae | [
"Apache-2.0"
] | null | null | null | core/bootstrap/src/main/java/org/qi4j/bootstrap/ObjectAssembly.java | bwzhang2011/qi4j-sdk | be5f91e61a3b02e21f8f236fbaf85747f7f993ae | [
"Apache-2.0"
] | 1 | 2022-01-22T10:59:44.000Z | 2022-01-22T10:59:44.000Z | 17.583333 | 80 | 0.753555 | 9,329 | package org.qi4j.bootstrap;
import org.qi4j.api.type.HasTypes;
/**
* This represents the assembly information of a single object type in a Module.
*/
public interface ObjectAssembly
extends HasTypes
{
}
|
3e15ede19aa4f04c0103fe34aba4b8d01b9a9888 | 559 | java | Java | platform-shop/src/main/java/com/platform/dao/OrderDao.java | SJshenjian/platform | c5c0f72179dc7cadc569bff3e37027c91fc3c975 | [
"Apache-2.0"
] | 1 | 2019-03-04T00:13:39.000Z | 2019-03-04T00:13:39.000Z | platform-shop/src/main/java/com/platform/dao/OrderDao.java | SJshenjian/platform | c5c0f72179dc7cadc569bff3e37027c91fc3c975 | [
"Apache-2.0"
] | null | null | null | platform-shop/src/main/java/com/platform/dao/OrderDao.java | SJshenjian/platform | c5c0f72179dc7cadc569bff3e37027c91fc3c975 | [
"Apache-2.0"
] | null | null | null | 24.521739 | 94 | 0.735816 | 9,330 | package com.platform.dao;
import com.platform.entity.OrderEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* @author Jian Shen
* @email ychag@example.com
* @date 2017-08-13 10:41:09
*/
public interface OrderDao extends BaseDao<OrderEntity> {
// 查询网点的出库清单
List<OrderEntity> listOrder(@Param("address") String address, @Param("date") String date);
int batchSendGoods(@Param("date") String date);
int batchConfirm(@Param("date") String date);
}
|
3e15ee361ea62645a1378afa8c45b4d1cdec2991 | 5,225 | java | Java | notice/src/main/java/campuslifecenter/notice/model/AccountNoticeInfo.java | Yang-xingchen/campus-life-center | e9ef049a7c5c84c9d55733690ae485d50fae1923 | [
"Apache-2.0"
] | null | null | null | notice/src/main/java/campuslifecenter/notice/model/AccountNoticeInfo.java | Yang-xingchen/campus-life-center | e9ef049a7c5c84c9d55733690ae485d50fae1923 | [
"Apache-2.0"
] | null | null | null | notice/src/main/java/campuslifecenter/notice/model/AccountNoticeInfo.java | Yang-xingchen/campus-life-center | e9ef049a7c5c84c9d55733690ae485d50fae1923 | [
"Apache-2.0"
] | null | null | null | 34.150327 | 129 | 0.670622 | 9,331 | package campuslifecenter.notice.model;
import campuslifecenter.notice.entry.*;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.scheduling.annotation.Async;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class AccountNoticeInfo extends NoticeInfo {
@ApiModelProperty("账户id")
private String aid;
@ApiModelProperty("是否已读")
private Boolean looked;
@ApiModelProperty("是否置顶")
private Boolean top;
@ApiModelProperty("是否删除")
private Boolean del;
@ApiModelProperty("相对重要度")
private Integer relativeImportance;
public static class Info extends NoticeInfoKey {
private String name;
public String getName() {
return name;
}
public Info setName(String name) {
this.name = name;
return this;
}
}
public static AccountNoticeInfo createByNotice(Notice notice) {
Objects.requireNonNull(notice, "notice not find");
AccountNoticeInfo info = new AccountNoticeInfo();
info.setNotice(notice);
return info;
}
public static AccountNoticeInfo createByAccountNotice(AccountNotice notice) {
Objects.requireNonNull(notice, "account notice not find");
return new AccountNoticeInfo()
.setAccountOperation(notice);
}
public void merge(AccountNoticeInfo other) {
if (other == null) {
return;
}
// notice
setId(Optional.ofNullable(other.getId()).orElse(getId()));
setCreator(Optional.ofNullable(other.getCreator()).orElse(getCreator()));
setOrganization(Optional.ofNullable(other.getOrganization()).orElse(getOrganization()));
setVisibility(Optional.ofNullable(other.getVisibility()).orElse(getVisibility()));
setImportance(Optional.ofNullable(other.getImportance()).orElse(getImportance()));
setPublicType(Optional.ofNullable(other.getPublicType()).orElse(getPublicType()));
setVersion(Optional.ofNullable(other.getVersion()).orElse(getVersion()));
setTitle(Optional.ofNullable(other.getTitle()).orElse(getTitle()));
setContentType(Optional.ofNullable(other.getContentType()).orElse(getContentType()));
setCreateTime(Optional.ofNullable(other.getCreateTime()).orElse(getCreateTime()));
setStartTime(Optional.ofNullable(other.getStartTime()).orElse(getStartTime()));
setEndTime(Optional.ofNullable(other.getEndTime()).orElse(getEndTime()));
setRef(Optional.ofNullable(other.getRef()).orElse(getRef()));
setContent(Optional.ofNullable(other.getContent()).orElse(getContent()));
// account
setAid(Optional.ofNullable(other.getAid()).orElse(getAid()));
setLooked(Optional.ofNullable(other.getLooked()).orElse(getLooked()));
setTop(Optional.ofNullable(other.getTop()).orElse(getTop()));
setDel(Optional.ofNullable(other.getDel()).orElse(getDel()));
// other
setOrganizationName(Optional.ofNullable(other.getOrganizationName()).orElse(getOrganizationName()));
setCreatorName(Optional.ofNullable(other.getCreatorName()).orElse(getCreatorName()));
setRelativeImportance(Optional.ofNullable(other.getRelativeImportance()).orElse(getRelativeImportance()));
setTag(Stream.concat(getTag().stream(), other.getTag().stream()).distinct().collect(Collectors.toList()));
setTodoList(Stream.concat(getTodoList().stream(), other.getTodoList().stream()).distinct().collect(Collectors.toList()));
}
public AccountNoticeInfo setAccountOperation(AccountNotice accountOperation) {
if (accountOperation == null) {
return this;
}
if (getImportance() == null) {
setImportance(accountOperation.getNoticeImportance());
}
if (getOrganization() == null) {
setOrganization(accountOperation.getOrganization());
}
setAid(accountOperation.getAid());
setId(accountOperation.getNid());
setLooked(accountOperation.getLooked());
setTop(accountOperation.getTop());
setDel(accountOperation.getDel());
setRelativeImportance(accountOperation.getRelativeImportance());
return this;
}
public String getAid() {
return aid;
}
public AccountNoticeInfo setAid(String aid) {
this.aid = aid;
return this;
}
public Boolean getLooked() {
return looked;
}
public AccountNoticeInfo setLooked(Boolean read) {
looked = read;
return this;
}
public Boolean getTop() {
return top;
}
public AccountNoticeInfo setTop(Boolean top) {
this.top = top;
return this;
}
public Boolean getDel() {
return del;
}
public AccountNoticeInfo setDel(Boolean delete) {
del = delete;
return this;
}
public Integer getRelativeImportance() {
return relativeImportance;
}
public AccountNoticeInfo setRelativeImportance(Integer relativeImportance) {
this.relativeImportance = relativeImportance;
return this;
}
}
|
3e15f004940d9ae52ca7af30c5ff743114643bb7 | 5,585 | java | Java | mblog-base/src/main/java/mblog/base/lang/Common.java | wpeiguang/myblog | 510b7de78b53aed6b58323c1f7e8a7b37dd6139d | [
"Apache-2.0"
] | null | null | null | mblog-base/src/main/java/mblog/base/lang/Common.java | wpeiguang/myblog | 510b7de78b53aed6b58323c1f7e8a7b37dd6139d | [
"Apache-2.0"
] | null | null | null | mblog-base/src/main/java/mblog/base/lang/Common.java | wpeiguang/myblog | 510b7de78b53aed6b58323c1f7e8a7b37dd6139d | [
"Apache-2.0"
] | null | null | null | 83.358209 | 273 | 0.676455 | 9,332 | package mblog.base.lang;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Common {
public static Map<String, Timer> taskList = new HashMap<>();
public static Map<String, Thread> threadList = new HashMap<>();
public static String GENERALIZE_THREAD = "GENERALIZE_THREAD_";
public static Map<String, String> schools = new HashMap<>();
public static ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
public static final String[] userAgents = new String[]{"Mozilla/5.0 (Linux; Android 5.1.1; SM-G9350 Build/LMY48Z) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/39.0.0.0 Safari/537.36",
"Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
"JUC (Linux; U; 2.3.7; zh-cn; MB200; 320*480) UCWEB7.9.3.103/139/999",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0a1) Gecko/20110623 Firefox/7.0a1 Fennec/7.0a1",
"Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
"Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
"Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/1A542a Safari/419.3",
"Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7",
"Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10",
"Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
"Mozilla/5.0 (iPhone;U;CPUiPhoneOS4_3_3likeMacOSX;en-us)AppleWebKit/533.17.9(KHTML,likeGecko)Version/5.0.2Mobile/8J2Safari/6533.18.5",
"Mozilla/5.0 (iPad;U;CPUOS4_3_3likeMacOSX;en-us)AppleWebKit/533.17.9(KHTML,likeGecko)Version/5.0.2Mobile/8J2Safari/6533.18.5",
"Mozilla/5.0 (Linux;U;Android2.3.7;en-us;NexusOneBuild/FRF91)AppleWebKit/533.1(KHTML,likeGecko)Version/4.0MobileSafari/533.1",
"Mozilla/5.0 (iPhone 8; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Version/10.0 MQQBrowser/7.8.0 Mobile/14G60 Safari/8536.25 MttCustomUA/2 QBWebViewType/1 WKType/1",
"Mozilla/5.0 (Linux; Android 7.0; STF-AL10 Build/HUAWEISTF-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043508 Safari/537.36 V1_AND_SQ_7.2.0_730_YYB_D QQ/7.2.0.3270 NetType/4G WebP/0.3.0 Pixel/1080",
"Mozilla/5.0 (Linux; Android 5.1.1; vivo Xplay5A Build/LMY47V; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/48.0.2564.116 Mobile Safari/537.36 T7/9.3 baiduboxapp/9.3.0.10 (Baidu; P1 5.1.1)",
"Mozilla/5.0 (Linux; U; Android 7.0; zh-cn; STF-AL00 Build/HUAWEISTF-AL00) AppleWebKit/537.36 (KHTML, like Gecko)Version/4.0 Chrome/37.0.0.0 MQQBrowser/7.9 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 6.0; LEX626 Build/HEXCNFN5902606111S) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/35.0.1916.138 Mobile Safari/537.36 T7/7.4 baiduboxapp/8.3.1 (Baidu; P1 6.0)",
"Mozilla/5.0 (Linux; U; Android 7.0; zh-CN; ZUK Z2121 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.6.8.952 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; U; Android 6.0.1; zh-CN; SM-C7000 Build/MMB29M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.6.2.948 Mobile Safari/537.36",
"MQQBrowser/5.3/Mozilla/5.0 (Linux; Android 6.0; TCL 580 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.98 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; U; Android 5.1.1; zh-cn; MI 4S Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.146 Mobile Safari/537.36 XiaoMi/MiuiBrowser/9.1.3",
"Mozilla/5.0 (Linux; U; Android 7.0; zh-CN; SM-G9550 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.7.0.953 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 5.1; m3 note Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/48.0.2564.116 Mobile Safari/537.36 T7/9.3 baiduboxapp/9.3.0.10 (Baidu; P1 5.1)"};
public static String getCookie(String url) {
String cookie = "";
try {
Connection conn = Jsoup.connect(url);
conn.method(Connection.Method.GET);
conn.followRedirects(false);
Connection.Response response;
response = conn.execute();
Map<String, String> getCookies = response.cookies();
cookie = getCookies.toString();
cookie = cookie.substring(cookie.indexOf("{") + 1, cookie.lastIndexOf("}"));
cookie = cookie.replaceAll(",", ";");
} catch (Exception e) {
e.printStackTrace();
}
return cookie;
}
}
|
3e15f01a6a393e3e33ad051e9baaa3988ae0936c | 3,620 | java | Java | platform/web-security/src/main/java/org/motechproject/security/repository/AllPasswordRecoveries.java | 1navinkumar/motech | abbc38c96ba6e402fd4690ac5b6341d5ae37833e | [
"BSD-3-Clause"
] | 1 | 2020-10-22T07:36:05.000Z | 2020-10-22T07:36:05.000Z | platform/web-security/src/main/java/org/motechproject/security/repository/AllPasswordRecoveries.java | 1navinkumar/motech | abbc38c96ba6e402fd4690ac5b6341d5ae37833e | [
"BSD-3-Clause"
] | null | null | null | platform/web-security/src/main/java/org/motechproject/security/repository/AllPasswordRecoveries.java | 1navinkumar/motech | abbc38c96ba6e402fd4690ac5b6341d5ae37833e | [
"BSD-3-Clause"
] | null | null | null | 29.430894 | 129 | 0.679834 | 9,333 | package org.motechproject.security.repository;
import org.joda.time.DateTime;
import org.motechproject.commons.api.Range;
import org.motechproject.commons.date.util.DateUtil;
import org.motechproject.security.domain.PasswordRecovery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Locale;
/**
* Implementation of DAO interface that utilizes a MDS back-end for storage.
* Class responsible for handling PasswordRecoveries.
*/
@Repository
public class AllPasswordRecoveries {
private PasswordRecoveriesDataService dataService;
/**
* Returns all expired PasswordRecoveries
*
* @return list that contains recoveries
*/
public List<PasswordRecovery> getExpired() {
Range<DateTime> range = new Range<>(new DateTime(0), DateUtil.now());
return dataService.findByExpirationDate(range);
}
/**
* Returns all PasswordRecoveries
*
* @return list that contains recoveries
*/
public List<PasswordRecovery> allRecoveries() {
return dataService.retrieveAll();
}
/**
* Gets PasswordRecovery for user with given name
*
* @param username name of user
* @return recovery for given name or null in case when username is a null
*/
public PasswordRecovery findForUser(String username) {
return null == username ? null : dataService.findForUser(username);
}
/**
* Gets PasswordRecovery for given token
*
* @param token for recovery
* @return recovery for given token or null in case when token is a null
*/
public PasswordRecovery findForToken(String token) {
return null == token ? null : dataService.findForToken(token);
}
/**
* Creates PasswordRecovery for given informations and return it
*
* @param username for recovery
* @param email for recovery
* @param token for recovery
* @param expirationDate for recovery
* @param locale for recovery
* @return recovery with given informations
*/
public PasswordRecovery createRecovery(String username, String email, String token, DateTime expirationDate, Locale locale) {
PasswordRecovery oldRecovery = findForUser(username);
if (oldRecovery != null) {
remove(oldRecovery);
}
PasswordRecovery recovery = new PasswordRecovery();
recovery.setUsername(username);
recovery.setEmail(email);
recovery.setToken(token);
recovery.setExpirationDate(expirationDate);
recovery.setLocale(locale);
add(recovery);
return recovery;
}
/**
* Updates given PasswordRecovery
*
* @param passwordRecovery to be updated
*/
public void update(PasswordRecovery passwordRecovery) {
dataService.update(passwordRecovery);
}
/**
* Adds given PasswordRecovery provided tha one doesn't exist yet for the user
*
* @param passwordRecovery to be added
*/
public void add(PasswordRecovery passwordRecovery) {
if (findForUser(passwordRecovery.getUsername()) == null) {
dataService.create(passwordRecovery);
}
}
/**
* Deletes given PasswordRecovery
*
* @param passwordRecovery to be removed
*/
public void remove(PasswordRecovery passwordRecovery) {
dataService.delete(passwordRecovery);
}
@Autowired
public void setDataService(PasswordRecoveriesDataService dataService) {
this.dataService = dataService;
}
}
|
3e15f2369d4075f59b41c2fe3fde93dce10b38d0 | 3,633 | java | Java | backend/src/main/java/com/example/password_manager/controller/UserController.java | shameme97/Password-Manager | f99e5b3410b87f2aab10010567b39e2e7e02f28e | [
"Apache-2.0"
] | null | null | null | backend/src/main/java/com/example/password_manager/controller/UserController.java | shameme97/Password-Manager | f99e5b3410b87f2aab10010567b39e2e7e02f28e | [
"Apache-2.0"
] | null | null | null | backend/src/main/java/com/example/password_manager/controller/UserController.java | shameme97/Password-Manager | f99e5b3410b87f2aab10010567b39e2e7e02f28e | [
"Apache-2.0"
] | null | null | null | 44.851852 | 95 | 0.612717 | 9,334 | package com.example.password_manager.controller;
import com.example.password_manager.model.User;
import com.example.password_manager.model.WebCredentials;
import com.example.password_manager.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@AllArgsConstructor
public class UserController {
@Autowired
public UserService userService;
@GetMapping(value = "/all/{username}/{password}/{email}")
public List<WebCredentials> getAllWebCredentials(@PathVariable("username") String username,
@PathVariable("password") String password,
@PathVariable("email") String email){
User user = new User(username,password,email);
return userService.getAllWebCredentials(user);
}
@PostMapping(value = "/add/{username}/{password}/{email}")
public String addWebCredentials(@PathVariable("username") String username,
@PathVariable("password") String password,
@PathVariable("password") String email,
@RequestBody WebCredentials webCredential){
User user = new User(username,password,email);
return userService.addWebCredentials(user, webCredential);
}
@DeleteMapping(value = "/delete/{username}/{password}/{email}")
public String deleteWebCredentials(@PathVariable("username") String username,
@PathVariable("password") String password,
@PathVariable("password") String email,
@RequestBody WebCredentials webCredential){
User user = new User(username,password,email);
return userService.deleteWebCredentials(user, webCredential);
}
@PutMapping(value = "/update/{username}/{password}/{email}")
public String updateWebCredentials(@PathVariable("username") String username,
@PathVariable("password") String password,
@PathVariable("password") String email,
@RequestBody WebCredentials webCredential){
User user = new User(username,password,email);
return userService.updateWebCredentials(user, webCredential);
}
@PostMapping(value = "/register")
public String registerUser(@RequestBody User user){
return userService.registerUser(user);
}
@PostMapping(value = "/login")
public Boolean userLogin(@RequestBody User user){
Boolean login = userService.loginAuthentication(user);
// log.info("Login status - {}", login);
// return ((login) ? "Login Successful" : "User not found") ;
return login;
}
@GetMapping(value = "/search/{username}/{password}/{email}/{string}")
public List<WebCredentials> searchWebCredentials(@PathVariable("username") String username,
@PathVariable("password") String password,
@PathVariable("email") String email,
@PathVariable("string") String string){
User user = new User(username,password,email);
return userService.searchWebCredentials(user, string);
}
}
|
3e15f26c3ccd603b95c1c792d256fb1f583ee47e | 6,430 | java | Java | app/src/androidTest/java/info/romanelli/udacity/capstone/reddit/data/db/NewPostEntityITest.java | aromanelli/Capstone-Project | 40d82fe173dd929bee9dc306b629b64d55ff658a | [
"Apache-2.0"
] | null | null | null | app/src/androidTest/java/info/romanelli/udacity/capstone/reddit/data/db/NewPostEntityITest.java | aromanelli/Capstone-Project | 40d82fe173dd929bee9dc306b629b64d55ff658a | [
"Apache-2.0"
] | null | null | null | app/src/androidTest/java/info/romanelli/udacity/capstone/reddit/data/db/NewPostEntityITest.java | aromanelli/Capstone-Project | 40d82fe173dd929bee9dc306b629b64d55ff658a | [
"Apache-2.0"
] | null | null | null | 40.696203 | 109 | 0.584759 | 9,335 | package info.romanelli.udacity.capstone.reddit.data.db;
import android.content.Context;
import android.util.Log;
import androidx.arch.core.executor.testing.InstantTaskExecutorRule;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import info.romanelli.udacity.capstone.reddit.data.DataRepository;
import info.romanelli.udacity.capstone.util.AppExecutors;
import info.romanelli.udacity.capstone.util.FirebaseAnalyticsManager;
import static org.junit.Assert.assertEquals;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class NewPostEntityITest {
private static final String TAG = NewPostEntityITest.class.getSimpleName();
@Rule // https://stackoverflow.com/questions/52274924/cannot-invoke-observeforever-on-a-background-thread
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();
@Test
public void testNewPosts() throws InterruptedException {
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("info.romanelli.udacity.capstone", appContext.getPackageName());
FirebaseAnalyticsManager.$(appContext);
final AtomicBoolean flag = new AtomicBoolean(false);
try {
// Initial cleanup ...
Thread.sleep(5000); // Hacky, but works ok for testing purposes only
DataRepository.$(appContext).clearDatabase();
final LiveData<List<NewPostEntity>> newPosts1 = DataRepository.$(appContext).getNewPosts();
final Observer<List<NewPostEntity>> obs1 = newPostEntities -> {
Log.d(TAG, "testNewPosts: delete");
Assert.assertNotNull(newPostEntities);
Assert.assertEquals(0, newPostEntities.size());
flag.set(true);
};
try {
newPosts1.observeForever(obs1);
int waitCounter = 0;
while (!flag.get()) {
Thread.sleep(250);
waitCounter++;
if (waitCounter % 4 == 0) {
Log.d(TAG, "delete check: Waiting for completion ... [" + (waitCounter / 4) + "]");
}
if (waitCounter > 120) { // 250 * 120 = 30,000ms == 30 seconds
Assert.fail("Interrupted while waiting for response back!");
break;
}
}
} finally {
AppExecutors.$().mainUI().execute(() -> newPosts1.removeObserver(obs1));
}
///////////////////////////////////////////////////////////////////////////
NewPostEntity entity1 = new NewPostEntity();
Assert.assertNotNull(entity1.getId());
entity1.setId("9sizd6");
entity1.setAuthor("DrunkShroom");
entity1.setCreated(1540888306L);
entity1.setSubreddit("gaming");
entity1.setSubreddit_pre("r/gaming");
entity1.setSubreddit_icon("https://b.thumbs.redditm…z1F1GrrJLCL8oi2Gz0Ak.png");
entity1.setTitle("Nintendo switch turbo controller?");
entity1.setText("Anyone know a decent 3rd… rather than holding it");
entity1.setUrl("https://www.reddit.com/r…switch_turbo_controller/");
DataRepository.$(appContext).addNewPost(entity1);
final int[] retryCounter = {0};
flag.set(false);
final LiveData<List<NewPostEntity>> newPosts2 = DataRepository.$(appContext).getNewPosts();
final Observer<List<NewPostEntity>> obs2 = newPostEntities -> {
Log.d(TAG, "testNewPosts: insert");
Assert.assertNotNull(newPostEntities);
// Gets called twice, first with 0 size, second with non-zero size
if (newPostEntities.size() == 0 && retryCounter[0] == 0) {
Log.d(TAG, "testNewPosts: insert - zero pass thru");
retryCounter[0] += 1;
return;
}
Assert.assertEquals(1, newPostEntities.size());
NewPostEntity entity2 = newPostEntities.get(0);
Assert.assertNotNull(entity2);
Assert.assertEquals(entity1, entity2); // Testing equals() method in NewPostEntity
Assert.assertEquals(entity1.getId(), entity2.getId());
Assert.assertEquals(entity1.getAuthor(), entity2.getAuthor());
Assert.assertEquals(entity1.getCreated(), entity2.getCreated());
Assert.assertEquals(entity1.getSubreddit(), entity2.getSubreddit());
Assert.assertEquals(entity1.getSubreddit_pre(), entity2.getSubreddit_pre());
Assert.assertEquals(entity1.getSubreddit_icon(), entity2.getSubreddit_icon());
Assert.assertEquals(entity1.getTitle(), entity2.getTitle());
Assert.assertEquals(entity1.getText(), entity2.getText());
Assert.assertEquals(entity1.getUrl(), entity2.getUrl());
flag.set(true);
};
try {
newPosts2.observeForever(obs2);
int waitCounter = 0;
while (!flag.get()) {
Thread.sleep(250);
waitCounter++;
if (waitCounter % 4 == 0) {
Log.d(TAG, "add check: Waiting for completion ... [" + (waitCounter / 4) + "]");
}
if (waitCounter > 120) { // 250 * 120 = 30,000ms == 30 seconds
Assert.fail("Interrupted while waiting for response back!");
break;
}
}
} finally {
AppExecutors.$().mainUI().execute(() -> newPosts2.removeObserver(obs2));
}
} finally {
// Post testing cleanup ...
DataRepository.$(appContext).clearDatabase();
}
}
}
|
3e15f26fc6b9c9440cb3d9f2962d9024f550bfc4 | 9,487 | java | Java | netreflected/microsoft_entityframeworkcore_6_0_2_0/src/net6.0/microsoft.entityframeworkcore_version_6.0.0.0_culture_neutral_publickeytoken_adb9793829ddae60/microsoft/entityframeworkcore/storage/TypeMappingSource.java | masesdevelopers/NuReflector | bf25df84c211e66821a503d4588ab22c99e26c7f | [
"MIT"
] | null | null | null | netreflected/microsoft_entityframeworkcore_6_0_2_0/src/net6.0/microsoft.entityframeworkcore_version_6.0.0.0_culture_neutral_publickeytoken_adb9793829ddae60/microsoft/entityframeworkcore/storage/TypeMappingSource.java | masesdevelopers/NuReflector | bf25df84c211e66821a503d4588ab22c99e26c7f | [
"MIT"
] | 7 | 2021-11-14T02:18:03.000Z | 2022-03-30T17:38:29.000Z | netreflected/microsoft_entityframeworkcore_6_0_2_0/src/net6.0/microsoft.entityframeworkcore_version_6.0.0.0_culture_neutral_publickeytoken_adb9793829ddae60/microsoft/entityframeworkcore/storage/TypeMappingSource.java | masesdevelopers/NuReflector | bf25df84c211e66821a503d4588ab22c99e26c7f | [
"MIT"
] | 1 | 2021-11-16T00:08:00.000Z | 2021-11-16T00:08:00.000Z | 45.610577 | 422 | 0.704227 | 9,336 | /*
* MIT License
*
* Copyright (c) 2022 MASES s.r.l.
*
* 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.
*/
/**************************************************************************************
* <auto-generated>
* This code was generated from a template using JCOReflector
*
* Manual changes to this file may cause unexpected behavior in your application.
* Manual changes to this file will be overwritten if the code is regenerated.
* </auto-generated>
*************************************************************************************/
package microsoft.entityframeworkcore.storage;
import org.mases.jcobridge.*;
import org.mases.jcobridge.netreflection.*;
import java.util.ArrayList;
// Import section
import microsoft.entityframeworkcore.storage.TypeMappingSourceBase;
import microsoft.entityframeworkcore.storage.CoreTypeMapping;
import microsoft.entityframeworkcore.metadata.IProperty;
import microsoft.entityframeworkcore.metadata.IPropertyImplementation;
import system.reflection.MemberInfo;
import microsoft.entityframeworkcore.metadata.IModel;
import microsoft.entityframeworkcore.metadata.IModelImplementation;
/**
* The base .NET class managing Microsoft.EntityFrameworkCore.Storage.TypeMappingSource, Microsoft.EntityFrameworkCore, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60.
* <p>
*
* See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Microsoft.EntityFrameworkCore.Storage.TypeMappingSource" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Microsoft.EntityFrameworkCore.Storage.TypeMappingSource</a>
*/
public class TypeMappingSource extends TypeMappingSourceBase {
/**
* Fully assembly qualified name: Microsoft.EntityFrameworkCore, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
*/
public static final String assemblyFullName = "Microsoft.EntityFrameworkCore, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60";
/**
* Assembly name: Microsoft.EntityFrameworkCore
*/
public static final String assemblyShortName = "Microsoft.EntityFrameworkCore";
/**
* Qualified class name: Microsoft.EntityFrameworkCore.Storage.TypeMappingSource
*/
public static final String className = "Microsoft.EntityFrameworkCore.Storage.TypeMappingSource";
static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName);
/**
* The type managed from JCOBridge. See {@link JCType}
*/
public static JCType classType = createType();
static JCEnum enumInstance = null;
JCObject classInstance = null;
static JCType createType() {
try {
String classToCreate = className + ", "
+ (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Creating %s", classToCreate);
JCType typeCreated = bridge.GetType(classToCreate);
if (JCOReflector.getDebug())
JCOReflector.writeLog("Created: %s",
(typeCreated != null) ? typeCreated.toString() : "Returned null value");
return typeCreated;
} catch (JCException e) {
JCOReflector.writeLog(e);
return null;
}
}
void addReference(String ref) throws Throwable {
try {
bridge.AddReference(ref);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
/**
* Internal constructor. Use with caution
*/
public TypeMappingSource(java.lang.Object instance) throws Throwable {
super(instance);
if (instance instanceof JCObject) {
classInstance = (JCObject) instance;
} else
throw new Exception("Cannot manage object, it is not a JCObject");
}
public String getJCOAssemblyName() {
return assemblyFullName;
}
public String getJCOClassName() {
return className;
}
public String getJCOObjectName() {
return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName);
}
public java.lang.Object getJCOInstance() {
return classInstance;
}
public void setJCOInstance(JCObject instance) {
classInstance = instance;
super.setJCOInstance(classInstance);
}
public JCType getJCOType() {
return classType;
}
/**
* Try to cast the {@link IJCOBridgeReflected} instance into {@link TypeMappingSource}, a cast assert is made to check if types are compatible.
* @param from {@link IJCOBridgeReflected} instance to be casted
* @return {@link TypeMappingSource} instance
* @throws java.lang.Throwable in case of error during cast operation
*/
public static TypeMappingSource cast(IJCOBridgeReflected from) throws Throwable {
NetType.AssertCast(classType, from);
return new TypeMappingSource(from.getJCOInstance());
}
// Constructors section
public TypeMappingSource() throws Throwable {
}
// Methods section
public CoreTypeMapping FindMapping(IProperty property) throws Throwable, system.ArgumentOutOfRangeException, system.ArgumentNullException, system.PlatformNotSupportedException, system.IndexOutOfRangeException, system.RankException, system.ArgumentException, system.ArrayTypeMismatchException, system.InvalidOperationException, system.ObjectDisposedException, system.OutOfMemoryException, system.NotSupportedException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objFindMapping = (JCObject)classInstance.Invoke("FindMapping", property == null ? null : property.getJCOInstance());
return new CoreTypeMapping(objFindMapping);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public CoreTypeMapping FindMapping(MemberInfo member) throws Throwable, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.OutOfMemoryException, system.FormatException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objFindMapping = (JCObject)classInstance.Invoke("FindMapping", member == null ? null : member.getJCOInstance());
return new CoreTypeMapping(objFindMapping);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public CoreTypeMapping FindMapping(NetType type, IModel model) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException, system.ObjectDisposedException, system.InvalidOperationException, system.RankException, system.ArrayTypeMismatchException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objFindMapping = (JCObject)classInstance.Invoke("FindMapping", type == null ? null : type.getJCOInstance(), model == null ? null : model.getJCOInstance());
return new CoreTypeMapping(objFindMapping);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
public CoreTypeMapping FindMapping(NetType type) throws Throwable, system.ArgumentException, system.PlatformNotSupportedException, system.NotSupportedException, system.ArgumentNullException, system.InvalidOperationException, system.ArgumentOutOfRangeException, system.IndexOutOfRangeException {
if (classInstance == null)
throw new UnsupportedOperationException("classInstance is null.");
try {
JCObject objFindMapping = (JCObject)classInstance.Invoke("FindMapping", type == null ? null : type.getJCOInstance());
return new CoreTypeMapping(objFindMapping);
} catch (JCNativeException jcne) {
throw translateException(jcne);
}
}
// Properties section
// Instance Events section
} |
3e15f277d1b5c09718b446ebbd46ef1179ccda54 | 655 | java | Java | exts/jphp-git-ext/src/main/java/org/develnext/jphp/ext/git/classes/WrapGitAPIException.java | Diffblue-benchmarks/Jphp-group-jphp | e0d00163a74d78adb72629d8309d1df3ffed7662 | [
"Apache-2.0"
] | 903 | 2015-01-02T18:49:24.000Z | 2018-05-02T14:44:25.000Z | exts/jphp-git-ext/src/main/java/org/develnext/jphp/ext/git/classes/WrapGitAPIException.java | Diffblue-benchmarks/Jphp-group-jphp | e0d00163a74d78adb72629d8309d1df3ffed7662 | [
"Apache-2.0"
] | 137 | 2018-05-11T20:47:24.000Z | 2022-02-24T23:21:21.000Z | exts/jphp-git-ext/src/main/java/org/develnext/jphp/ext/git/classes/WrapGitAPIException.java | Diffblue-benchmarks/Jphp-group-jphp | e0d00163a74d78adb72629d8309d1df3ffed7662 | [
"Apache-2.0"
] | 129 | 2015-01-06T06:34:03.000Z | 2018-04-22T10:00:35.000Z | 31.190476 | 70 | 0.783206 | 9,337 | package org.develnext.jphp.ext.git.classes;
import org.develnext.jphp.ext.git.GitExtension;
import org.eclipse.jgit.api.errors.GitAPIException;
import php.runtime.annotation.Reflection;
import php.runtime.env.Environment;
import php.runtime.ext.java.JavaException;
import php.runtime.reflection.ClassEntity;
@Reflection.Name("GitAPIException")
@Reflection.Namespace(GitExtension.NS)
public class WrapGitAPIException extends JavaException {
public WrapGitAPIException(Environment env, Throwable throwable) {
super(env, throwable);
}
public WrapGitAPIException(Environment env, ClassEntity clazz) {
super(env, clazz);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.