blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
4b7123bac996597a427e6d71679b6849a60f88c3 | Java | meganjohn/advent-of-code-2020 | /day1/src/main/java/multiplier/Multiplier.java | UTF-8 | 277 | 2.90625 | 3 | [] | no_license | package main.java.multiplier;
public class Multiplier {
public static int multiplyTwoNumbers(int[] numbers) {
return numbers[0]*numbers[1];
}
public static int multiplyThreeNumbers(int[] numbers) {
return numbers[0]*numbers[1]*numbers[2];
}
}
| true |
9a9a6c739e375754f05e9dd3080e364dc2827001 | Java | danieljiang2013/Wealth_Distribution | /src/LineGraph.java | UTF-8 | 659 | 3.28125 | 3 | [] | no_license | import java.util.ArrayList;
import java.util.List;
/**
* This class is a generic representation of a stat that can
* be calculated in the system.
* @param <T>
*/
public class LineGraph<T extends Number > {
private String name = "";
private Double sum = 0.0;
private List<T> counts = new ArrayList<T>();
public LineGraph(String name) {
this.name = name;
}
public List<T> getCounts() {
return counts;
}
public void add(T value) {
if(value != null) {
counts.add(value);
sum += value.doubleValue();
}
}
public String getName() {
return name;
}
public double average() {
return sum.doubleValue() / counts.size();
}
}
| true |
855079b0fff89252b066d7110330933b506f8eed | Java | eye-bs/ascend-exam | /src/main/java/com/ascendcorp/exam/model/Reference.java | UTF-8 | 607 | 2.421875 | 2 | [] | no_license | package com.ascendcorp.exam.model;
import lombok.Data;
@Data
public class Reference {
private String reference1;
private String reference2;
private String firstName;
private String lastName;
public Reference(String reference1, String reference2, String firstName, String lastName) {
this.reference1 = reference1;
this.reference2 = reference2;
this.firstName = firstName;
this.lastName = lastName;
}
public Reference(String reference1, String reference2) {
this.reference1 = reference1;
this.reference2 = reference2;
}
}
| true |
1ab5d0e77b2c931188f19538727fb1475b817c76 | Java | HaiPiaoAPP/haipiao | /user-service/src/main/java/com/haipiao/userservice/enums/RecommendationContextEnum.java | UTF-8 | 703 | 2.375 | 2 | [] | no_license | package com.haipiao.userservice.enums;
import java.util.Arrays;
/**
* @author wangjipeng
*/
public enum RecommendationContextEnum {
/**
* 推荐用户场景
*/
DEFAULT("default"),
ARTICLE("article"),
USER_PROFILE("user_profile");
RecommendationContextEnum(String value) {
this.value = value;
}
private String value;
public String getValue() {
return value;
}
public static RecommendationContextEnum findByValue(String code) {
return Arrays.stream(RecommendationContextEnum.values())
.filter(re -> code.equalsIgnoreCase(re.getValue()))
.findFirst()
.orElse(null);
}
}
| true |
bc3bf2a8ab14480c83256014cd20210995f32d57 | Java | shulieTech/Takin-web | /takin-web-data/src/main/java/com/pamirs/takin/entity/domain/dto/report/ReportDetailDTO.java | UTF-8 | 2,695 | 1.71875 | 2 | [] | no_license | package com.pamirs.takin.entity.domain.dto.report;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import com.pamirs.takin.entity.domain.dto.scenemanage.WarnDTO;
import io.shulie.takin.web.ext.entity.UserCommonExt;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @author 莫问
* @date 2020-04-17
*/
@Data
public class ReportDetailDTO extends UserCommonExt implements Serializable {
private static final long serialVersionUID = 6093881590337487184L;
@ApiModelProperty(value = "报告状态:0/就绪状态,1/生成中, 2/完成生成")
private Integer taskStatus;
@ApiModelProperty(value = "报告ID")
private Long id;
@ApiModelProperty(value = "消耗流量")
private BigDecimal amount;
@ApiModelProperty(value = "场景名称")
private Long sceneId;
@ApiModelProperty(value = "场景名称")
private String sceneName;
@ApiModelProperty(value = "开始时间")
private String startTime;
@ApiModelProperty(value = "结束时间")
private Date endTime;
@ApiModelProperty(value = "压测结论: 0/不通过,1/通过")
private Integer conclusion;
@ApiModelProperty(value = "压测结论描述")
private String conclusionRemark;
@ApiModelProperty(value = "警告次数")
private Long totalWarn;
@ApiModelProperty(value = "请求总数")
private Long totalRequest;
@ApiModelProperty(value = "最大并发")
private Integer concurrent;
@ApiModelProperty(value = "施压类型,0:并发,1:tps,2:自定义;不填默认为0")
private Integer pressureType;
@ApiModelProperty(value = "平均并发数")
private BigDecimal avgConcurrent;
@ApiModelProperty(value = "目标TPS")
private Integer tps;
@ApiModelProperty(value = "平均TPS")
private BigDecimal avgTps;
@ApiModelProperty(value = "平均RT")
private BigDecimal avgRt;
@ApiModelProperty(value = "成功率")
private BigDecimal successRate;
@ApiModelProperty(value = "sa")
private BigDecimal sa;
@ApiModelProperty(value = "测试时长")
private String testTime;
@ApiModelProperty(value = "测试总时长")
private String testTotalTime;
@ApiModelProperty(value = "警告列表")
private List<WarnDTO> warn;
@ApiModelProperty(value = "业务活动链路概览")
private List<BusinessActivitySummaryDTO> businessActivity;
@ApiModelProperty(name = "leakVerifyResult", value = "漏数验证结果")
private LeakVerifyResult leakVerifyResult;
@ApiModelProperty(name = "jobId", value = "压测引擎任务Id")
private Long jobId;
}
| true |
28d6f8706e8f7db3fcd480fbd8fd914f1a75c30c | Java | thombergs/coderadar | /plugins/findbugs-adapter-plugin/src/test/java/org/wickedsource/coderadar/analyzer/findbugs/xsd/BugCollectionParserTest.java | UTF-8 | 460 | 1.851563 | 2 | [
"MIT"
] | permissive | package org.wickedsource.coderadar.analyzer.findbugs.xsd;
import org.junit.Assert;
import org.junit.Test;
public class BugCollectionParserTest extends TestReportAccessor {
@Test
public void parsesSuccessfully() throws Exception {
byte[] report = getValidReport();
BugCollectionParser parser = new BugCollectionParser();
BugCollection collection = parser.fromBytes(report);
Assert.assertNotNull(collection);
}
} | true |
536836490ef50947610c297c167d1a146afa307a | Java | MStart/RepositoryCache | /repository-cache-compiler/src/main/java/com/kuassivi/compiler/ProxyClassGenerator.java | UTF-8 | 12,193 | 1.976563 | 2 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
* Copyright (c) 2016 Francisco Gonzalez-Armijo Riádigos
*
* 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.kuassivi.compiler;
import com.kuassivi.annotation.RepositoryCacheManager;
import com.kuassivi.annotation.RepositoryProxyCache;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.JavaFile;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
/**
* @author Francisco Gonzalez-Armijo
*/
public class ProxyClassGenerator {
/**
* Will be added to the name of the generated proxy class
*/
private static final String CLASS_SUFFIX = "ProxyCache";
/**
* The full qualified name of the Class that will be processed
*/
private String qualifiedClassName;
/**
* The simple name of the Class that will be processed
*/
private String simpleClassName;
/**
* The name of the Proxy Class that will be generated
*/
private String generatedClassName;
/**
* The package name of the current class
*/
private String packageName;
/**
* Element Utils
*/
private Elements elementUtils;
/**
* Maps all annotated methods
*/
private Map<String, AnnotatedMethod> methodsMap = new LinkedHashMap<String, AnnotatedMethod>();
/**
* Supply the Qualified ClassName for the Proxy
*
* @param elementUtils Element utils object
* @param qualifiedClassName ClassName of the Annotated Class
*/
public ProxyClassGenerator(Elements elementUtils, String qualifiedClassName) {
this.qualifiedClassName = qualifiedClassName;
this.elementUtils = elementUtils;
TypeElement classElement = this.elementUtils.getTypeElement(qualifiedClassName);
this.simpleClassName = classElement.getSimpleName().toString();
this.generatedClassName = this.simpleClassName + CLASS_SUFFIX;
PackageElement pkg = this.elementUtils.getPackageOf(classElement);
this.packageName = pkg.isUnnamed()
? null
: pkg.getQualifiedName().toString();
}
/**
* Adds the annotated method into the methods Map
*
* @param methodToInsert Method annotated
* @throws ProcessingException Method already exist, please use the named value
*/
public void add(AnnotatedMethod methodToInsert) throws ProcessingException {
String methodName = methodToInsert.getQualifiedMethodName();
// Checks for overloaded methods
if (methodsMap.containsKey(methodName)) {
// Method already exist in Map
throw new ProcessingException(methodToInsert.getElement(),
"Conflict: The method \"%1$s\" already exists in %2$s"
+ CLASS_SUFFIX + "."
+ "class"
+ "\nThe checked method in conflict is %1$s( %3$s )."
+ "\nWe cannot process overloaded methods, so please add the "
+ "\"named\" attribute in the annotated method like "
+ "RepositoryCache(named = \"%1$s_2\").",
methodName,
this.simpleClassName,
methodToInsert.getExecutableType().getParameterTypes()
.toString());
}
methodsMap.put(methodName, methodToInsert);
}
/**
* Generates the proxy cache java file
*
* @param filer Filer
* @throws IOException Generator file exception
*/
public void generateCode(Filer filer) throws IOException {
TypeSpec.Builder classBuilder =
TypeSpec.classBuilder(generatedClassName)
.addJavadoc("Auto-generated Class by RepositoryCache library Processor")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addSuperinterface(RepositoryProxyCache.class);
// Add Fields
classBuilder
.addField(
FieldSpec
.builder(RepositoryCacheManager.class, "repositoryCacheManager")
.addModifiers(Modifier.PRIVATE, Modifier.FINAL)
.build())
.addField(
FieldSpec
.builder(File.class, "cacheDir")
.addModifiers(Modifier.PRIVATE)
.build())
.addField(
FieldSpec
.builder(String.class, "fileName")
.addModifiers(Modifier.PRIVATE)
.build())
.addField(
FieldSpec
.builder(String.class, "cacheKey")
.addModifiers(Modifier.PRIVATE)
.build())
.addField(
FieldSpec
.builder(TypeName.LONG, "cacheTime")
.addModifiers(Modifier.PRIVATE)
.build());
// Add Constructor
MethodSpec.Builder constructor =
MethodSpec.constructorBuilder()
.addModifiers(Modifier.PRIVATE)
.addParameter(File.class, "cacheDir")
.addParameter(String.class, "fileName")
.addParameter(TypeName.LONG, "cacheTime")
.addStatement("this.repositoryCacheManager = "
+ "RepositoryCacheManager.getInstance()")
.addStatement("this.cacheDir = cacheDir")
.addStatement("this.fileName = fileName")
.addStatement("this.cacheTime = cacheTime");
classBuilder.addMethod(constructor.build());
for (AnnotatedMethod annotatedMethod : methodsMap.values()) {
MethodSpec.Builder method = MethodSpec
.methodBuilder(annotatedMethod.getQualifiedMethodName())
.addModifiers(Modifier.PUBLIC, Modifier.STATIC)
.addParameter(File.class, "cacheDir")
.returns(ClassName.get(packageName, generatedClassName));
String fileName = simpleClassName + "_" + annotatedMethod.getFullMethodName();
fileName = RepositoryCacheManager.hashMD5(fileName);
method.addStatement("return new $L(cacheDir, $S, $L)",
generatedClassName,
fileName,
annotatedMethod.getAnnotation().value());
classBuilder.addMethod(method.build());
}
// Add proxy methods
addProxyMethods(classBuilder);
// Write file
TypeSpec typeSpec = classBuilder.build();
JavaFile.builder(packageName, typeSpec).build().writeTo(filer);
}
private void addProxyMethods(TypeSpec.Builder classBuilder) {
MethodSpec.Builder method;
method = MethodSpec.methodBuilder("persist")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(TypeName.VOID);
method.addStatement("this.repositoryCacheManager.persist(this)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("persist")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(String.class, "content")
.addAnnotation(Override.class)
.returns(TypeName.VOID);
method.addStatement("this.repositoryCacheManager.persist(this, content)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("evict")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(TypeName.VOID);
method.addStatement("this.repositoryCacheManager.evict(this)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("select")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addParameter(Object.class, "cacheKey")
.addAnnotation(Override.class)
.returns(TypeName.VOID);
method.addStatement("this.cacheKey = String.valueOf(cacheKey)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("getContent")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(String.class);
method.addStatement("return repositoryCacheManager.getContent(this)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("getCacheDir")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(File.class);
method.addStatement("return this.cacheDir");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("getCacheTime")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(TypeName.LONG);
method.addStatement("return this.cacheTime");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("getFileName")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(String.class);
method.addStatement("return RepositoryCacheManager.hashMD5(this.fileName + this.cacheKey)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("isCached")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(TypeName.BOOLEAN);
method.addStatement("return repositoryCacheManager.isCached(this)");
classBuilder.addMethod(method.build());
method = MethodSpec.methodBuilder("isExpired")
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addAnnotation(Override.class)
.returns(TypeName.BOOLEAN);
method.addStatement("return repositoryCacheManager.isExpired(this)");
classBuilder.addMethod(method.build());
}
}
| true |
b01fb0e3aac08a6f69ab8849838a94660f75b479 | Java | groupon/metrics | /tsd/cluster-aggregator/src/main/java/com/arpnetworking/clusteraggregator/http/Routes.java | UTF-8 | 9,522 | 1.640625 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* Copyright 2014 Groupon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.arpnetworking.clusteraggregator.http;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.cluster.Member;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import akka.dispatch.OnComplete;
import akka.http.javadsl.model.ContentType;
import akka.http.javadsl.model.HttpHeader;
import akka.http.javadsl.model.HttpMethods;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.http.javadsl.model.MediaTypes;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.model.headers.CacheControl;
import akka.http.javadsl.model.headers.CacheDirectives;
import akka.japi.JavaPartialFunction;
import akka.pattern.Patterns;
import akka.util.Timeout;
import com.arpnetworking.clusteraggregator.Status;
import com.arpnetworking.clusteraggregator.models.StatusResponse;
import com.arpnetworking.configuration.jackson.akka.AkkaModule;
import com.arpnetworking.jackson.ObjectMapperFactory;
import com.arpnetworking.metrics.Metrics;
import com.arpnetworking.metrics.MetricsFactory;
import com.arpnetworking.metrics.Timer;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Future;
import scala.runtime.AbstractFunction1;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Http server routes.
*
* @author Ville Koskela (vkoskela at groupon dot com)
*/
public class Routes extends AbstractFunction1<HttpRequest, Future<HttpResponse>> {
/**
* Public constructor.
*
* @param actorSystem Instance of <code>ActorSystem</code>.
* @param metricsFactory Instance of <code>MetricsFactory</code>.
*/
public Routes(final ActorSystem actorSystem, final MetricsFactory metricsFactory) {
_actorSystem = actorSystem;
_metricsFactory = metricsFactory;
_mapper.registerModule(new SimpleModule().addSerializer(Member.class, new MemberSerializer()));
_mapper.registerModule(new AkkaModule(actorSystem));
}
/**
* {@inheritDoc}
*/
@Override
public Future<HttpResponse> apply(final HttpRequest request) {
final Metrics metrics = _metricsFactory.create();
final Timer timer = metrics.createTimer(createTimerName(request));
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(String.format("Request; %s", request));
}
final Future<HttpResponse> futureResponse = process(request);
futureResponse.onComplete(
new OnComplete<HttpResponse>() {
@Override
public void onComplete(final Throwable failure, final HttpResponse response) {
timer.close();
metrics.close();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(String.format("Response; %s", response));
}
}
},
_actorSystem.dispatcher());
return futureResponse;
}
private Future<HttpResponse> process(final HttpRequest request) {
if (HttpMethods.GET.equals(request.method())) {
if (PING_PATH.equals(request.getUri().path())) {
return ask("/user/status", new Status.HealthRequest(), Boolean.FALSE)
.map(
new Mapper<Boolean, HttpResponse>() {
@Override
public HttpResponse apply(final Boolean isHealthy) {
return (HttpResponse) response()
.withStatus(isHealthy ? StatusCodes.OK : StatusCodes.INTERNAL_SERVER_ERROR)
.addHeader(PING_CACHE_CONTROL_HEADER)
.withEntity(JSON_CONTENT_TYPE,
"{\"status\":\""
+ (isHealthy ? HEALTHY_STATE : UNHEALTHY_STATE)
+ "\"}");
}
},
_actorSystem.dispatcher());
} else if (STATUS_PATH.equals(request.getUri().path())) {
return ask("/user/status", new Status.StatusRequest(), (StatusResponse) null)
.map(
new Mapper<StatusResponse, HttpResponse>() {
@Override
public HttpResponse checkedApply(final StatusResponse status) throws JsonProcessingException {
return (HttpResponse) response()
.withEntity(
JSON_CONTENT_TYPE,
_mapper.writeValueAsString(status));
}
},
_actorSystem.dispatcher());
}
}
return Futures.successful((HttpResponse) response().withStatus(404));
}
private HttpResponse response() {
return HttpResponse.create();
}
private <T> Future<T> ask(final String actorPath, final Object request, final T defaultValue) {
return _actorSystem.actorSelection(actorPath)
.resolveOne(TIMEOUT)
.flatMap(
new Mapper<ActorRef, Future<T>>() {
@Override
public Future<T> apply(final ActorRef actor) {
@SuppressWarnings("unchecked")
final Future<T> future = (Future<T>) Patterns.ask(
actor,
request,
TIMEOUT);
return future;
}
},
_actorSystem.dispatcher())
.recover(
new JavaPartialFunction<Throwable, T>() {
@Override
public T apply(final Throwable t, final boolean isCheck) throws Exception {
LOGGER.error(String.format("Error when asking actor; actorPath=%s, request=%s", actorPath, request), t);
return defaultValue;
}
},
_actorSystem.dispatcher());
}
private String createTimerName(final HttpRequest request) {
final StringBuilder nameBuilder = new StringBuilder()
.append("RestService/")
.append(request.method().value());
if (!request.getUri().path().startsWith("/")) {
nameBuilder.append("/");
}
nameBuilder.append(request.getUri().path());
return nameBuilder.toString();
}
private final ActorSystem _actorSystem;
private final MetricsFactory _metricsFactory;
private static final Logger LOGGER = LoggerFactory.getLogger(Routes.class);
// Ping
private static final String PING_PATH = "/ping";
private static final String STATUS_PATH = "/status";
private static final HttpHeader PING_CACHE_CONTROL_HEADER = CacheControl.create(
CacheDirectives.PRIVATE(),
CacheDirectives.NO_CACHE,
CacheDirectives.NO_STORE,
CacheDirectives.MUST_REVALIDATE);
private static final String UNHEALTHY_STATE = "UNHEALTHY";
private static final String HEALTHY_STATE = "HEALTHY";
private static final ContentType JSON_CONTENT_TYPE = ContentType.create(MediaTypes.APPLICATION_JSON);
private static final Timeout TIMEOUT = Timeout.apply(5, TimeUnit.SECONDS);
private final ObjectMapper _mapper = ObjectMapperFactory.createInstance();
private static class MemberSerializer extends JsonSerializer<Member> {
@Override
public void serialize(
final Member value,
final JsonGenerator jgen,
final SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeObjectField("address", value.address().toString());
jgen.writeObjectField("roles", value.getRoles().toArray());
jgen.writeEndObject();
}
}
}
| true |
f75e8a41efbfa7e00af04108e3197dd4be50ef89 | Java | fuzhiyan/DiSanZhou_B | /app/src/main/java/text/bawei/com/disanzhou_b/fragments/LiaoTianFragment.java | UTF-8 | 1,715 | 2.21875 | 2 | [] | no_license | package text.bawei.com.disanzhou_b.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
import text.bawei.com.disanzhou_b.R;
import text.bawei.com.disanzhou_b.adapter.LiaoTian_Adapter;
import text.bawei.com.disanzhou_b.bean.LiaoTianBean;
/**
* A simple {@link Fragment} subclass.
*/
public class LiaoTianFragment extends Fragment {
private ListView liaotian_list;
public LiaoTianFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_liao_tian, container, false);
initView(view);
initData();
return view;
}
private void initData() {
ArrayList<LiaoTianBean> list = new ArrayList<>();
for (int x = 0; x < 10; x++) {
LiaoTianBean bean;
if (x % 2 == 0) {
bean = new LiaoTianBean(R.mipmap.ic_launcher, "张" + x, "这里是聊天的内容" + x);
} else {
bean = new LiaoTianBean(R.mipmap.ic_launcher, "李" + x, "这里是聊天的内容" + x);
}
list.add(bean);
}
LiaoTian_Adapter adapter = new LiaoTian_Adapter(getActivity(), list);
liaotian_list.setAdapter(adapter);
}
private void initView(View view) {
liaotian_list = (ListView) view.findViewById(R.id.liaotian_list);
}
}
| true |
618adb51d270c5dde6c10599c3de6837af306604 | Java | naveengowda6197/Bank-Application | /SpringMVCHibernateCRUD/src/main/java/com/jwt/controller/AccountController.java | UTF-8 | 4,502 | 2.203125 | 2 | [] | no_license | package com.jwt.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.jwt.model.Account;
import com.jwt.model.LoginForms;
import com.jwt.service.AccountService;
@Controller
public class AccountController {
private static final Logger logger = Logger
.getLogger(AccountController.class);
@Autowired
private AccountService accountService;
//login by naveen
@RequestMapping(value = "/")
public ModelAndView dashboard(ModelAndView model) throws IOException {
model.addObject("loginforms", new LoginForms());
model.setViewName("login");
return model;
}
//validation for useer and admin
@RequestMapping(value = "/admin", method = RequestMethod.POST)
public ModelAndView admindashboard(@ModelAttribute LoginForms loginforms) {
ModelAndView mav=null;
//boolean authenticated=false;
if(loginforms.getEmail().equals("admin@gmail.com") &&loginforms.getPass().equals("admin"))
mav= new ModelAndView("redirect:/adminHome");
//authenticated=accountService.authenticateUserLogin(loginforms.getEmail(),loginforms.getPass());
else if(accountService.authenticateUserLogin(loginforms.getEmail(),loginforms.getPass()))
mav= new ModelAndView("redirect:/userHome/"+loginforms.getEmail()+"/");
else
mav= new ModelAndView("redirect:/");
return mav;
}
//accountService.authenticateUserLogin(loginforms.getEmail(),loginforms.getPass());
//user dashboard
@RequestMapping(value = "/userHome/{email}/", method = RequestMethod.GET)
public ModelAndView userHome(ModelAndView model,@PathVariable String email) {
System.out.println(email);
List<Account> listOfAccount=accountService.getUserByEmail(email);
model.addObject("listOfAccount", listOfAccount);
model.setViewName("userHome");
return model;
}
//admin home
@RequestMapping(value = "/adminHome")
public ModelAndView listAccounts(ModelAndView model) throws IOException {
List<Account> listAccount = accountService.getAllAccount();
model.addObject("listAccount", listAccount);
model.setViewName("adminHome");
return model;
}
//accountService.authenticateUser
@RequestMapping(value = "/newAccount", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Account account = new Account();
model.addObject("account", account);
model.setViewName("AccountForm");
return model;
}
@RequestMapping(value = "/saveAccount", method = RequestMethod.POST)
public ModelAndView saveEmployee(@ModelAttribute Account account) {
if (account.getAc_no() == 0) { // if employee id is 0 then creating the
// employee other updating the employee
accountService.addAccount(account);
} else {
accountService.updateAccount(account);
}
return new ModelAndView("redirect:/adminHome");
}
@RequestMapping(value = "/editAccount", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int ac_no = Integer.parseInt(request.getParameter("ac_no"));
Account account = accountService.getAccount(ac_no);
ModelAndView model = new ModelAndView("AccountForm");
model.addObject("account", account);
return model;
}
// @RequestMapping(value = "/withdraw/${account.ac_no}/${account.balance}", method = RequestMethod.GET)
// public ModelAndView withdraw(ModelAndView model,@PathVariable String ac_no,@PathVariable String balance) {
// String acno=new String(ac_no);
// Integer bal=new Integer(balance);
// model.addObject("ac_no", acno);
// model.addObject("ac_no", bal);
// model.setViewName("withdrowDashboards");
// return model;
// }
//
//
// @RequestMapping(value = "/withdraw/${ac_no}/${balance}/${withrawn}", method = RequestMethod.POST)
// public ModelAndView withdraw(ModelAndView model,@PathVariable String ac_no,@PathVariable String balance,@PathVariable String withrawn) {
// System.out.println(withrawn);
// return new ModelAndView("redirect:/adminHome");
// }
} | true |
db5ade8f6ca20230f42ed3970e60a4a6461e0a5c | Java | oreoTaste/bitcamp-study | /bitcamp-java/src/main/java/com/eomcs/oop/ex11/c/step6/Product.java | UTF-8 | 199 | 2.0625 | 2 | [] | no_license | package com.eomcs.oop.ex11.c.step6;
public class Product {
// 카테고리 별로 클래스를 분리하면 관리하기 쉬워진다
int category;
String name;
String maker;
int price;
}
| true |
7311e920a390fef4467288a00192d64116a35764 | Java | FelipeJuanFernandes/Generation | /Java/src/br/comgeneration/POO/Patinete_5.java | ISO-8859-1 | 1,072 | 3.203125 | 3 | [] | no_license | package br.comgeneration.POO;
public class Patinete_5 {
private String modelo;
private String cor;
private double velocidade;
public Patinete_5 (String modelo, String cor, double velocidade) {
this.modelo = modelo;
this.cor = cor;
this.velocidade = velocidade;
}
public void imprimirInfo(){
System.out.println("Modelo: "+modelo+"\nCor: "+cor+"\nVelocidade atual: "+velocidade);
}
public void pararPatinete(){
if (velocidade > 0){
velocidade = 0;
System.out.println("\nSeu patinete est parado agora!");
}
}
public void andarPatinete(){
if (velocidade == 0){
velocidade = velocidade+1;
System.out.println("\nVoc e seu patinete esto em movimento agora!");
}
}
public String getModelo(){
return modelo;
}
public void setModelo(String modelo){
this.modelo = modelo;
}
public String getCor(){
return cor;
}
public void setCor(String cor){
this.cor = cor;
}
public double getVelocidade(){
return velocidade;
}
public void setVelocidade(double velocidade){
this.velocidade = velocidade;
}
}
| true |
b8584b7e890aa7c140581635b4b43b288448373c | Java | tnicacio/programacao-2 | /provaprog2/src/provaprog2/ControleDeEstoque.java | UTF-8 | 9,093 | 3 | 3 | [] | no_license | package provaprog2;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ControleDeEstoque {
/**
* *
* 1 - salvar em estoque.dados 2 - listar array de registros 3 - ordenar por
* id, nome ou quantidade 4 - excluir um registro
*
**
*/
protected RandomAccessFile arquivo;
private long TAMANHO_ID = 10;
private long TAMANHO_NOME = 100;
private long TAMANHO_LOCAL = 50;
private long TAMANHO_QUANTIDADE = 40;
private long TAMANHO_REGISTRO = (TAMANHO_ID + TAMANHO_NOME + TAMANHO_LOCAL + TAMANHO_QUANTIDADE) * 2;
public ControleDeEstoque() {
try {
arquivo = new RandomAccessFile("estoque.dados", "rw");
} catch (Exception e) {
System.out.println(e);
}
}
public void finalizar() {
try {
arquivo.close();
} catch (Exception e) {
System.out.println(e);
}
}
private void salvar(Registro r, long nRegistro) {
try {
arquivo.seek(TAMANHO_REGISTRO * nRegistro);
} catch (IOException e) {
System.out.println(e);
}
gravar(r);
}
private void gravar(Registro r) {
try {
String id = Integer.toString(r.getID());
String nome = r.getNomeProduto();
String local = r.getLocal();
String quantidade = Float.toString(r.getQuantidade());
int i = 0;
for (; i < (int) TAMANHO_ID && i < id.length(); i++) {
arquivo.writeChar(id.charAt(i));
}
for (; i < 10; i++) {
arquivo.writeChar('\u0000');
}
i = 0;
for (; i < (int) TAMANHO_NOME && i < nome.length(); i++) {
arquivo.writeChar(nome.charAt(i));
}
for (; i < (int) TAMANHO_NOME; i++) {
arquivo.writeChar('\u0000');
}
i = 0;
for (; i < (int) TAMANHO_LOCAL && i < local.length(); i++) {
arquivo.writeChar(local.charAt(i));
}
for (; i < (int) TAMANHO_LOCAL; i++) {
arquivo.writeChar('\u0000');
}
i = 0;
for (; i < (int) TAMANHO_QUANTIDADE && i < quantidade.length(); i++) {
arquivo.writeChar(quantidade.charAt(i));
}
for (; i < (int) TAMANHO_QUANTIDADE; i++) {
arquivo.writeChar('\u0000');
}
} catch (Exception e) {
System.out.println(e);
}
}
public void adicionar(Registro r) {
try {
if (arquivo.length() > 0) {
arquivo.seek(arquivo.length());
}
gravar(r);
} catch (Exception e) {
System.out.println(e);
}
}
public Registro ler(long nRegistro) {
Registro registro = null;
try {
arquivo.seek(nRegistro * TAMANHO_REGISTRO);
String id = "";
String nome = "";
String local = "";
String quantidade = "";
for (int i = 0; i < TAMANHO_ID; i++) {
id += arquivo.readChar();
}
for (int i = 0; i < TAMANHO_NOME; i++) {
nome += arquivo.readChar();
}
for (int i = 0; i < TAMANHO_LOCAL; i++) {
local += arquivo.readChar();
}
for (int i = 0; i < TAMANHO_QUANTIDADE; i++) {
quantidade += arquivo.readChar();
}
int idd = Integer.parseInt(id.trim());
registro = new Registro(idd, nome, local, Float.parseFloat(quantidade));
} catch (Exception e) {
System.out.println(e);
}
return registro;
}
public long quantidadeRegistros() {
long tamanho = -1;
try {
tamanho = arquivo.length() / (TAMANHO_REGISTRO);
} catch (Exception e) {
System.out.println(e);
}
return tamanho;
}
public Registro[] listar() {
Registro[] lista;
lista = new Registro[(int) quantidadeRegistros()];
for (int i = 0; i < quantidadeRegistros(); i++) {
lista[i] = (ler(i));
System.out.println(ler(i));
}
return lista;
}
private Registro[] ArrayLista() {
Registro[] lista;
lista = new Registro[(int) quantidadeRegistros()];
for (int i = 0; i < quantidadeRegistros(); i++) {
lista[i] = (ler(i));
}
return lista;
}
private void sortByID(Registro[] lista) {
boolean troca = true;
Registro aux;
while (troca) {
troca = false;
for (int i = 0; i < lista.length - 1; i++) {
if (lista[i].getID() > lista[i + 1].getID()) {
aux = lista[i];
lista[i] = lista[i + 1];
lista[i + 1] = aux;
troca = true;
}
}
}
for (int i = 0; i < quantidadeRegistros(); i++) {
System.out.println(lista[i].toString());
}
}
private void sortByQuantidade(Registro[] lista) {
boolean troca = true;
Registro aux;
while (troca) {
troca = false;
for (int i = 0; i < lista.length - 1; i++) {
if (lista[i].getQuantidade() > lista[i + 1].getQuantidade()) {
aux = lista[i];
lista[i] = lista[i + 1];
lista[i + 1] = aux;
troca = true;
}
}
}
for (int i = 0; i < quantidadeRegistros(); i++) {
System.out.println(lista[i].toString());
}
}
private void sortByNomeProduto(Registro[] lista) {
boolean troca = true;
Registro aux;
while (troca) {
troca = false;
for (int j = 0; j < lista.length; j++) {
for (int i = j + 1; i < lista.length; i++) {
if (lista[i].getNomeProduto().compareTo(lista[j].getNomeProduto()) < 0) {
aux = lista[j];
lista[j] = lista[i];
lista[i] = aux;
troca = true;
}
}
}
}
for (int i = 0; i < quantidadeRegistros(); i++) {
System.out.println(lista[i].toString());
}
}
public void ordenar(int valor) {
switch (valor) {
case 1:
sortByID(ArrayLista());
break;
case 2:
sortByNomeProduto(ArrayLista());
break;
case 3:
sortByQuantidade(ArrayLista());
break;
default:
System.out.println("Ordenação inválida");
break;
}
}
/**
* *
* Retorna -1 quando não encontra registros com o id
*/
private int getPosicaoByID(int id) {
int pos = -1;
for (int i = 0; i < quantidadeRegistros(); i++) {
boolean egual = ler(i).getID() == id;
if (egual) {
return i;
}
}
return pos;
}
// public void excluir(int id) throws IOException {
// long posicao = getPosicaoByID(id);
// long ler = TAMANHO_REGISTRO * (posicao + 1);
// long escrever = TAMANHO_REGISTRO * posicao;
// int tamanho = (int) ((int) TAMANHO_REGISTRO * quantidadeRegistros() - (int) TAMANHO_REGISTRO);
//
// byte[] bytes = new byte[tamanho];
//
// if (getPosicaoByID(id) == ((int) quantidadeRegistros() - 1)) {
// arquivo.getChannel().truncate(escrever);
// } else if (getPosicaoByID(id) > 0 && getPosicaoByID(id) < ((int) quantidadeRegistros() - 1)) {
// arquivo.seek(ler);
// arquivo.read(bytes);
// arquivo.seek(escrever);
// arquivo.write(bytes);
// arquivo.getChannel().truncate(tamanho);
// } else {
// System.out.println("Índice inválido");
// }
// }
public void excluir(int id) throws IOException {
long posicao = getPosicaoByID(id);
long tamanho = TAMANHO_REGISTRO * quantidadeRegistros() - TAMANHO_REGISTRO;
boolean truncar = posicao > 0 && posicao < ((int) quantidadeRegistros());
if (truncar) {
if (posicao != ((int) quantidadeRegistros() - 1)) {
for (int i = (int) posicao + 1; i < quantidadeRegistros(); i++) {
salvar(ler(i), i - 1);
}
}
arquivo.getChannel().truncate(tamanho);
} else {
System.out.println("Índice inválido");
}
}
public void limparTudo() throws IOException {
arquivo.setLength(0);
}
}
| true |
aac153627580f261387132913c2e1534d2673037 | Java | dkrivosic/opt-java | /DZ-02/src/hr/fer/zemris/optjava/dz2/Prijenosna.java | UTF-8 | 1,957 | 3 | 3 | [] | no_license | package hr.fer.zemris.optjava.dz2;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import Jama.Matrix;
public class Prijenosna {
public static void main(String[] args) throws IOException {
if (args.length != 3) {
System.out.println("3 arguments expected.");
System.exit(0);
}
String method = args[0];
int maxIterations = Integer.parseInt(args[1]);
String path = args[2];
// Reading
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
String line = reader.readLine();
List<String> lines = new ArrayList<>();
while (line != null && !line.isEmpty()) {
if (!line.startsWith("#")) {
lines.add(line);
}
line = reader.readLine();
}
reader.close();
int m = lines.size();
int n = 5;
double xArr[][] = new double[m][n];
double yArr[][] = new double[m][1];
for (int i = 0; i < m; i++) {
String str = lines.get(i).replaceAll("[,\\[\\]]", "");
str = str.trim();
String tmp[] = str.split("( )+");
for (int j = 0; j < n; j++) {
xArr[i][j] = Double.parseDouble(tmp[j]);
}
yArr[i][0] = Double.parseDouble(tmp[n]);
}
Matrix x = new Matrix(xArr);
Matrix y = new Matrix(yArr);
Matrix solution = new Matrix(6, 1);
for (int i = 0; i < 6; i++)
solution.set(i, 0, 0);
Matrix coef = Matrix.random(6, 1);
ErrorFunctionPrijenosna err = new ErrorFunctionPrijenosna(x, y, m);
if (method.equals("grad")) {
coef = NumOptAlgorithms.gradientDescent(err, maxIterations, coef);
// coef.print(n, 1);
} else {
coef = NumOptAlgorithms.newtonsMethod(err, maxIterations, coef);
// x.print(n, 1);
}
System.out.println("final solution: ");
coef.print(coef.getRowDimension(), coef.getColumnDimension());
System.out.println("error = " + err.getFunctionValue(coef));
}
}
| true |
fe9f4604ebf4e011faf922271e5d40203f00019a | Java | czarea/jcodes | /jcodes-core/src/main/java/com/czarea/jcodes/model/Project.java | UTF-8 | 1,644 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package com.czarea.jcodes.model;
/**
* 项目配置
*
* @author zhouzx
*/
public class Project {
private String baseDir;
private String template;
private String name;
private String module;
private String groupId;
private String version;
private String config;
public String getConfig() {
return config;
}
public void setConfig(String config) {
this.config = config;
}
public String getBaseDir() {
return baseDir;
}
public void setBaseDir(String baseDir) {
this.baseDir = baseDir;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getModule() {
return module;
}
public void setModule(String module) {
this.module = module;
}
@Override
public String toString() {
return "Project{" +
"baseDir='" + baseDir + '\'' +
", name='" + name + '\'' +
", module='" + module + '\'' +
", groupId='" + groupId + '\'' +
", version='" + version + '\'' +
'}';
}
}
| true |
cd0ea6720afca0d77eaee0d90b37e96af79180a4 | Java | cotterea1u/TpDesignPatterns | /src/visiteur/Article.java | UTF-8 | 561 | 2.921875 | 3 | [] | no_license | package visiteur;
public class Article extends Media {
protected String auteur;
protected String texte;
public Article(int d, String nom, String auteur, String texte) {
super(d, nom);
this.auteur = auteur;
this.texte = texte;
}
@Override
public String toString() {
return "Article{" +
"auteur='" + auteur + '\'' +
", annee=" + annee +
", nom='" + nom + '\'' +
'}';
}
public void accept(Visiteur v){
v.visit(this);
}
}
| true |
a1ac9c2be2708008c264168320d02c52acea3459 | Java | codebaise/SnmpMibInfoManagement | /src/main/java/com/zhi/snmp/utils/PDUUtils.java | UTF-8 | 3,143 | 2.34375 | 2 | [] | no_license | package com.zhi.snmp.utils;
import com.zhi.snmp.pojo.Result;
import com.zhi.snmp.mib.MibFileParse;
import net.percederberg.mibble.MibValueSymbol;
import org.snmp4j.PDU;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class PDUUtils {
private MibFileParse mibFileParse;
public PDUUtils() {
}
@Autowired
public PDUUtils(MibFileParse mibFileParse) {
this.mibFileParse = mibFileParse;
}
public static PDU createGetPdu(List<String> oidList) {
PDU pdu = new PDU();
pdu.setType(PDU.GET);
for (String oid : oidList) {
pdu.add(new VariableBinding(new OID(oid)));
}
return pdu;
}
public static PDU createGetNextPdu(List<String> oidList) {
PDU pdu = new PDU();
pdu.setType(PDU.GETNEXT);
for (String oid : oidList) {
pdu.add(new VariableBinding(new OID(oid)));
}
return pdu;
}
public static PDU createGetBulkPdu(List<String> oidList) {
PDU pdu = new PDU();
pdu.setType(PDU.GETBULK);
pdu.setMaxRepetitions(10); //must set it, default is 0
pdu.setNonRepeaters(0);
for (String oid : oidList) {
pdu.add(new VariableBinding(new OID(oid)));
}
return pdu;
}
public static PDU createSetPdu(Map<String, String> setMap) {
PDU pdu = new PDU();
pdu.setType(PDU.SET);
for (Map.Entry<String, String> stringStringEntry : setMap.entrySet()) {
pdu.add(new VariableBinding(new OID(stringStringEntry.getKey()), new OctetString(stringStringEntry.getValue())));
}
return pdu;
}
/**
* 打印结果集
* @param response
*/
public void showResponseVbs(PDU response) {
List<? extends VariableBinding> vbs = response.getVariableBindings();
for (VariableBinding vb : vbs) {
MibValueSymbol entity = mibFileParse.getMibValueByOID(vb.getOid().toString());
System.out.println("Name: " + entity.getName() + "\nOID: " + vb + " >> Type: " + vb.getVariable().getSyntaxString());
}
}
/**
* 根据获得的请求体解析结果, 封装到Result对象中
* @param response
* @return
*/
public List<Result> getResults(PDU response) {
List<? extends VariableBinding> allVariable = response.getVariableBindings();
ArrayList<Result> results = new ArrayList<>();
for (VariableBinding per : allVariable) {
MibValueSymbol entity = mibFileParse.getMibValueByOID(per.getOid().toString());
results.add(new Result(entity.getName(),per.getOid().toString(), per.getVariable().toString(), per.getVariable().getSyntaxString()));
}
return results;
}
public void showResponseVbsWithHex(PDU response) {
showResponseVbs(response);
BytesUtils.showHex();
}
}
| true |
0c4c52bfef2b991724e4a1dbe9f242393b91119d | Java | Lalito114/demo | /app/src/main/java/com/szzcs/smartpos/Productos/VentasProductos.java | UTF-8 | 18,115 | 1.9375 | 2 | [] | no_license | package com.szzcs.smartpos.Productos;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.szzcs.smartpos.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.Integer.parseInt;
import org.json.JSONObject;
import org.json.JSONException;
public class VentasProductos extends AppCompatActivity{
//Declaracion de Variables
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
//Declaracion de objetos
Button btnAgregar,btnEnviar, incrementar, decrementar, comprar;
TextView cantidadProducto, txtDescripcion, NumeroProductos, precio;
EditText Producto;
String cantidad;
JSONObject mjason = new JSONObject();
JSONArray myArray = new JSONArray();
String EstacionId;
ListView list;
Integer ProductosAgregados = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ventas_productos);
//instruccion para que aparezca la flecha de regreso
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
comprar=findViewById(R.id.comprar);
comprar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//se asignan valores
final String posicion;
posicion = getIntent().getStringExtra("car");
final String usuarioid;
usuarioid = getIntent().getStringExtra("user");
if (myArray.length()==0 ) //.length() >0)
{
Toast.makeText(getApplicationContext(), "Seleccione al menos uno de los Productos", Toast.LENGTH_LONG).show();
} else {
EnviarProductos(posicion, usuarioid);
}
}
});
btnEnviar = findViewById(R.id.btnEnviar);
btnEnviar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Valida si se ha agregado productos al arreglo
if (myArray.length()==0 ) //.length() >0)
{
Toast.makeText(getApplicationContext(), "Seleccione al menos uno de los Productos", Toast.LENGTH_LONG).show();
} else {
EnviarDatos();
}
}
});
btnAgregar = findViewById(R.id.btnAgregar);
btnAgregar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//procedimiento para agregar un producto al arreglo
AgregarProducto();
//CrearJSON();
}
});
incrementar = findViewById(R.id.incrementar);
incrementar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Aumentar();
}
});
decrementar= findViewById(R.id.decrementar);
decrementar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Decrementar();
}
});
//procedimiento para inicializar variables
CantidadProducto();
//procedimiento que despliega la lista de productos
MostrarProductos();
}
private void EnviarDatos() {
//Si es valido se asignan valores
final String posicion;
posicion = getIntent().getStringExtra("car");
final String usuarioid;
usuarioid = getIntent().getStringExtra("user");
EnviarProductos(posicion, usuarioid);
//Se instancia y se llama a la clase VentaProductos
Intent intent = new Intent(getApplicationContext(), formapagoProducto.class);
//DAtos enviados a formaPago
intent.putExtra("posicion",posicion);
intent.putExtra("usuario",usuarioid);
//SE envía json con los productos seleccionados
//Gson gson = new Gson();
String myJson = myArray.toString();
intent.putExtra("myjson", myArray.toString());
startActivity(intent);
}
private void CantidadProducto() {
cantidadProducto = findViewById(R.id.cantidadProducto);
Producto= findViewById(R.id.Producto);
cantidad = cantidadProducto.toString();
txtDescripcion = findViewById(R.id.txtDescripcion);
precio = findViewById(R.id.precio);
}
private void Aumentar() {
cantidad = cantidadProducto.getText().toString();
int numero = Integer.parseInt(cantidad);
int total = numero + 1;
String resultado = String.valueOf(total);
cantidadProducto.setText(resultado);
}
private void Decrementar() {
cantidad = cantidadProducto.getText().toString();
int numero = Integer.parseInt(cantidad);
if (numero > 1) {
int total = numero - 1;
String resultado = String.valueOf(total);
cantidadProducto.setText(resultado);
}else{
Toast.makeText(getApplicationContext(), "el valor minimo debe ser 1", Toast.LENGTH_LONG).show();
}
};
private void AgregarProducto(){
String resultado = "";
//EditText cantidadProducto = (EditText)getActivity().findViewById();
String ProductoId;
int TotalProducto;
int ProductoIdEntero;
TotalProducto = Integer.parseInt(cantidadProducto.getText().toString());
String PrecioMonto = precio.getText().toString();
Double precioUnitario = Double.valueOf(PrecioMonto);
ProductoId = Producto.getText().toString();
ProductoIdEntero = Integer.parseInt(ProductoId);
if (ProductoId.isEmpty())
{
Toast.makeText(getApplicationContext(), "Seleccione uno de los Productos", Toast.LENGTH_LONG).show();
}
else{
try {
boolean bandera=true;
if (myArray.length()>0 ) {
for (int i = 0; i < myArray.length(); i++) {
try {
JSONObject jsonObject = myArray.getJSONObject(i);
if (jsonObject.has("ProductoId")) {
String valor = jsonObject.getString("ProductoId");
int res = Integer.parseInt(valor);
if (res==ProductoIdEntero){
bandera=false;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
if (bandera==true) {
JSONObject mjason = new JSONObject();
mjason.put("ProductoId", ProductoIdEntero);
mjason.put("Cantidad", TotalProducto);
mjason.put("Precio", precioUnitario);
myArray.put(mjason);
ProductosAgregados = +ProductosAgregados;
}else{
Toast.makeText(getApplicationContext(), "Producto: "+ ProductoId+" cargado anteriormente" , Toast.LENGTH_LONG).show();
}
Producto.setText("");
txtDescripcion.setText("");
cantidadProducto.setText("1");
precio.setText("");
} catch (JSONException error) {
}
}
}
private void MostrarProductos() {
String url = "http://10.2.251.58/CorpogasService/api/islas/productos/estacion/"+EstacionId+"/posicionCargaId/1";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mostarProductor(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.toString(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this.getApplicationContext());
requestQueue.add(stringRequest);
}
private void mostrarProductosExistencias(String response){
//Declaracion de variables
final List<String> ID;
ID = new ArrayList<String>();
final List<String> NombreProducto;
NombreProducto = new ArrayList<String>();
final List<String> PrecioProducto;
PrecioProducto = new ArrayList<>();
final List<String> ClaveProducto;
ClaveProducto = new ArrayList();
//ArrayList<singleRow> singlerow = new ArrayList<>();
try {
JSONArray productos = new JSONArray(response);
for (int i = 0; i <productos.length() ; i++) {
JSONObject p1 = productos.getJSONObject(i);
String idArticulo = p1.getString("IdArticulo");
String DesLarga = p1.getString("DescLarga");
String precio = p1.getString("Precio");
NombreProducto.add("ID: " + idArticulo + " | $"+precio);
ID.add(DesLarga);
PrecioProducto.add(precio);
ClaveProducto.add(idArticulo);
}
} catch (JSONException e) {
e.printStackTrace();
}
final ListAdapterProductos adapterP = new ListAdapterProductos(this, ID, NombreProducto);
list=(ListView)findViewById(R.id.list);
list.setTextFilterEnabled(true);
list.setAdapter(adapterP);
// Agregado click en la lista
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String Descripcion = ID.get(i).toString();
String precioUnitario = PrecioProducto.get(i).toString();
String paso= ClaveProducto.get(i).toString();
Producto.setText(paso);
txtDescripcion.setText(Descripcion);
precio.setText(precioUnitario);
}
});
}
private void mostarProductor(String response) {
//Declaracion de variables
final List<String> ID;
ID = new ArrayList<String>();
final List<String> NombreProducto;
NombreProducto = new ArrayList<String>();
final List<String> PrecioProducto;
PrecioProducto = new ArrayList<>();
final List<String> ClaveProducto;
ClaveProducto = new ArrayList();
//ArrayList<singleRow> singlerow = new ArrayList<>();
try {
JSONArray productos = new JSONArray(response);
for (int i = 0; i <productos.length() ; i++) {
JSONObject p1 = productos.getJSONObject(i);
String idArticulo = p1.getString("IdArticulo");
String DesLarga = p1.getString("DescLarga");
String precio = p1.getString("Precio");
NombreProducto.add("ID: " + idArticulo + " | $"+precio);
ID.add(DesLarga);
PrecioProducto.add(precio);
ClaveProducto.add(idArticulo);
}
} catch (JSONException e) {
e.printStackTrace();
}
final ListAdapterProductos adapterP = new ListAdapterProductos(this, ID, NombreProducto);
list=(ListView)findViewById(R.id.list);
list.setTextFilterEnabled(true);
list.setAdapter(adapterP);
Producto.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//adapterP.getFilter().filter(charSequence);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
// Agregado click en la lista
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String Descripcion = ID.get(i).toString();
String precioUnitario = PrecioProducto.get(i).toString();
String paso= ClaveProducto.get(i).toString();
Producto.setText(paso);
txtDescripcion.setText(Descripcion);
precio.setText(precioUnitario);
}
});
}
private void EnviarProductos(final String posicionCarga, final String Usuarioid) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.2.251.58/CorpogasService/api/ventaProductos/sucursal/1/procedencia/"+posicionCarga+"/tipoTransaccion/1/empleado/"+Usuarioid;
queue = Volley.newRequestQueue(this);
JsonArrayRequest request_json = new JsonArrayRequest(Request.Method.POST, url, myArray,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//Get Final response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.e("Error: ", volleyError.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
// Add headers
return headers;
}
//Important part to convert response to JSON Array Again
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
String responseString;
JSONArray array = new JSONArray();
if (response != null) {
try {
responseString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
//JSONObject obj = new JSONObject(responseString);
//Si es valido se asignan valores
Intent intent = new Intent(getApplicationContext(), formapagoProducto.class);
//DAtos enviados a formaPago
intent.putExtra("posicion",posicionCarga);
intent.putExtra("usuario",Usuarioid);
//SE envía json con los productos seleccionados
//Gson gson = new Gson();
//String myJson = myArray.toString();
//intent.putExtra("myjson", myArray.toString());
startActivity(intent);
//Toast.makeText(getApplicationContext(), "Venta realizada", Toast.LENGTH_LONG).show();
//(array).put(obj);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
//return array;
return Response.success(myArray, HttpHeaderParser.parseCacheHeaders(response));
}
};
queue.add(request_json);
}
// private void CrearJSON() {
// btnAgregar = findViewById(R.id.btnAgregar);
// btnAgregar.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// String ProductoId;
// int TotalProducto = 0;
// TotalProducto = Integer.parseInt(cantidadProducto.getText().toString());
// ProductoId = Producto.getText().toString();
// if (ProductoId.isEmpty())
// {
// Toast.makeText(getApplicationContext(), "Seleccione uno de los Productos", Toast.LENGTH_LONG).show();
// }
// else{
// try {
// mjason.put("cantidad", TotalProducto);
// mjason.put("producto", ProductoId);
// ProductosAgregados = ProductosAgregados +1;
// } catch (JSONException error) {
// }
// }
// }
// });
// }
} | true |
5228955ef0af208e8b05e8f5ea72ef34265d76c7 | Java | jspark0225/web-cell | /app/src/main/java/com/spring/jspark/springwebcell/presenter/CellMemberListPresenter.java | UTF-8 | 4,318 | 2.296875 | 2 | [] | no_license | package com.spring.jspark.springwebcell.presenter;
import com.spring.jspark.springwebcell.R;
import com.spring.jspark.springwebcell.common.Common;
import com.spring.jspark.springwebcell.contract.CellMemberListContract;
import com.spring.jspark.springwebcell.httpclient.OnHttpResponse;
import com.spring.jspark.springwebcell.httpclient.WebCellHttpClient;
import com.spring.jspark.springwebcell.httpclient.model.Attendance;
import com.spring.jspark.springwebcell.httpclient.model.Cell;
import com.spring.jspark.springwebcell.httpclient.model.CellMember;
import com.spring.jspark.springwebcell.httpclient.model.Parish;
import com.spring.jspark.springwebcell.utils.ResourceManager;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by jspark on 2017. 3. 15..
*/
public class CellMemberListPresenter implements CellMemberListContract.Presenter {
CellMemberListContract.View mView;
Cell mCellMemberList = null;
boolean isWorshipAttendanceReceived = false;
boolean isCellAttendanceReceived = false;
public CellMemberListPresenter(String leaderName){
mCellMemberList = WebCellHttpClient.getInstance().getCell(leaderName);
WebCellHttpClient.getInstance().setListener(mHttpResonse);
}
@Override
public void setView(CellMemberListContract.View view) {
mView = view;
}
@Override
public Cell getCellMemberData() {
return mCellMemberList;
}
@Override
public void requestCellMemberAttendanceData(String leaderName, int year, int week) {
WebCellHttpClient.getInstance().getCellMemberAttendance(leaderName, year, week);
}
@Override
public void setAttendanceData(int index, int year, int week, boolean isWorshipAttended, boolean isCellAttended, String reason1, String reason2) {
String reason = "";
if (!reason1.isEmpty() || !reason2.isEmpty())
reason = reason1 + Common.REASON_DELIMETER + reason2;
mCellMemberList.setAttendanceData(index, year, week, isWorshipAttended, isCellAttended, reason);
}
@Override
public void onSubmitButtonClicked(int year, int week) {
isWorshipAttendanceReceived = false;
isCellAttendanceReceived = false;
WebCellHttpClient.getInstance().submitAttendance(year, week);
}
OnHttpResponse mHttpResonse = new OnHttpResponse() {
@Override
public void onLoginResult(boolean isSuccess) {
}
@Override
public void onRequestCellMemberInfoResult(boolean isSuccess, Cell cell) {
}
@Override
public void onRequestCellMemberAttendanceResult(boolean isSuccess, int year, int week, Cell cell) {
// final ArrayList<CellMember> mem = memberInfo;
mCellMemberList = cell;
if (isSuccess) {
mView.updateMemberList(year, week, mCellMemberList);
}
mView.hideRefreshProgressDialog();
}
@Override
public void onSubmitCellAttendanceResult(boolean isSuccess) {
if(isSuccess)
isCellAttendanceReceived = true;
else {
mView.hideSubmitProgressDialog();
mView.showToast(ResourceManager.getInstance().getString(R.string.webcell_submit_failure));
}
if(isCellAttendanceReceived && isWorshipAttendanceReceived){
mView.hideSubmitProgressDialog();
mView.showToast(ResourceManager.getInstance().getString(R.string.webcell_submit_success));
}
}
@Override
public void onSubmitWorshipAttendanceResult(boolean isSuccess) {
if(isSuccess)
isWorshipAttendanceReceived = true;
else {
mView.hideSubmitProgressDialog();
mView.showToast(ResourceManager.getInstance().getString(R.string.webcell_submit_failure));
}
if(isCellAttendanceReceived && isWorshipAttendanceReceived) {
mView.hideSubmitProgressDialog();
mView.showToast(ResourceManager.getInstance().getString(R.string.webcell_submit_success));
}
}
@Override
public void onRequestParishMemberInfoResult(boolean isSuccess, boolean isWorship, Parish parish) {
}
};
} | true |
d419f883f85d046a8d890295226fc4d0f12d93e5 | Java | glockasaur/ShoppingSaverApp | /app/src/main/java/com/zybooks/shoppingsaverapp/DiscountCalc.java | UTF-8 | 1,014 | 2.609375 | 3 | [] | no_license | package com.zybooks.shoppingsaverapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DiscountCalc extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discount);
Button click = findViewById(R.id.button);
}
public void calc(View view){
EditText harga = findViewById(R.id.editText2);
EditText discount = findViewById(R.id.editText);
TextView result = findViewById(R.id.textView3);
double harga1 = Double.parseDouble(harga.getText().toString());
double disc = Double.parseDouble(discount.getText().toString());
double total = harga1 - (harga1*disc);
result.setText("$" + harga1 + " is " + " $" + total + " after a " + disc + " discount");
}
}
| true |
bbd40719d2f6acccb2b99cac8bf457006b994942 | Java | CarvinicioX/basic-backend | /src/main/java/com/sinch/backend/model/User.java | UTF-8 | 628 | 2.171875 | 2 | [] | no_license | package com.sinch.backend.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "users")
@Getter
@Setter
@NoArgsConstructor
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String userName;
private String phoneNumber;
@OneToMany(
mappedBy = "user",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<Sale> sales = new ArrayList<>();
}
| true |
be9219c64a047ae87758cd0bf7a2773bba587670 | Java | Wangxiaobin123/springCloud-Learning | /springCloud-k8s/src/test/java/k8s/deployment/CrdLoadTest.java | UTF-8 | 2,040 | 2.265625 | 2 | [] | no_license | package k8s.deployment;
import cn.hutool.core.io.file.FileReader;
import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinition;
import io.fabric8.kubernetes.api.model.apiextensions.CustomResourceDefinitionList;
import io.fabric8.kubernetes.client.KubernetesClient;
import k8s.util.InitClientTest;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Objects;
/**
* @author: wangshengbin
* @date: 2020/7/10 上午11:34
*/
public class CrdLoadTest {
private static final Logger LOGGER = LoggerFactory.getLogger(CrdLoadTest.class);
private static final String SELDON_CONFIG = "seldon.yml";
@Test
public void testCrd() throws IOException {
try (final KubernetesClient client = InitClientTest.getClient()) {
// List all Custom resources.
log("Listing all current Custom Resource Definitions :");
CustomResourceDefinitionList crdList = client.customResourceDefinitions().list();
crdList.getItems().forEach(crd -> log(crd.getMetadata().getName()));
String seldonConfigPath = Objects.requireNonNull(Fabric8ApiTest.class.getClassLoader().getResource(SELDON_CONFIG)).getPath();
FileReader fileReader;
fileReader = new FileReader(seldonConfigPath);
// Creating a custom resource from yaml
CustomResourceDefinition aCustomResourceDefinition = client.customResourceDefinitions().load(fileReader.getInputStream()).get();
log("Creating CRD...");
client.customResourceDefinitions().create(aCustomResourceDefinition);
log("Updated Custom Resource Definitions: ");
client.customResourceDefinitions().list().getItems().forEach(crd -> log(crd.getMetadata().getName()));
}
}
private static void log(String action, Object obj) {
LOGGER.info("{}: {}", action, obj);
}
private static void log(String action) {
LOGGER.info(action);
}
}
| true |
0c70fc906e6897d355e174f794811d7248bf7040 | Java | Xavier4j/EmotionalAnalysisBackEnd | /src/main/java/club/doyoudo/emotional/service/AnalyseSentimentService.java | UTF-8 | 316 | 1.820313 | 2 | [] | no_license | package club.doyoudo.emotional.service;
import club.doyoudo.emotional.model.AnalysisSentiment;
import java.util.List;
public interface AnalyseSentimentService {
int insertAnalysisSentiment(AnalysisSentiment analysisSentiment);
List<AnalysisSentiment> selectAnalysisSentimentByPhoneId(String phoneId);
}
| true |
cd3b99397d9e5422870572e164a45f3b9c56de6a | Java | DanielDucuara2018/Java_Tests | /test_heritage/src/test/ChildClass.java | UTF-8 | 206 | 2.015625 | 2 | [] | no_license | package test;
/*
* Child classes have to implement abstract methods
* */
public class ChildClass extends AbstractClass{
@Override
public void method1() {
// TODO Auto-generated method stub
}
}
| true |
3b12cbf0ffcb73cad144218752553261ae57deca | Java | rlgomes/dtf | /src/java/com/yahoo/dtf/streaming/RandomInputStream.java | UTF-8 | 3,050 | 3.078125 | 3 | [
"BSD-3-Clause"
] | permissive | package com.yahoo.dtf.streaming;
import java.io.IOException;
import com.yahoo.dtf.exception.ParseException;
import com.yahoo.dtf.util.DTFRandom;
/**
* @dtf.feature Random Stream Type
* @dtf.feature.group DTF Properties
*
* @dtf.feature.desc
* <p>
* The random stream type generates a random sequence of bytes of the size that
* you choose with the optional seed you specify. The actual random data
* follows the details explained in the {@dtf.link Generating Random Data}
* section.
* </p>
* <p>
* Using the random streaming property is as simple as referencing the property
* like so:
* </p>
* <pre>
* ${dtf.stream(random,1024,1234)}
* </pre>
* <p>
* The previous property defines a random stream of data that has 1024 bytes in
* length and has a random seed of 1234. This pseudo random data is generated
* following some rules as explained earlier in this document and can always
* be re-generated using the same seed. This means you only have to store the
* size & seed to be able to do data validation later on and not have to save
* the data itself.
* </p>
*
*/
public class RandomInputStream extends DTFInputStream {
private DTFRandom _random = null;
private int _read = 0;
private long _seed = 0;
public RandomInputStream(long size, String[] args) throws ParseException {
super(size, args);
if ( args.length > 0 ) {
try {
_seed = new Long(args[0]);
} catch (NumberFormatException e ) {
throw new ParseException("Random input argument should be a long not [" +
args + "]");
}
}
_random = new DTFRandom(_seed);
}
@Override
public int read() throws IOException {
if ( _read >= getSize() )
return -1;
_read++;
return _random.nextInt();
}
@Override
public int read(byte[] buffer, int offset, int length) {
if ( _read >= getSize() )
return -1;
int diff = (int)(getSize() - _read);
int onlyread = length;
if ( diff < onlyread )
onlyread = diff;
byte[] bytes = new byte[length];
_random.nextBytes(bytes);
System.arraycopy(bytes,
0,
buffer,
offset,
onlyread);
_read+=onlyread;
return onlyread;
}
@Override
public int read(byte[] buffer) throws IOException {
int length = buffer.length;
if ( buffer.length > (getSize() - _read) )
length = (int)(getSize() - _read);
return read(buffer,0,length);
}
public String getAsString() {
byte[] bytes = new byte[(int)getSize()];
_random.nextBytes(bytes);
return new String(bytes);
}
@Override
public synchronized void reset() throws IOException {
_read = 0;
}
}
| true |
7aa58d9d5fff2d0707c1795cc21c43e24cda149f | Java | raj12789/deepstudio | /src/main/java/in/deepstudio/pvq/service/PvqConcernTypeService.java | UTF-8 | 363 | 1.867188 | 2 | [] | no_license | package in.deepstudio.pvq.service;
import in.deepstudio.pvq.domain.PvqConcernType;
import java.util.List;
public interface PvqConcernTypeService {
PvqConcernType save(PvqConcernType c);
List<PvqConcernType> findAll();
void delete(Long id);
PvqConcernType findOne(Long id);
PvqConcernType findByPvqConcernTypeName(String pvqConcernTypeName);
}
| true |
656263f9fcf3eb2942b0291981f541fd266a677e | Java | Thor7578/HVADFUCKSKERDER | /src/Main.java | UTF-8 | 68 | 1.984375 | 2 | [] | no_license | "Hej, lad os finde ud af om der overhovedet er hul igennem til Git." | true |
fcf617a641e0ae1e4b3336fa9db278c8c0da6594 | Java | Nulldextroyer/ProjetoFinal | /Projeto/src/com/list/ListProduto.java | UTF-8 | 354 | 2.484375 | 2 | [] | no_license | package com.list;
import java.util.ArrayList;
import java.util.List;
import com.classes.*;
public class ListProduto {
List<Produtos> listProdutos = new ArrayList<Produtos>();
public void inserirProdutos(Produtos Produtos) {
listProdutos.add(Produtos);
}
public List<Produtos> getListProdutos() {
return listProdutos;
}
}
| true |
2a4be6f6a81e5a858a94b8d97f1c0e82fa282542 | Java | RainerJava/gl_shop | /gl_shop_datas/src/main/java/com/appabc/datas/service/company/ICompanyAddressService.java | UTF-8 | 821 | 1.9375 | 2 | [] | no_license | /**
*
*/
package com.appabc.datas.service.company;
import com.appabc.bean.pvo.TCompanyAddress;
import com.appabc.common.base.service.IBaseService;
import java.io.Serializable;
import java.util.List;
/**
* @Description : 公司卸货地址SERVICE接口
* @Copyright : GL. All Rights Reserved
* @Company : 江苏国立网络技术有限公司
* @author : 杨跃红
* @version : 1.0
* Create Date : 2014年9月23日 上午11:25:08
*/
public interface ICompanyAddressService extends IBaseService<TCompanyAddress>{
/**
* 设置为默认卸货地址
* @param id
*/
public void setDefault(Serializable id);
/**
* 查询列表,带图片
* @param entity
* @return
*/
public List<TCompanyAddress> queryForListHaveImgs(TCompanyAddress entity);
}
| true |
aa76acb88a9f6336c42e9ac0357db72873007d2e | Java | LeonardoBerlatto/camel-final-fantasy-party-builder | /camel-party-builder/src/main/java/br/com/camel/finalfantasy/partybuilder/camelpartybuilder/utils/HttpEntityUtils.java | UTF-8 | 662 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package br.com.camel.finalfantasy.partybuilder.camelpartybuilder.utils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.util.Collections;
public class HttpEntityUtils {
public static HttpEntity createJSONRequestEntity(Object signedRequest) {
return new HttpEntity(signedRequest, createHeadersJSON());
}
public static HttpHeaders createHeadersJSON() {
return new HttpHeaders() {{
setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
setContentType(MediaType.APPLICATION_JSON);
}};
}
}
| true |
ad3b2d8d1201d6dbed98656cda34015bf0f22f95 | Java | Seping/JQL | /src/main/java/sep/jql/impls/statement/condition/JQLSingleConditionExpression.java | UTF-8 | 943 | 2.5625 | 3 | [] | no_license | package sep.jql.impls.statement.condition;
import sep.jql.interfaces.condition.Condition;
import sep.jql.interfaces.statement.condition.CompositeConditionExpression;
import sep.jql.interfaces.statement.condition.SingleConditionExpression;
public class JQLSingleConditionExpression implements SingleConditionExpression {
private Condition condition;
@Override
public Condition getCondition() {
return condition;
}
@Override
public void setCondition(Condition condition) {
this.condition = condition;
}
@Override
public String toSQLString() {
return condition.toSQLString();
}
@Override
public CompositeConditionExpression compositize() {
CompositeConditionExpression compositeConditionExpression = new JQLCompositeConditionExpression();
compositeConditionExpression.addConditionExpression(this);
return compositeConditionExpression;
}
}
| true |
924525c457441d8a18a9276c08ab6b208404cf4b | Java | kancarec/ws-restful | /ws-restful/src/main/java/com/ws/restful/controller/StudentValidController.java | UTF-8 | 1,199 | 2.34375 | 2 | [] | no_license | package com.ws.restful.controller;
import javax.validation.Valid;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ws.restful.model.Student;
@RestController
@RequestMapping("/api/v1/validation")
public class StudentValidController {
@PostMapping(value = "/addStudent", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
Student addStudent(@Valid @RequestBody final Student student) {
return student;
}
// @ResponseStatus(HttpStatus.BAD_REQUEST)
// @ExceptionHandler(MethodArgumentNotValidException.class)
// public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
// Map<String, String> errors = new HashMap<>();
// ex.getBindingResult().getAllErrors().forEach((error) -> {
// String fieldName = ((FieldError) error).getField();
// String errorMessage = error.getDefaultMessage();
// errors.put(fieldName, errorMessage);
// });
// return errors;
// }
}
| true |
712c5e737ff30e0e27cd72a72ff37bba4e224ba4 | Java | pulumi/pulumi-azure | /sdk/java/src/main/java/com/pulumi/azure/media/StreamingEndpoint.java | UTF-8 | 17,499 | 1.75 | 2 | [
"BSD-3-Clause",
"MPL-2.0",
"Apache-2.0"
] | permissive | // *** WARNING: this file was generated by pulumi-java-gen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package com.pulumi.azure.media;
import com.pulumi.azure.Utilities;
import com.pulumi.azure.media.StreamingEndpointArgs;
import com.pulumi.azure.media.inputs.StreamingEndpointState;
import com.pulumi.azure.media.outputs.StreamingEndpointAccessControl;
import com.pulumi.azure.media.outputs.StreamingEndpointCrossSiteAccessPolicy;
import com.pulumi.azure.media.outputs.StreamingEndpointSkus;
import com.pulumi.core.Output;
import com.pulumi.core.annotations.Export;
import com.pulumi.core.annotations.ResourceType;
import com.pulumi.core.internal.Codegen;
import java.lang.Boolean;
import java.lang.Integer;
import java.lang.String;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
/**
* Manages a Streaming Endpoint.
*
* ## Example Usage
* ```java
* package generated_program;
*
* import com.pulumi.Context;
* import com.pulumi.Pulumi;
* import com.pulumi.core.Output;
* import com.pulumi.azure.core.ResourceGroup;
* import com.pulumi.azure.core.ResourceGroupArgs;
* import com.pulumi.azure.storage.Account;
* import com.pulumi.azure.storage.AccountArgs;
* import com.pulumi.azure.media.ServiceAccount;
* import com.pulumi.azure.media.ServiceAccountArgs;
* import com.pulumi.azure.media.inputs.ServiceAccountStorageAccountArgs;
* import com.pulumi.azure.media.StreamingEndpoint;
* import com.pulumi.azure.media.StreamingEndpointArgs;
* import java.util.List;
* import java.util.ArrayList;
* import java.util.Map;
* import java.io.File;
* import java.nio.file.Files;
* import java.nio.file.Paths;
*
* public class App {
* public static void main(String[] args) {
* Pulumi.run(App::stack);
* }
*
* public static void stack(Context ctx) {
* var exampleResourceGroup = new ResourceGroup("exampleResourceGroup", ResourceGroupArgs.builder()
* .location("West Europe")
* .build());
*
* var exampleAccount = new Account("exampleAccount", AccountArgs.builder()
* .resourceGroupName(exampleResourceGroup.name())
* .location(exampleResourceGroup.location())
* .accountTier("Standard")
* .accountReplicationType("GRS")
* .build());
*
* var exampleServiceAccount = new ServiceAccount("exampleServiceAccount", ServiceAccountArgs.builder()
* .location(exampleResourceGroup.location())
* .resourceGroupName(exampleResourceGroup.name())
* .storageAccounts(ServiceAccountStorageAccountArgs.builder()
* .id(exampleAccount.id())
* .isPrimary(true)
* .build())
* .build());
*
* var exampleStreamingEndpoint = new StreamingEndpoint("exampleStreamingEndpoint", StreamingEndpointArgs.builder()
* .resourceGroupName(exampleResourceGroup.name())
* .location(exampleResourceGroup.location())
* .mediaServicesAccountName(exampleServiceAccount.name())
* .scaleUnits(2)
* .build());
*
* }
* }
* ```
* ### With Access Control
* ```java
* package generated_program;
*
* import com.pulumi.Context;
* import com.pulumi.Pulumi;
* import com.pulumi.core.Output;
* import com.pulumi.azure.core.ResourceGroup;
* import com.pulumi.azure.core.ResourceGroupArgs;
* import com.pulumi.azure.storage.Account;
* import com.pulumi.azure.storage.AccountArgs;
* import com.pulumi.azure.media.ServiceAccount;
* import com.pulumi.azure.media.ServiceAccountArgs;
* import com.pulumi.azure.media.inputs.ServiceAccountStorageAccountArgs;
* import com.pulumi.azure.media.StreamingEndpoint;
* import com.pulumi.azure.media.StreamingEndpointArgs;
* import com.pulumi.azure.media.inputs.StreamingEndpointAccessControlArgs;
* import java.util.List;
* import java.util.ArrayList;
* import java.util.Map;
* import java.io.File;
* import java.nio.file.Files;
* import java.nio.file.Paths;
*
* public class App {
* public static void main(String[] args) {
* Pulumi.run(App::stack);
* }
*
* public static void stack(Context ctx) {
* var exampleResourceGroup = new ResourceGroup("exampleResourceGroup", ResourceGroupArgs.builder()
* .location("West Europe")
* .build());
*
* var exampleAccount = new Account("exampleAccount", AccountArgs.builder()
* .resourceGroupName(exampleResourceGroup.name())
* .location(exampleResourceGroup.location())
* .accountTier("Standard")
* .accountReplicationType("GRS")
* .build());
*
* var exampleServiceAccount = new ServiceAccount("exampleServiceAccount", ServiceAccountArgs.builder()
* .location(exampleResourceGroup.location())
* .resourceGroupName(exampleResourceGroup.name())
* .storageAccounts(ServiceAccountStorageAccountArgs.builder()
* .id(exampleAccount.id())
* .isPrimary(true)
* .build())
* .build());
*
* var exampleStreamingEndpoint = new StreamingEndpoint("exampleStreamingEndpoint", StreamingEndpointArgs.builder()
* .resourceGroupName(exampleResourceGroup.name())
* .location(exampleResourceGroup.location())
* .mediaServicesAccountName(exampleServiceAccount.name())
* .scaleUnits(2)
* .accessControl(StreamingEndpointAccessControlArgs.builder()
* .ipAllows(
* StreamingEndpointAccessControlIpAllowArgs.builder()
* .name("AllowedIP")
* .address("192.168.1.1")
* .build(),
* StreamingEndpointAccessControlIpAllowArgs.builder()
* .name("AnotherIp")
* .address("192.168.1.2")
* .build())
* .akamaiSignatureHeaderAuthenticationKeys(
* StreamingEndpointAccessControlAkamaiSignatureHeaderAuthenticationKeyArgs.builder()
* .identifier("id1")
* .expiration("2030-12-31T16:00:00Z")
* .base64Key("dGVzdGlkMQ==")
* .build(),
* StreamingEndpointAccessControlAkamaiSignatureHeaderAuthenticationKeyArgs.builder()
* .identifier("id2")
* .expiration("2032-01-28T16:00:00Z")
* .base64Key("dGVzdGlkMQ==")
* .build())
* .build())
* .build());
*
* }
* }
* ```
*
* ## Import
*
* Streaming Endpoints can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:media/streamingEndpoint:StreamingEndpoint example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Media/mediaServices/service1/streamingEndpoints/endpoint1
* ```
*
*/
@ResourceType(type="azure:media/streamingEndpoint:StreamingEndpoint")
public class StreamingEndpoint extends com.pulumi.resources.CustomResource {
/**
* A `access_control` block as defined below.
*
*/
@Export(name="accessControl", refs={StreamingEndpointAccessControl.class}, tree="[0]")
private Output</* @Nullable */ StreamingEndpointAccessControl> accessControl;
/**
* @return A `access_control` block as defined below.
*
*/
public Output<Optional<StreamingEndpointAccessControl>> accessControl() {
return Codegen.optional(this.accessControl);
}
/**
* The flag indicates if the resource should be automatically started on creation.
*
*/
@Export(name="autoStartEnabled", refs={Boolean.class}, tree="[0]")
private Output<Boolean> autoStartEnabled;
/**
* @return The flag indicates if the resource should be automatically started on creation.
*
*/
public Output<Boolean> autoStartEnabled() {
return this.autoStartEnabled;
}
/**
* The CDN enabled flag.
*
*/
@Export(name="cdnEnabled", refs={Boolean.class}, tree="[0]")
private Output</* @Nullable */ Boolean> cdnEnabled;
/**
* @return The CDN enabled flag.
*
*/
public Output<Optional<Boolean>> cdnEnabled() {
return Codegen.optional(this.cdnEnabled);
}
/**
* The CDN profile name.
*
*/
@Export(name="cdnProfile", refs={String.class}, tree="[0]")
private Output<String> cdnProfile;
/**
* @return The CDN profile name.
*
*/
public Output<String> cdnProfile() {
return this.cdnProfile;
}
/**
* The CDN provider name. Supported value are `StandardVerizon`,`PremiumVerizon` and `StandardAkamai`
*
*/
@Export(name="cdnProvider", refs={String.class}, tree="[0]")
private Output<String> cdnProvider;
/**
* @return The CDN provider name. Supported value are `StandardVerizon`,`PremiumVerizon` and `StandardAkamai`
*
*/
public Output<String> cdnProvider() {
return this.cdnProvider;
}
/**
* A `cross_site_access_policy` block as defined below.
*
*/
@Export(name="crossSiteAccessPolicy", refs={StreamingEndpointCrossSiteAccessPolicy.class}, tree="[0]")
private Output</* @Nullable */ StreamingEndpointCrossSiteAccessPolicy> crossSiteAccessPolicy;
/**
* @return A `cross_site_access_policy` block as defined below.
*
*/
public Output<Optional<StreamingEndpointCrossSiteAccessPolicy>> crossSiteAccessPolicy() {
return Codegen.optional(this.crossSiteAccessPolicy);
}
/**
* The custom host names of the streaming endpoint.
*
*/
@Export(name="customHostNames", refs={List.class,String.class}, tree="[0,1]")
private Output</* @Nullable */ List<String>> customHostNames;
/**
* @return The custom host names of the streaming endpoint.
*
*/
public Output<Optional<List<String>>> customHostNames() {
return Codegen.optional(this.customHostNames);
}
/**
* The streaming endpoint description.
*
*/
@Export(name="description", refs={String.class}, tree="[0]")
private Output</* @Nullable */ String> description;
/**
* @return The streaming endpoint description.
*
*/
public Output<Optional<String>> description() {
return Codegen.optional(this.description);
}
/**
* The host name of the Streaming Endpoint.
*
*/
@Export(name="hostName", refs={String.class}, tree="[0]")
private Output<String> hostName;
/**
* @return The host name of the Streaming Endpoint.
*
*/
public Output<String> hostName() {
return this.hostName;
}
/**
* The Azure Region where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created.
*
*/
@Export(name="location", refs={String.class}, tree="[0]")
private Output<String> location;
/**
* @return The Azure Region where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created.
*
*/
public Output<String> location() {
return this.location;
}
/**
* Max cache age in seconds.
*
*/
@Export(name="maxCacheAgeSeconds", refs={Integer.class}, tree="[0]")
private Output</* @Nullable */ Integer> maxCacheAgeSeconds;
/**
* @return Max cache age in seconds.
*
*/
public Output<Optional<Integer>> maxCacheAgeSeconds() {
return Codegen.optional(this.maxCacheAgeSeconds);
}
/**
* The Media Services account name. Changing this forces a new Streaming Endpoint to be created.
*
*/
@Export(name="mediaServicesAccountName", refs={String.class}, tree="[0]")
private Output<String> mediaServicesAccountName;
/**
* @return The Media Services account name. Changing this forces a new Streaming Endpoint to be created.
*
*/
public Output<String> mediaServicesAccountName() {
return this.mediaServicesAccountName;
}
/**
* The name which should be used for this Streaming Endpoint maximum length is `24`. Changing this forces a new Streaming Endpoint to be created.
*
*/
@Export(name="name", refs={String.class}, tree="[0]")
private Output<String> name;
/**
* @return The name which should be used for this Streaming Endpoint maximum length is `24`. Changing this forces a new Streaming Endpoint to be created.
*
*/
public Output<String> name() {
return this.name;
}
/**
* The name of the Resource Group where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created.
*
*/
@Export(name="resourceGroupName", refs={String.class}, tree="[0]")
private Output<String> resourceGroupName;
/**
* @return The name of the Resource Group where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created.
*
*/
public Output<String> resourceGroupName() {
return this.resourceGroupName;
}
/**
* The number of scale units. To create a Standard Streaming Endpoint set `0`. For Premium Streaming Endpoint valid values are between `1` and `10`.
*
*/
@Export(name="scaleUnits", refs={Integer.class}, tree="[0]")
private Output<Integer> scaleUnits;
/**
* @return The number of scale units. To create a Standard Streaming Endpoint set `0`. For Premium Streaming Endpoint valid values are between `1` and `10`.
*
*/
public Output<Integer> scaleUnits() {
return this.scaleUnits;
}
/**
* A `sku` block defined as below.
*
*/
@Export(name="skus", refs={List.class,StreamingEndpointSkus.class}, tree="[0,1]")
private Output<List<StreamingEndpointSkus>> skus;
/**
* @return A `sku` block defined as below.
*
*/
public Output<List<StreamingEndpointSkus>> skus() {
return this.skus;
}
/**
* A mapping of tags which should be assigned to the Streaming Endpoint.
*
*/
@Export(name="tags", refs={Map.class,String.class}, tree="[0,1,1]")
private Output</* @Nullable */ Map<String,String>> tags;
/**
* @return A mapping of tags which should be assigned to the Streaming Endpoint.
*
*/
public Output<Optional<Map<String,String>>> tags() {
return Codegen.optional(this.tags);
}
/**
*
* @param name The _unique_ name of the resulting resource.
*/
public StreamingEndpoint(String name) {
this(name, StreamingEndpointArgs.Empty);
}
/**
*
* @param name The _unique_ name of the resulting resource.
* @param args The arguments to use to populate this resource's properties.
*/
public StreamingEndpoint(String name, StreamingEndpointArgs args) {
this(name, args, null);
}
/**
*
* @param name The _unique_ name of the resulting resource.
* @param args The arguments to use to populate this resource's properties.
* @param options A bag of options that control this resource's behavior.
*/
public StreamingEndpoint(String name, StreamingEndpointArgs args, @Nullable com.pulumi.resources.CustomResourceOptions options) {
super("azure:media/streamingEndpoint:StreamingEndpoint", name, args == null ? StreamingEndpointArgs.Empty : args, makeResourceOptions(options, Codegen.empty()));
}
private StreamingEndpoint(String name, Output<String> id, @Nullable StreamingEndpointState state, @Nullable com.pulumi.resources.CustomResourceOptions options) {
super("azure:media/streamingEndpoint:StreamingEndpoint", name, state, makeResourceOptions(options, id));
}
private static com.pulumi.resources.CustomResourceOptions makeResourceOptions(@Nullable com.pulumi.resources.CustomResourceOptions options, @Nullable Output<String> id) {
var defaultOptions = com.pulumi.resources.CustomResourceOptions.builder()
.version(Utilities.getVersion())
.build();
return com.pulumi.resources.CustomResourceOptions.merge(defaultOptions, options, id);
}
/**
* Get an existing Host resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state
* @param options Optional settings to control the behavior of the CustomResource.
*/
public static StreamingEndpoint get(String name, Output<String> id, @Nullable StreamingEndpointState state, @Nullable com.pulumi.resources.CustomResourceOptions options) {
return new StreamingEndpoint(name, id, state, options);
}
}
| true |
bece50b0651674f40a6988157f3bbfbe121d265b | Java | FullStackNet/kickstart | /kickstart-platform/src/main/java/platform/webservice/ui/html/HTMLBUTTON.java | UTF-8 | 511 | 2.28125 | 2 | [] | no_license | package platform.webservice.ui.html;
import platform.webservice.ui.util.Attribute;
public class HTMLBUTTON extends INPUT {
public HTMLBUTTON() {
this(null,null,null);
}
public HTMLBUTTON(String id,String className) {
this(id,null,className);
}
public HTMLBUTTON(String id, String name,String className) {
super(id,name,className);
addAttribute(new Attribute("type", "submit"));
}
@Override
public String getTag() {
// TODO Auto-generated method stub
return "button";
}
}
| true |
916d09a3305abf18cbaa60bdcb4e186e9889efe0 | Java | somnath1102/ddd | /src/com/thoughtworks/domain/valueobjects/Context.java | UTF-8 | 883 | 2.71875 | 3 | [] | no_license | package com.thoughtworks.domain.valueobjects;
import com.thoughtworks.domain.entity.Transaction;
/**
* Is mutable.
* Holds the input and transaction.
* Transaction entity is populated from this context by the expressions.
* output field is only used for the roman value calculation.
*
* @author somnath
*
*/
public class Context {
private String input;
private long output;
private final Transaction transaction;
public Context(String input, Transaction transaction) {
this.input = input;
this.transaction = transaction;
}
public String getInput() {
return input;
}
public void setInput(String input) {
this.input = input;
}
public long getOutput() {
return output;
}
public void setOutput(long output) {
this.output = output;
}
public Transaction getTransaction() {
return transaction;
}
}
| true |
e2987b21e0402ac9c13b16c378d225ff75cd1a57 | Java | topicanica/N26-Coding-Challenge | /transactions/src/main/java/com/challenge/transactions/services/TransactionService.java | UTF-8 | 674 | 2.171875 | 2 | [] | no_license | package com.challenge.transactions.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.challenge.transactions.models.Transaction;
import com.challenge.transactions.repositories.TransactionRepository;
@Component
public class TransactionService {
@Autowired
private TransactionRepository transactionRepository;
public List<Transaction> getAllValidTransactions() {
return transactionRepository.findAllTransactionsYoungerThan60SecondsFromNow();
}
public void saveTransaction(Transaction transaction) {
transactionRepository.saveTransaction(transaction);
}
}
| true |
37f6192084601840490b08b41f5957836bff28ea | Java | ziang-info/ZaSpringAOP | /src/main/java/info/ziang/aop/ITalk.java | UTF-8 | 161 | 2.34375 | 2 | [
"MIT"
] | permissive | package info.ziang.aop;
/**
* 抽象主体角色:声明了真实主体和抽象主体的共同接口
*/
public interface ITalk{
void talk(String msg);
} | true |
aa0d41faa8b2375b2bc90f1556245a02dc0fe9ff | Java | PaaS-TA/PAAS-TA-CAAS-API | /src/main/java/org/paasta/caas/api/common/model/CommonAddresses.java | UTF-8 | 247 | 1.523438 | 2 | [
"Apache-2.0"
] | permissive | package org.paasta.caas.api.common.model;
import lombok.Data;
/**
* Common Addresses Model 클래스
*
* @author REX
* @version 1.0
* @since 2018.08.13
*/
@Data
class CommonAddresses {
private String ip;
private String nodeName;
}
| true |
8dcc366be4f3a307a8d350adb6a7d0a49b95aeed | Java | cchenyh/SnugAlpha | /gethepost.java | UTF-8 | 6,183 | 2.59375 | 3 | [] | no_license | public void LoginByGet() {
new Thread(new Runnable() {
@Override
public void run() {
try {
//我们请求的数据:
// String data = "account=" + URLEncoder.encode(name, "UTF-8") +
// "&password=" + URLEncoder.encode(passwd, "UTF-8");
//get请求的url
URL url=new URL( "https://api.shisanshui.rtxux.xyz/rank");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式,请求超时信息
conn.setRequestMethod("GET");
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
// //设置运行输入,输出:
// conn.setDoOutput(true);
// conn.setDoInput(true);
// //Post方式不能缓存,需手动设置为false
// conn.setUseCaches(false);
//
// //设置请求的头信息
// conn.setRequestProperty("staffid",StaffId ); //当前请求用户StaffId
// conn.setRequestProperty("timestamp", ApiHelper.GetTimeStamp()); //发起请求时的时间戳(单位:毫秒)
// conn.setRequestProperty("nonce", ApiHelper.GetRandom()); //发起请求时的随机数
//开启连接
conn.connect();
InputStream inputStream=null;
BufferedReader reader=null;
//如果应答码为200的时候,表示成功的请求带了,这里的HttpURLConnection.HTTP_OK就是200
if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
//获得连接的输入流
inputStream=conn.getInputStream();
//转换成一个加强型的buffered流
reader=new BufferedReader(new InputStreamReader(inputStream));
//把读到的内容赋值给result
String result = reader.readLine();
msg = result;
Log.d("Ranking", "Result:" + result);
// JSONObject json_test = new JSONObject(result);
//打印json 数据
// Log.e("json", json_test.get("player_id").toString());
// Log.e("json", json_test.get("score").toString());
// Log.e("json", json_test.get("name").toString());
}
//关闭流和连接
reader.close();
inputStream.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void registerPost() {
//请求
new Thread(new Runnable() {
@Override
public void run() {
try {
// 0.相信证书
// 1. 获取访问地址URL
URL url = new URL("https://api.shisanshui.rtxux.xyz/auth/register");
// 2. 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 3. 设置请求参数等
// 请求方式
connection.setRequestMethod("POST");
// 超时时间
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
// 设置是否输出
connection.setDoOutput(true);
// 设置是否读入
connection.setDoInput(true);
// 设置是否使用缓存
connection.setUseCaches(false);
// 设置此 HttpURLConnection 实例是否应该自动执行 HTTP 重定向
connection.setInstanceFollowRedirects(true);
// 设置使用标准编码格式编码
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");//json格式
// 连接
connection.connect();
// 4. 处理输入输出
// 写入参数到请求中
//Content-Type:application/json;charset=UTF-8 对应json格式参数数据
String params = "{" +
"\"username\":\"" + login_name.getText() + "\"" + "," +
"\"password\":\"" + login_password.getText() + "\"" +
"}";
Log.d("BaoFuPay", "RiskManagerParams:" + params);
OutputStream out = connection.getOutputStream();
out.write(params.getBytes());
out.flush();
out.close();
// 从连接中读取响应信息
String msg = "";
int code = connection.getResponseCode();
if (code == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
msg += line + "\n";
}
Log.d("BaoFuPay", "Result:" + msg);
reader.close();
}
// 5. 断开连接
connection.disconnect();
//loading
// 处理结果
Log.d("BaoFuPay", "RiskManagerResult:" + msg);
} catch (Exception e) {
//loading
Log.e("BaoFuPay", "RiskManager:" + e);
}
}
}).start();
} | true |
7d1ff235d9b82ba6b6323f3488cadc27a0bf38e4 | Java | rafkub90/Labki3-4 | /src/com/company/Main.java | UTF-8 | 1,445 | 3.21875 | 3 | [] | no_license | package com.company;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String n = "";
try {
System.out.print("podaj cene samochodu: ");
n=scanner.nextLine();
int cena = Integer.parseInt(n);
n="";
System.out.print("podaj moc samochodu: ");
n=scanner.nextLine();
int moc = Integer.parseInt(n);
n="";
System.out.print("podaj spalanie samochodu: ");
n=scanner.nextLine();
double spalanie = Double.parseDouble(n);
n="";
System.out.print("podaj kolor samochodu: ");
n=scanner.nextLine();
String kolor = n;
samochod vw = new samochod(moc, cena,kolor,spalanie);
System.out.println("VW cena: "+vw.cena);
System.out.println("Koszt przy 234 km: "+vw.paliwo(100,4.56));
PrintWriter file = new PrintWriter("plik.txt");
file.println("Cena: "+cena+", Moc: "+moc+"spalanie: "+spalanie+"Koszt przy 100 km: "+vw.paliwo(100,4.56));
file.close();
}
catch (Exception e) {
System.out.println("podales zle dane");
System.out.println(e.getMessage());
System.out.println(e.getClass());
}
}
} | true |
dc73d342333a9cb421627ad076d1949d42429378 | Java | sviatiq/java-core | /src/lesson1/task2/Workers.java | UTF-8 | 1,506 | 3.171875 | 3 | [] | no_license | package lesson1.task2;
public class Workers {
private String workerName;
private String workerSurname;
private int workerExperience;
private String position;
public Workers() {
}
public Workers(String workerName, String workerSurname, int workerExperience, String position) {
this.workerName = workerName;
this.workerSurname = workerSurname;
this.workerExperience = workerExperience;
this.position = position;
}
public String getWorkerName() {
return workerName;
}
public void setWorkerName(String workerName) {
this.workerName = workerName;
}
public String getWorkerSurname() {
return workerSurname;
}
public void setWorkerSurname(String workerSurname) {
this.workerSurname = workerSurname;
}
public int getWorkerExperience() {
return workerExperience;
}
public void setWorkerExperience(int workerExperience) {
this.workerExperience = workerExperience;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public String toString() {
return "Workers{" +
"workerName='" + workerName + '\'' +
", workerSurname='" + workerSurname + '\'' +
", workerExperience=" + workerExperience +
", position='" + position + '\'' +
'}';
}
}
| true |
c8654431aa363ac304cb873e94f0e6c6daf9f648 | Java | lcycat/Cpsc410-Code-Trip | /temp/src/minecraft/net/minecraft/src/GameWindowListener.java | UTF-8 | 583 | 1.976563 | 2 | [] | no_license | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode fieldsfirst
package net.minecraft.src;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.PrintStream;
public final class GameWindowListener extends WindowAdapter
{
public GameWindowListener()
{
}
public void windowClosing(WindowEvent p_windowClosing_1_)
{
System.err.println("Someone is closing me!");
System.exit(1);
}
}
| true |
e86271d3386e0c997384ff1537366cd644f0a77f | Java | Eieyron/CMSC137_Wild_Ones | /proto/Obstacles.java | UTF-8 | 2,058 | 3.03125 | 3 | [] | no_license | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Obstacles extends JPanel implements GameObject{
int block;
int xPos;
int yPos;
int width;
int height;
Obstacles(int num){
this.block=num;
createObstacle(this.block);
this.setBackground(Color.BLACK);
this.setOpaque(false);
}
public int getX(){
return this.xPos;
}
public int getY(){
return this.yPos;
}
public int getWidth(){
return this.width;
}
public int getHeight(){
return this.height;
}
public Rectangle getRectangle(){
return new Rectangle(new Point(this.xPos, this.yPos), new Dimension(this.width,this.height));
}
public boolean intersects(GameObject o){
return this.getRectangle().intersects(o.getRectangle());
}
public void render(int a, int b, int c, int d){
this.setPreferredSize(new Dimension(c,d));
this.xPos = a;
this.yPos = b;
this.width = c;
this.height = d;
}
public void createObstacle(int blk){
switch(blk){
case 1:
render(0,466,277,87);
break;
case 2:
render(344,373,119,190);
break;
case 3:
render(607,347,124,194);
break;
case 4:
render(524,411,84,131);
break;
case 5:
render(0,208,200,24);
break;
case 6:
render(78,60,252,20);
break;
case 7:
render(377,124,64,40);
break;
// case 8:
// render(193,269,78,78);
// break;
case 9:
render(462,248,140,17);
break;
case 10:
render(650,320,82,28);
break;
// case 11:
// render(644,294,27,27);
// break;
case 12:
render(252,252,127,19);
break;
case 13:
render(584,156,127,9);
break;
case 14:
render(500,220,60,30);
break;
case 15:
render(500,190,30,30);
break;
case 16:
render(44,436,90,30);
break;
case 17:
render(40,180,30,30);
break;
case 18:
render(704,292,27,27);
break;
case 19:
render(183,438,90,30);
break;
case 20:
render(214,406,60,30);
break;
case 21:
render(244,376,30,30);
break;
default:
break;
}
}
} | true |
233609589ab23b7eb58c1a8e7b619e0b30ab9536 | Java | jurniores/reporJava | /Teste/src/teste/Teste.java | UTF-8 | 892 | 2.75 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package teste;
/**
*
* @author Antonio
*/
public class Teste {
private int marcha;
private double velocidade;
private String cor;
private int aro;
public void setMarcha(int marcha){
this.marcha = marcha;
}
public int getMarcha(){
return marcha;
}
public double getVelocidade(){
return velocidade;
}
public void setVelocidade (int velocidade){
this.velocidade = velocidade;
}
public static void main(String[] args) {
Teste bicicleta = new Teste();
bicicleta.setMarcha(3);
System.out.println("Marcha "+ biciclegvta.getMarcha());
}
}
| true |
ff59bf2bf5a8c30e8ebbddb8ee4ea7c04fedcd1c | Java | Dmitryyyyo/java_1_tuesday_2020_online | /src/main/java/student_dmitrijs_jasvins/lesson_12/day_3/task_19/WrongUserInputHandlingDemo.java | UTF-8 | 663 | 2.953125 | 3 | [] | no_license | package student_dmitrijs_jasvins.lesson_12.day_3.task_19;
import java.util.InputMismatchException;
import java.util.Scanner;
import teacher.codereview.CodeReview;
@CodeReview(approved = true)
public class WrongUserInputHandlingDemo {
public static void main(String[] args) {
while (true) {
try {
System.out.println("Please enter number: ");
Scanner scr = new Scanner(System.in);
int number = scr.nextInt();
break;
} catch (InputMismatchException exception) {
System.out.println("It's not a number! Try again!");
}
}
}
} | true |
ae7e3a5d9d4a1f2901ea76882e8e7101080ceeb2 | Java | vctrmarques/interno-rh-sistema | /rhServer/src/main/java/com/rhlinkcon/model/UnidadePagamentoEnum.java | UTF-8 | 595 | 2.578125 | 3 | [] | no_license | package com.rhlinkcon.model;
public enum UnidadePagamentoEnum {
POR_HORA("Por Hora"), POR_DIA("Por Dia"), POR_SEMANA("Por Semana"), POR_QUINZENA("Por Quinzena"),
POR_MES("Por Mês"), POR_TAREFA("Por Tarefa"), NAO_APLICAVEL("Não Aplicável");
private String label;
private UnidadePagamentoEnum(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public static UnidadePagamentoEnum getEnumByString(String str) {
for (UnidadePagamentoEnum e : UnidadePagamentoEnum.values()) {
if (str.equals(e.getLabel()))
return e;
}
return null;
}
}
| true |
746e2d4afb70f26aa7cf520765a4191f479f28dd | Java | 499196191/label-platform | /src/main/java/com/fhpt/imageqmind/objects/vo/DbInfoVo.java | UTF-8 | 1,224 | 2.140625 | 2 | [] | no_license | package com.fhpt.imageqmind.objects.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 数据源信息
* @author Marty
*/
@ApiModel(description= "数据库信息")
@Data
public class DbInfoVo {
@ApiModelProperty(name="id",value = "主键id,新增时可以不传递", required = false)
private long id;
@ApiModelProperty(value = "连接名称")
private String connectName;
@ApiModelProperty(value = "数据库IP")
private String ip;
@ApiModelProperty(value = "数据库端口")
private Integer port;
@ApiModelProperty(value = "数据库用户名")
private String userName;
@ApiModelProperty(value = "数据库密码")
private String password;
@ApiModelProperty(value = "数据库名称")
private String dbName;
@ApiModelProperty(value = "数据库表名")
private String tableName;
@ApiModelProperty(value = "数据库schema")
private String schema;
@ApiModelProperty(value = "创建时间")
private String createTime;
@ApiModelProperty(value = "更新时间")
private String updateTime;
@ApiModelProperty(value = "创建人")
private String createdBy;
}
| true |
454b977e3cee6b0469e4de0036d917ed7e60bab1 | Java | appelqvist/mongodb_beaver_coffee | /src/main/java/Client.java | UTF-8 | 16,010 | 2.875 | 3 | [] | no_license | import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
/**
* Created by Andréas Appelqvist on 2017-05-15.
*/
public class Client {
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
private Customer customerCollection;
private Employee employeeCollection;
private Store storeCollection;
private Order orderCollection;
public Client(String host) {
//instance the client
mongoClient = new MongoClient(host);
//open database
mongoDatabase = mongoClient.getDatabase("BeaverCoffee");
//Setting up the different collections as classes.
customerCollection = new Customer(mongoDatabase);
employeeCollection = new Employee(mongoDatabase);
storeCollection = new Store(mongoDatabase);
orderCollection = new Order(mongoDatabase);
}
/**
* This is where the program in running
*/
public void start() {
while (true) {
int choice;
choice = Integer.parseInt(JOptionPane.showInputDialog("Pick one of the alternative: \n" +
"1: Employee \n" +
"2: Customer \n" +
"3: Store \n" +
"0: Exit"));
switch (choice) {
case 1:
employeePick();
break;
case 2:
customerPick();
break;
case 3:
storePick();
break;
case 9:
break;
case 0:
System.exit(0);
break;
default:
System.exit(0);
break;
}
}
}
private void storePick() {
while (true) {
int choice = Integer.parseInt(JOptionPane.showInputDialog("1: Add new store\n" +
"2: Bla bla\n" +
"0: Exit store section "));
switch (choice) {
case 1:
String city = JOptionPane.showInputDialog("City where the store is located:");
String street = JOptionPane.showInputDialog("Street:");
String country = JOptionPane.showInputDialog("Country");
String zip = JOptionPane.showInputDialog("Zip-code:");
String currency = JOptionPane.showInputDialog("Currency used in store:");
storeCollection.addStore(currency, country, street, city, zip);
break;
case 2:
break;
case 0:
return;
default:
break;
}
}
}
private void customerPick() {
while (true) {
int choice = Integer.parseInt(JOptionPane.showInputDialog("" +
"Do purchase as:\n" +
"1: New Customer\n" +
"2: Old Customer \n" +
"0: Exit customer"));
switch (choice) {
case 0:
return;
case 1:
doPurchase(false);
break;
case 2:
doPurchase(true);
break;
default:
break;
}
}
}
private ObjectId addCustomerPick() {
ObjectId newCustomerId = customerCollection.addCustomer();
int choice = Integer.parseInt(JOptionPane.showInputDialog("Want to be beavermember?\n" +
"1: YES\n" +
"2: NO"));
if(choice == 1){
addBeaverMemberPick(newCustomerId);
}
return newCustomerId;
}
private void addBeaverMemberPick(ObjectId customer){
String ssn = JOptionPane.showInputDialog("Customers SSN:");
String occupation = JOptionPane.showInputDialog("Customers occupation");
ObjectId storeid = pickStoreID();
String city = JOptionPane.showInputDialog("Customers city:");
String street = JOptionPane.showInputDialog("Customers street:");
String country = JOptionPane.showInputDialog("Customers country:");
customerCollection.addBeaverClub(customer,ssn,occupation,storeid,city,street,country);
}
private void doPurchase(boolean old){
ObjectId customerID;
if(old){
LinkedList<String> allids = customerCollection.getAllCustomers();
String s = "Pick your id:\n";
int i = 0;
for(String id : allids){
s += i+" : " + id + "\n";
i ++;
}
int choice;
do{
choice = Integer.parseInt(JOptionPane.showInputDialog(s));
}while (choice < 0 || choice > allids.size());
customerID = new ObjectId(allids.get(choice));
}
else{
customerID = addCustomerPick();
}
JOptionPane.showMessageDialog(null, "You have customerID:"+customerID.toString()+"\n" +
"Continue!");
orderPick(pickStoreID(), customerID);
}
private void orderPick(ObjectId storeID, ObjectId customerID){
int choice;
LinkedList<Document> products = new LinkedList<>();
do {
Document product = productPick();
products.add(product);
choice = Integer.parseInt(JOptionPane.showInputDialog("Buy another product?\n" +
"1: YES!\n" +
"2: NO"));
}while(choice != 2);
Document order = new Document("storeID", storeID)
.append("customerID", customerID)
.append("employeeID", pickEmployeeID(storeID))
.append("products", products);
String orderStr;
int c = 0;
do{
orderStr = "This is your order:\n";
for(Document p : products){
orderStr += p.get("name")+"\n";
}
orderStr += "Ask employee to change current order? Or are you happy with the order?\n" +
"1 : I want to change my order\n" +
"2 : Remove product from order \n"+
"3 : This looks good! I want to finalise my order! Take my money!";
c = Integer.parseInt(JOptionPane.showInputDialog(orderStr));
if(c == 1){
products = changeOrderProduct(products);
order.append("products", products);
}else if(c == 2){
products = removeProductFromOrder(products);
order.append("products", products);
}
}while (c != 3);
//Dra av från stock.
storeCollection.removeFromStock(storeID, products);
String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
order.append("date", today);
orderCollection.addOrder(order);
}
private LinkedList<Document> removeProductFromOrder(LinkedList<Document> productlist){
String s = "Select the one you want to remove:\n";
for(int i = 0; i < productlist.size(); i++){
s += i + " : " + productlist.get(i).get("name")+"\n";
}
int index = Integer.parseInt(JOptionPane.showInputDialog(s));
productlist.remove(index);
return productlist;
}
private LinkedList<Document> changeOrderProduct(LinkedList<Document> productlist){
String s = "Select the one you want to change:\n";
for(int i = 0; i < productlist.size(); i++){
s += i + " : " + productlist.get(i).get("name") + "\n";
}
int index = Integer.parseInt(JOptionPane.showInputDialog(s));
productlist.set(index, productPick());
return productlist;
}
private Document productPick() {
Document product = new Document();
LinkedList<Document> list = new LinkedList<>();
int choice;
do {
choice = Integer.parseInt(JOptionPane.showInputDialog("Pick a product you want to add to order:\n" +
"1: Espresso\n" +
"2: Latte\n" +
"3: Cappuccino\n" +
"4: Hot Coco\n" +
"5: Brewed Coffee\n"));
} while (choice <= 0 || choice > 5);
String name = "-1";
int price = -1;
int milk = -1;
int syrup = -1;
int bean = -1;
switch (choice) {
case 1:
name = "Espresso";
bean = 1;
price = 10;
break;
case 2:
name = "Latte";
bean = 1;
price = 15;
milk = milkPick();
syrup = syrupPick();
break;
case 3:
name = "Cappuccino";
bean = 1;
price = 15;
milk = milkPick();
syrup = syrupPick();
break;
case 4:
name = "Hot coco";
bean = 4;
price = 25;
milk = milkPick();
syrup = syrupPick();
break;
case 5:
name = "Brewed Coffee";
bean = beanPick();
price = 5;
milk = milkPick();
syrup = syrupPick();
break;
}
list.add(new Document("ingredientsID", bean));
if(milk != -1){
list.add(new Document("ingredientsID", milk));
}
if(syrup != -1){
list.add(new Document("ingredientsID", syrup));
price += 2;
}
product.append("name", name)
.append("price", price)
.append("ingredients", list);
return product;
}
private int milkPick() {
int choice;
choice = Integer.parseInt(JOptionPane.showInputDialog("Any milk?\n" +
"1: Skim milk\n" +
"2: Soy milk\n" +
"3: Whole milk\n" +
"4: 2% milk\n" +
"0: No milk"));
switch (choice) {
case 0:
return -1;
case 1:
return 5;
case 2:
return 6;
case 3:
return 7;
case 4:
return 8;
default:
return -1;
}
}
private int syrupPick() {
int choice;
choice = Integer.parseInt(JOptionPane.showInputDialog("Want to add syrup? (can cost extra)\n" +
" 1: Vanilla \n" +
"2: Caramel \n" +
"3: Irish \n" +
"0: No sirap"));
switch (choice) {
case 0:
return -1;
case 1:
return 9;
case 2:
return 10;
case 3:
return 11;
default:
return -1;
}
}
private int beanPick() {
int choice;
choice = Integer.parseInt(JOptionPane.showInputDialog("1: French roast\n" +
"2: Light roast\n"));
switch (choice) {
case 0:
return -1;
case 1:
return 2;
case 2:
return 3;
default:
return 3;
}
}
private void employeePick() {
while (true) {
int choice;
choice = Integer.parseInt(JOptionPane.showInputDialog("1: Add employee\n" +
"2: Set comment on a employee\n" +
"0: Exit employee"));
switch (choice) {
case 0:
start();
break;
case 1:
//Method??
String name = JOptionPane.showInputDialog("Choose name:");
String ssn = JOptionPane.showInputDialog("Choose SSN:");
String salary = JOptionPane.showInputDialog("Choose salary:");
int discount = Integer.parseInt(JOptionPane.showInputDialog("Choose discount:"));
String position = JOptionPane.showInputDialog("Choose position:");
String startDate = JOptionPane.showInputDialog("Choose start date:\n" +
"Format: YYYY-MM-DD");
String endDate = JOptionPane.showInputDialog("Choose end date:\n" +
"Format: YYYY-MM-DD");
String workingTime = JOptionPane.showInputDialog("Choose working time (%):");
employeeCollection.addEmployee(name, ssn, salary, discount, position, startDate, endDate, workingTime, pickStoreID());
break;
case 2:
ObjectId store = pickStoreID();
LinkedList<Document> employees = employeeCollection.getEmployees(store);
String select = "Select one employee:\n";
int i = 0;
for (Document d : employees) {
select += i + " : " + d.get("name") + "\n";
i++;
}
int c;
do {
c = Integer.parseInt(JOptionPane.showInputDialog(select));
} while (c < 0 || c > employees.size());
ObjectId employeeID = employees.get(c).getObjectId("_id");
String msg = JOptionPane.showInputDialog("Write your msg:");
String date = JOptionPane.showInputDialog("Todays date? : ");
String manager = JOptionPane.showInputDialog("The managers name (Your name)");
employeeCollection.addComment(employeeID, msg, date, manager);
break;
}
}
}
private ObjectId pickEmployeeID(ObjectId storeID){
String[] names;
ObjectId[] ids;
LinkedList<Document> allEmployees = employeeCollection.getEmployees(storeID);
names = new String[allEmployees.size()];
ids = new ObjectId[allEmployees.size()];
Document d;
for (int i = 0; i < names.length; i++) {
d = allEmployees.removeFirst();
names[i] = String.valueOf(d.get("name"));
ids[i] = (ObjectId) d.get("_id");
}
int id = -1;
do {
String out = "Select id of employee you want to handle your order:\n";
for (int i = 0; i < names.length; i++) {
out += i + ": " + names[i] + "\n";
}
id = Integer.parseInt(JOptionPane.showInputDialog(out));
} while (id < 0 || id > names.length);
return ids[id];
}
private ObjectId pickStoreID() {
String[] storeCityStreet;
ObjectId[] ids;
LinkedList<Document> allStores = storeCollection.getAllStores();
storeCityStreet = new String[allStores.size()];
ids = new ObjectId[allStores.size()];
Document d;
for (int i = 0; i < storeCityStreet.length; i++) {
d = allStores.removeFirst();
storeCityStreet[i] = String.valueOf(d.get("location"));
ids[i] = (ObjectId) d.get("_id");
}
int id = -1;
do {
String out = "Select id of store:\n";
for (int i = 0; i < storeCityStreet.length; i++) {
out += i + ": " + storeCityStreet[i] + "\n";
}
id = Integer.parseInt(JOptionPane.showInputDialog(out));
} while (id < 0 || id > storeCityStreet.length);
return ids[id];
}
}
| true |
5f6fa495923ec027e2d86772d9c2cdf7f4231cc0 | Java | carlosmast23/codefac-lite | /workspace/servidor-interfaz/src/main/java/ec/com/codesoft/codefaclite/servidorinterfaz/other/session/SessionCodefac.java | UTF-8 | 4,669 | 1.953125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ec.com.codesoft.codefaclite.servidorinterfaz.other.session;
import ec.com.codesoft.codefaclite.servidorinterfaz.controller.ServiceFactory;
import ec.com.codesoft.codefaclite.servidorinterfaz.entity.Empresa;
import ec.com.codesoft.codefaclite.servidorinterfaz.entity.ParametroCodefac;
import ec.com.codesoft.codefaclite.servidorinterfaz.entity.Perfil;
import ec.com.codesoft.codefaclite.servidorinterfaz.entity.Sucursal;
import ec.com.codesoft.codefaclite.servidorinterfaz.entity.Usuario;
import ec.com.codesoft.codefaclite.servidorinterfaz.enumerados.ModuloCodefacEnum;
import ec.com.codesoft.codefaclite.servidorinterfaz.enumerados.TipoLicenciaEnum;
import java.io.Serializable;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Carlos
*/
public class SessionCodefac implements SessionCodefacInterface,Serializable{
protected Usuario usuario;
protected Empresa empresa;
protected Sucursal matriz;
protected Sucursal sucursal;
protected Map<String,ParametroCodefac> parametrosCodefac;
protected List<Perfil> perfiles;
protected TipoLicenciaEnum tipoLicenciaEnum;
protected String usuarioLicencia;
protected Licencia licencia;
protected List<ModuloCodefacEnum> modulos;
public SessionCodefac() {
}
public SessionCodefac(Usuario usuario, Empresa empresa) {
this.usuario = usuario;
this.empresa = empresa;
}
@Override
public Usuario getUsuario() {
return this.usuario;
}
@Override
public Empresa getEmpresa() {
return this.empresa;
}
@Override
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
@Override
public void setEmpresa(Empresa empresa) {
this.empresa = empresa;
}
@Override
public Map<String,ParametroCodefac> getParametrosCodefac() {
try {
//return parametrosCodefac;
return ServiceFactory.getFactory().getParametroCodefacServiceIf().getParametrosMap(empresa);
} catch (RemoteException ex) {
Logger.getLogger(SessionCodefac.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@Override
public void setParametrosCodefac(Map<String,ParametroCodefac> parametrosCodefac) {
this.parametrosCodefac = parametrosCodefac;
}
public void setPerfiles(List<Perfil> perfiles) {
this.perfiles = perfiles;
}
@Override
public List<Perfil> getPerfiles() {
return perfiles;
}
@Override
public boolean verificarExistePerfil(String nombre) {
for (Perfil perfil : perfiles) {
if(perfil.getNombre().equals(nombre))
{
return true;
}
}
return false;
}
public void setTipoLicenciaEnum(TipoLicenciaEnum tipoLicenciaEnum) {
this.tipoLicenciaEnum = tipoLicenciaEnum;
}
@Override
public TipoLicenciaEnum getTipoLicenciaEnum() {
return tipoLicenciaEnum;
}
public void setUsuarioLicencia(String usuarioLicencia) {
this.usuarioLicencia = usuarioLicencia;
}
@Override
public String getUsuarioLicencia() {
return this.usuarioLicencia;
}
@Override
public List<ModuloCodefacEnum> getModulos() {
return modulos;
}
public void setModulos(List<ModuloCodefacEnum> modulos) {
this.modulos = modulos;
}
public Sucursal getSucursal() {
return sucursal;
}
public void setSucursal(Sucursal sucursal) {
this.sucursal = sucursal;
}
public Sucursal getMatriz() {
return matriz;
}
public void setMatriz(Sucursal matriz) {
this.matriz = matriz;
}
/**
* Obtiene el valor en escala de 100%
* @return
*/
@Override
public BigDecimal obtenerIvaActual() {
ParametroCodefac parametroCodefac=getParametrosCodefac().get(ParametroCodefac.IVA_DEFECTO);
String valorString=parametroCodefac.getValor();
return new BigDecimal(valorString);
}
/**
* Obtiene el el valor en escala de decimales
* @return
*/
@Override
public BigDecimal obtenerIvaActualDecimal() {
return obtenerIvaActual().divide(new BigDecimal("100"),2,BigDecimal.ROUND_HALF_UP);
}
}
| true |
b186d44012f2aeb9bb5d39011e792e67b6157d45 | Java | xabicasado/buscaminas | /src/packModelo/packCasilla/Marcada.java | UTF-8 | 147 | 1.570313 | 2 | [] | no_license | package packModelo.packCasilla;
public class Marcada extends Estado {
public Marcada(Coordenada pCoordenada) {
super(pCoordenada);
}
}
| true |
bedc8c598a4cadcb51224d43424ade7e4f849ffe | Java | Jasic/jwork | /jcommon/src/main/java/org/jasic/util/ExcelHelper.java | UTF-8 | 7,568 | 2.28125 | 2 | [] | no_license | //package org.jasic.util;
//
//
//import com.midea.trade.common.util.DateUtils;
//import net.sf.ehcache.pool.sizeof.ReflectionSizeOf;
//import net.sf.ehcache.pool.sizeof.SizeOf;
//import org.apache.commons.lang.NumberUtils;
//import org.apache.poi.openxml4j.opc.OPCPackage;
//import org.apache.poi.ss.usermodel.DateUtil;
//import org.apache.poi.xssf.eventusermodel.XSSFReader;
//import org.apache.poi.xssf.model.SharedStringsTable;
//import org.apache.poi.xssf.usermodel.XSSFRichTextString;
//import org.springframework.util.StopWatch;
//import org.xml.sax.*;
//import org.xml.sax.helpers.DefaultHandler;
//import org.xml.sax.helpers.XMLReaderFactory;
//
//import java.io.InputStream;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.Iterator;
//import java.util.List;
//
///**
// * /**
// *
// * @Author 菜鹰
// * @Date 2015/7/4
// * @Explain: 工作当中遇到要读取大数据量Excel(10万行以上,Excel 2007),用POI方式读取,用HSSFWorkbook读取时,并会内存溢出
// * 后来参考官方写法,蛋疼
// */
//public class ExcelHelper {
//
// private List listAll;
//
// public static final ExcelHelper instance;
//
// static {
// instance = new ExcelHelper();
// }
//
// private ExcelHelper() {
// listAll = new ArrayList();
// }
//
// /**
// * xxx 非常 不建议使用全部加载到内存,而是在com.midea.trade.erp.common.util.ExcelHelper#handleRow(int, java.util.List)方法内使用事件驱动
// *
// * @param fileName
// * @return
// */
// public synchronized List getListAll(String fileName) {
// try {
// processOneSheet(fileName);
// } catch (Exception e) {
// }
// List result = new ArrayList(listAll);
// listAll = new ArrayList();
// return result;
// }
//
// private void processOneSheet(String filename) throws Exception {
// OPCPackage pkg = OPCPackage.open(filename);
// XSSFReader r = new XSSFReader(pkg);
// SharedStringsTable sst = r.getSharedStringsTable();
// XMLReader parser = fetchSheetParser(sst);
// // rId2 found by processing the Workbook
// // Seems to either be rId# or rSheet#
// InputStream sheet2 = r.getSheet("rId2");
// InputSource sheetSource = new InputSource(sheet2);
// parser.parse(sheetSource);
// sheet2.close();
// }
//
// private void processAllSheets(String filename) throws Exception {
// OPCPackage pkg = OPCPackage.open(filename);
// XSSFReader r = new XSSFReader(pkg);
// SharedStringsTable sst = r.getSharedStringsTable();
//
// XMLReader parser = fetchSheetParser(sst);
//
// Iterator<InputStream> sheets = r.getSheetsData();
// while (sheets.hasNext()) {
// System.out.println("Processing new sheet:\n");
// InputStream sheet = sheets.next();
// InputSource sheetSource = new InputSource(sheet);
// parser.parse(sheetSource);
// sheet.close();
// System.out.println("");
// }
// }
//
// private XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
// XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
// ContentHandler handler = new SheetHandler(sst);
// parser.setContentHandler(handler);
// return parser;
// }
//
//
// /**
// * 处理每一行
// *
// * @param rowIndex
// * @param celllist
// */
// private void handleRow(int rowIndex, List<String> celllist) {
// listAll.add(rowIndex, celllist);
// }
//
// /**
// * See org.xml.sax.helpers.DefaultHandler javadocs
// */
// private class SheetHandler extends DefaultHandler {
// private SharedStringsTable sst;
// private String lastContents;
// private boolean nextIsString;
//
// /**
// * 当前行
// */
// private int rowIndex;
// /**
// * 当前列
// */
// private int columnIndex;
//
// /**
// * 用于装载每一行
// */
// private List celllist = new ArrayList();
//
// private SheetHandler(SharedStringsTable sst) {
// this.sst = sst;
// }
//
//
// public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
// // c => cell
// if (name.equals("c")) {
// // Print the cell reference
//// System.out.print(attributes.getValue("r") + " - ");
// // Figure out if the value is an index in the SST
// String cellType = attributes.getValue("t");
// if (cellType != null && cellType.equals("s")) {
// nextIsString = true;
// } else {
// nextIsString = false;
// }
// }
// // Clear contents cache
// lastContents = "";
// }
//
// public void endElement(String uri, String localName, String name)
// throws SAXException {
// // Process the last contents as required.
// // Do now, as characters() may be called more than once
// if (nextIsString) {
// int idx = Integer.parseInt(lastContents);
// lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
// nextIsString = false;
// }
//
// // v => contents of a cell
// // Output after we've seen the string contents
// if (name.equals("v")) {
// Object value = "";
// String v = lastContents.trim();
// v = v.equals("") ? " " : v;
// if (NumberUtils.isNumber(v) && v.indexOf('.') > 0) {
// if (DateUtil.isValidExcelDate(Double.parseDouble(v))) {
// Date date = DateUtil.getJavaDate(Double.parseDouble(v), false);
// value = DateUtils.formatDate(date);
// }
// } else value = v;
// celllist.add(columnIndex, value);
// columnIndex++;
// }
//
// // 处理行
// else if (name.equals("row")) {
// handleRow(rowIndex, celllist);
// celllist.clear();
// rowIndex++;
// columnIndex = 0;
// }
// }
//
// public void characters(char[] ch, int start, int length)
// throws SAXException {
// lastContents += new String(ch, start, length);
// }
// }
//
// public static void main(String[] args) throws Exception {
// ExcelHelper example = new ExcelHelper();
// StopWatch stopWatch = new StopWatch();
// stopWatch.start();
//// example.processOneSheet("C:\\Users\\Caiying\\Desktop\\1.xlsx");
//// example.processAllSheets(args[0]);
// List result = example.getListAll("C:\\Users\\Caiying\\Desktop\\1.xlsx");
// stopWatch.stop();
// System.out.println("处理结束,result总条数:" + result.size());
// System.out.println(stopWatch.prettyPrint());
//
//
// SizeOf sizeOf = new ReflectionSizeOf();
// System.out.println("int大小;" + sizeOf.sizeOf(1));
// System.out.println("总大小;" + sizeOf.sizeOf(result.get(0)));
// System.out.println("总大小;" + sizeOf.sizeOf(result.get(1)));
// }
//}
| true |
f9fbc451e4e622a91923b1daa7981eae810a1f34 | Java | Currence-Online/emandates-libraries-java | /library/src/net/emandates/merchant/library/CoreCommunicator.java | UTF-8 | 12,027 | 2.328125 | 2 | [
"MIT"
] | permissive | package net.emandates.merchant.library;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.cert.CertificateException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.xml.bind.JAXBException;
import javax.xml.crypto.MarshalException;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* Communicator class, to be used for sending messages where LocalInstrumentationCode = CORE
*/
public class CoreCommunicator {
/**
* Logger instance, to be used for logging iso pain raw messages and library messages.
*/
protected ILogger logger;
/**
* XmlProcessor instance, used to process XMLs (signing, verifying, validating signature).
*/
protected XmlProcessor xmlProcessor;
/**
* LocalInstrumentCode used by the current instance (can be CORE or B2B).
*/
protected Instrumentation localInstrumentCode;
/**
* Configuration used by the current instance (can be CORE or B2B).
*/
protected Configuration config;
/**
* Constructs a new Communicator, initializes the Configuration and sets LocalInstrumentCode = CORE
*/
public CoreCommunicator() {
this(Configuration.defaultInstance());
}
public CoreCommunicator(Configuration config) {
this.config = config;
logger = (this.config.getLoggerFactory() != null)
? this.config.getLoggerFactory().Create() : new LoggerFactory().Create();
xmlProcessor = new XmlProcessor(this.config);
localInstrumentCode = Instrumentation.CORE;
}
/**
* Sends a directory request to the URL specified in Configuration.AcquirerUrl_DirectoryReq.
* @return A DirectoryResponse object which contains the response from the server (a list of debtor banks), or error
* information when an error occurs
*/
public DirectoryResponse directory() {
try {
logger.Log(config, "sending new directory request");
String xml = new iDxMessageBuilder(localInstrumentCode).getDirectoryRequest(config);
xml = xmlProcessor.AddSignature(config, xml);
DirectoryResponse dr = DirectoryResponse.Parse(
performRequest(xml, config.getAcquirerUrl_DirectoryReq(), config.isTls12Enabled())
);
return dr;
} catch (DatatypeConfigurationException | JAXBException | CommunicatorException ex) {
logger.Log(config, ex.getMessage());
return DirectoryResponse.Get(ex);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException | InvalidAlgorithmParameterException | ParserConfigurationException | MarshalException | SAXException | XMLSignatureException | TransformerException ex) {
logger.Log(config, ex.getMessage());
return DirectoryResponse.Get(ex);
}
}
private HttpURLConnection getConnection(String url, boolean isTls12Enabled) throws IOException, KeyManagementException, NoSuchAlgorithmException
{
if(url.startsWith("https://"))
{
HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
if(isTls12Enabled)
{
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null,null,new java.security.SecureRandom());
con.setSSLSocketFactory(sc.getSocketFactory());
}
return con;
}
else
{
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
return con;
}
}
String performRequest(String xml, String url, boolean isTls12Enabled) throws CommunicatorException {
try {
logger.Log(config, "sending request to " + url);
if (!xmlProcessor.VerifySchema(config, xml)) {
logger.Log(config, "request xml schema is not valid");
throw new CommunicatorException("request xml schema not valid");
}
logger.LogXmlMessage(config, xml);
logger.Log(config, "creating http(s) client");
HttpURLConnection con = getConnection(url, isTls12Enabled );//HttpsURLConnection) new URL(url).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
con.setDoInput(true);
con.setDoOutput(true);
con.getOutputStream().write(xml.getBytes(StandardCharsets.UTF_8));
String response = Utils.copy(con.getInputStream());
logger.LogXmlMessage(config, response);
if (!xmlProcessor.VerifySchema(config,response)) {
logger.Log(config, "response xml schema is not valid");
throw new CommunicatorException("response xml schema not valid");
}
if (!xmlProcessor.VerifySignature(config, response)) {
logger.Log(config, "response xml signature not valid");
throw new CommunicatorException("response xml signature not valid");
}
return response;
} catch (IOException | IllegalStateException | ParserConfigurationException | SAXException ex) {
logger.Log(config, ex.getMessage());
throw new CommunicatorException("error occured", ex);
} catch (MarshalException | XMLSignatureException ex) {
logger.Log(config, ex.getMessage());
throw new CommunicatorException("error occured", ex);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
logger.Log(config, ex.getMessage());
throw new CommunicatorException("error occured", ex);
} catch (TransformerException ex) {
logger.Log(config, ex.getMessage());
throw new CommunicatorException("error occured", ex);
} catch (KeyManagementException ex) {
logger.Log(config, ex.getMessage());
throw new CommunicatorException("error occured", ex);
} catch (NoSuchAlgorithmException ex) {
logger.Log(config, ex.getMessage());
throw new CommunicatorException("error occured", ex);
}
}
/**
* Sends a new mandate request to the URL specified in Configuration.AcquirerUrl_TransactionReq.
* @param newMandateRequest A NewMandateRequest object.
* @return A NewMandateResponse object which contains the response from the server (transaction id, issuer authentication URL), or error information
* when an error occurs
*/
public NewMandateResponse newMandate(NewMandateRequest newMandateRequest) {
try {
logger.Log(config, "sending new mandate request");
Element eMandate = new eMandateMessageBuilder(localInstrumentCode).getNewMandate(newMandateRequest);
String xml = new iDxMessageBuilder(localInstrumentCode).getTransactionRequest(config,newMandateRequest, eMandate);
xml = xmlProcessor.AddSignature(config, xml);
NewMandateResponse nmr = NewMandateResponse.Parse(
performRequest(xml, config.getAcquirerUrl_TransactionReq(), config.isTls12Enabled())
);
return nmr;
} catch (ParserConfigurationException | SAXException | IOException | TransformerException | CommunicatorException ex) {
logger.Log(config, ex.getMessage());
return NewMandateResponse.Get(ex);
} catch (DatatypeConfigurationException | JAXBException ex) {
logger.Log(config, ex.getMessage());
return NewMandateResponse.Get(ex);
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException | InvalidAlgorithmParameterException | MarshalException | XMLSignatureException ex) {
logger.Log(config, ex.getMessage());
return NewMandateResponse.Get(ex);
}
}
/**
* Sends an amendment request to the URL specified in Configuration.AcquirerUrl_TransactionReq.
* @param amendmentRequest An AmendmentRequest object.
* @return An AmendmentResponse object which contains the response from the server (transaction id, issuer authentication URL),
* or error information when an error occurs.
*/
public AmendmentResponse amend(AmendmentRequest amendmentRequest) {
try {
logger.Log(config, "sending amend mandate request");
Element eMandate = new eMandateMessageBuilder(localInstrumentCode).getAmend(amendmentRequest);
String xml = new iDxMessageBuilder(localInstrumentCode).getTransactionRequest(config, amendmentRequest, eMandate);
xml = xmlProcessor.AddSignature(config, xml);
AmendmentResponse ar = AmendmentResponse.Parse(
performRequest( xml, config.getAcquirerUrl_TransactionReq(), config.isTls12Enabled())
);
return ar;
} catch (ParserConfigurationException | SAXException | IOException | TransformerException | CommunicatorException ex) {
logger.Log(config, ex.getMessage());
return AmendmentResponse.Get(ex);
} catch (DatatypeConfigurationException | JAXBException ex) {
logger.Log(config, ex.getMessage());
return AmendmentResponse.Get(ex);
} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException | InvalidAlgorithmParameterException | MarshalException | XMLSignatureException ex) {
logger.Log(config, ex.getMessage());
return AmendmentResponse.Get(ex);
}
}
/**
* Sends a transaction status request to the URL specified in Configuration.AcquirerUrl_TransactionReq.
* @param statusRequest A StatusRequest object
* @return A StatusResponse object which contains the response from the server (transaction id, status message), or
* error information when an error occurs.
*/
public StatusResponse getStatus(StatusRequest statusRequest) {
try {
logger.Log(config, "sending status request");
String xml = new iDxMessageBuilder(localInstrumentCode).getStatusRequest(config, statusRequest);
xml = xmlProcessor.AddSignature(config, xml);
StatusResponse sr = StatusResponse.Parse(
performRequest( xml, config.getAcquirerUrl_StatusReq(), config.isTls12Enabled())
);
return sr;
} catch (CommunicatorException ex) {
logger.Log(config, ex.getMessage());
return StatusResponse.Get(ex);
} catch (DatatypeConfigurationException | JAXBException ex) {
logger.Log(config, ex.getMessage());
return StatusResponse.Get(ex);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableEntryException | InvalidAlgorithmParameterException | ParserConfigurationException | MarshalException | SAXException | XMLSignatureException | TransformerException ex) {
logger.Log(config, ex.getMessage());
return StatusResponse.Get(ex);
}
}
public static String getVersion() {
return "1.2.4";
}
}
| true |
f35db628e0e5a9950306a7d307041a9fc810e2c4 | Java | AiRanthem/Design-Pattern-Demo | /src/main/java/com/learn/Iterator/BookShelf.java | UTF-8 | 679 | 3.15625 | 3 | [
"MIT"
] | permissive | package com.learn.Iterator;
public class BookShelf implements Aggregate {
private final Book[] books;
private int last = 0;
private final int size;
public BookShelf(int maxsize){
this.books = new Book[maxsize];
this.size = maxsize;
}
public Book get(int index){
return books[index];
}
public boolean appendBook(Book book){
if(last >= size){
return false;
}
this.books[last] = book;
last ++;
return true;
}
public int getLength() {
return last;
}
@Override
public Iterator getIterator() {
return new AggreateIterator(this);
}
}
| true |
b477784a498e3a85cacc84523c965887e2d55525 | Java | SavaGaborov/Thesis | /SavaDiplosmkiRad/DiplomskiRadPrivatnaBolnica/src/entiteti/Bolest.java | UTF-8 | 755 | 2.765625 | 3 | [] | no_license | package entiteti;
public class Bolest {
public int BolestID;
public String NazivBolesti;
public boolean MogucePruzanjeZdravstvenihUsluga;
public String toString(){
return NazivBolesti + " ";
}
public int getBolestID() {
return BolestID;
}
public void setBolestID(int bolestID) {
BolestID = bolestID;
}
public String getNazivBolesti() {
return NazivBolesti;
}
public void setNazivBolesti(String nazivBolesti) {
NazivBolesti = nazivBolesti;
}
public boolean isMogucePruzanjeZdravstvenihUsluga() {
return MogucePruzanjeZdravstvenihUsluga;
}
public void setMogucePruzanjeZdravstvenihUsluga(boolean mogucePruzanjeZdravstvenihUsluga) {
MogucePruzanjeZdravstvenihUsluga = mogucePruzanjeZdravstvenihUsluga;
}
}
| true |
6326b22221a9edac3688e022a855ead40d10ac97 | Java | noudisan/falcon_sample | /core/xqwy-api/src/main/java/com/zhiyi/community/dto/CommunityTudeFLag.java | UTF-8 | 516 | 2.1875 | 2 | [] | no_license | package com.zhiyi.community.dto;
public enum CommunityTudeFLag {
// // 无
// public static final int TUDE_FLAG_NONE = 0;
// // 机器
// public static final int TUDE_FLAG_ROBOT = 1;
// // 人工
// public static final int TUDE_FLAG_PERSON = 2;
TUDE_FLAG_NONE("无"),TUDE_FLAG_ROBOT("机器"),TUDE_FLAG_PERSON("人工");
private String status;
CommunityTudeFLag(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
}
| true |
02afb91ef1192497abd39605129c8ee4d12aad5e | Java | robsondejesus1996/Trabalho-Persistencia-de-Dados-manipulacaoArquivo | /br.com.udesc.trabalhoarquivo/src/br/com/udesc/trabalhoarquivo/model/Cidades.java | UTF-8 | 2,066 | 2.734375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.udesc.trabalhoarquivo.model;
import java.io.Serializable;//classes de entraga e saída de arquivo
import java.util.Objects;
/**
* @versão 01 desenvolvimento rj
* @author Robson de Jesus
*/
public class Cidades implements Serializable{//interface de marcação
private String nome;
private String uf;
private String cep;
public Cidades() {
}
public Cidades(String nome, String uf, String cep) {
this.nome = nome;
this.uf = uf;
this.cep = cep;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
@Override
public int hashCode() {
int hash = 3;
hash = 17 * hash + Objects.hashCode(this.nome);
hash = 17 * hash + Objects.hashCode(this.uf);
hash = 17 * hash + Objects.hashCode(this.cep);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cidades other = (Cidades) obj;
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
if (!Objects.equals(this.uf, other.uf)) {
return false;
}
if (!Objects.equals(this.cep, other.cep)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Cidades{" + "nome=" + nome + ", uf=" + uf + ", cep=" + cep + '}';
}
}
| true |
843d7556e9ec459ef4d115f56b68dc41cc562aca | Java | stepan-tarasenko/TestTask | /TestTask/app/src/main/java/com/developer/tarasenko/testtask/fragments/MainFragment.java | UTF-8 | 3,585 | 2.4375 | 2 | [] | no_license | package com.developer.tarasenko.testtask.fragments;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.developer.tarasenko.testtask.ApiInterface;
import com.developer.tarasenko.testtask.R;
import com.developer.tarasenko.testtask.entity.DisplayModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainFragment extends Fragment {
private TextView textView;
private WebView webView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View target = inflater.inflate(R.layout.base_fragment, container, false);
findAndConfigureViews(target);
if (getArguments() != null) {
if (getArguments().containsKey("id")) {
int id = getArguments().getInt("id");
/**
* Load than particular id, what we passed to fragment
*/
loadDisplayModelById(id);
}
}
return target;
}
/**
* Loads DisplayModel by id and display it into fragment
* @param id
*/
private void loadDisplayModelById(int id) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<DisplayModel> displayModelCall = apiInterface.getReceiveModelById(id);
displayModelCall.enqueue(new Callback<DisplayModel>() {
@Override
public void onResponse(Call<DisplayModel> call, Response<DisplayModel> response) {
if (response.isSuccessful()) {
renderDisplayModel(response.body());
}
}
@Override
public void onFailure(Call<DisplayModel> call, Throwable t) {
Log.e(getTag(), t.toString());
}
});
}
/**
* Display into WebView/TextView depends on type
* @param displayModel model what we get by id, from response
*/
private void renderDisplayModel(DisplayModel displayModel){
if (displayModel.getType().equals("text")) {
webView.setVisibility(View.INVISIBLE);
textView.setVisibility(View.VISIBLE);
textView.setText(displayModel.getContents());
}
else {
textView.setVisibility(View.INVISIBLE);
webView.setVisibility(View.VISIBLE);
webView.loadUrl(displayModel.getUrl());
}
}
/**
* Finds views, make them invisible,
* enables js in webview, makes wvclient
* @param target view, what will be displayed in fragment
*/
private void findAndConfigureViews(View target){
textView = target.findViewById(R.id.text_view);
webView = target.findViewById(R.id.web_view);
webView.setVisibility(View.INVISIBLE);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
textView.setVisibility(View.INVISIBLE);
}
}
| true |
537ea694514eb71950d7daa4d1c26057882a85d3 | Java | skazakov93/amadeusounds | /amadeusounds/src/main/java/com/amadeusounds/model/Song.java | UTF-8 | 2,524 | 2.09375 | 2 | [] | no_license | package com.amadeusounds.model;
import org.hibernate.validator.constraints.Length;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import java.sql.Blob;
import java.util.Date;
import java.util.List;
/**
* Created by Vladica Jovanovski on 3/15/2016.
*/
@Entity
@Table(name = "songs")
public class Song extends BaseEntity {
@Length(max = 50)
private String name;
@NotNull
private Blob song;
@Length(max = 200)
private String description;
@OneToMany
private List<SongImage> images;
@ManyToOne
private Category category;
@ManyToMany (fetch = FetchType.EAGER)
private List<Tag> tags;
@NotNull
private Date date;
@ManyToOne
private User user;
@OneToMany
private List<Comment> comments;
@OneToMany
private List<Rating> ratings;
@Transient
private Long views;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Blob getSong() {
return song;
}
public void setSong(Blob song) {
this.song = song;
}
public List<SongImage> getImages() {
return images;
}
public void setImages(List<SongImage> images) {
this.images = images;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public List<Rating> getRatings() {
return ratings;
}
public void setRatings(List<Rating> ratings) {
this.ratings = ratings;
}
public Long getViews() {
return views;
}
public void setViews(Long views) {
this.views = views;
}
}
| true |
5348cdf4c227c8759f8dbf4b367aa7d282cb0f7c | Java | sylwiaswieczkowska/javastart | /src/main/java/pl/sda/javastart/Homework/UniqueValuesArray_Ex27.java | UTF-8 | 1,426 | 3.328125 | 3 | [] | no_license | package pl.sda.javastart.Homework;
import java.util.Arrays;
public class UniqueValuesArray_Ex27 {
public static void main(String[] args) {
System.out.println(Arrays.toString(uniqueValuesArrays(new int[]{1, 2, 4, 2, 5, 6}, new int[]{7, 9, 3, 2, 5, 2, 6})));
}
private static int[] uniqueValuesArrays(int[] firstTab, int[] secondTab) {
System.out.println("Zwraca tablicę zawierającą posortowane unikatowe wartości przekazanych tablic ");
int[] twoTable = new int[firstTab.length + secondTab.length];
for (int i = 0; i <firstTab.length ; i++) {
twoTable[i] = firstTab[i];
}
for (int i = firstTab.length ; i < twoTable.length; i++) {
twoTable[i] = secondTab[i- (firstTab.length)];
}
Arrays.sort(twoTable);
int end = twoTable.length;
for (int i = 0; i < end; i++) {
for (int j = i + 1; j < end; j++) {
if (twoTable[i] == twoTable[j]) {
int shiftLeft = j;
for (int k = j + 1; k < end; k++, shiftLeft++) {
twoTable[shiftLeft] = twoTable[k];
}
end--;
j--;
}
}
}
int[] resultTab = new int[end];
for (int i = 0; i < end; i++) {
resultTab[i] = twoTable[i];
}
return resultTab;
}
}
| true |
46db052cd948ebc5441416b764b4fbcd3e328509 | Java | ankitsharma37/java_workspace | /Workspace/exercises/Classes/src/Practice/main.java | UTF-8 | 235 | 2.078125 | 2 | [] | no_license | package Practice;
public class main {
public static void main(String[] args) {
Apple apple1 = new Apple("spartan");
//apple1.setPrice(50);
userPurchase item1 = new userPurchase(1000);
item1.buy(50.0);
}
}
| true |
c0bc9a25705952cc362428fc81febca6a2cae960 | Java | uk-gov-mirror/ONSdigital.TakeOn-VP-Wrangler | /src/main/java/uk/gov/ons/validation/entity/HandlerAdditionalRequest.java | UTF-8 | 304 | 1.5625 | 2 | [] | no_license | package uk.gov.ons.validation.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class HandlerAdditionalRequest {
private String type;
private PostRequest input;
}
| true |
20a200e93d179450287f85281e64ff052e618817 | Java | You-can-do-better/ucloud-sdk-java | /src/main/java/com/xiaolong/ucloud/ufile/request/GetBucketRequest.java | UTF-8 | 1,697 | 2.375 | 2 | [] | no_license |
package com.xiaolong.ucloud.ufile.request;
import com.xiaolong.ucloud.ufile.UFileRegion;
import com.xiaolong.ucloud.ufile.exception.UFileServiceException;
import com.xiaolong.ucloud.ufile.model.UBucket;
import com.xiaolong.ucloud.ufile.utils.ObjectsUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public final class GetBucketRequest
extends UBucketRequest
{
public GetBucketRequest(UFileRegion region, String bucketName)
{
super(HttpType.GET, "DescribeBucket", region);
ObjectsUtil.requireNonNull(bucketName, "Bucket name is null");
this.addParameter("BucketName", bucketName);
}
@Override
public Object execute(BucketExecutor executor) throws UFileServiceException
{
UResponse response = executor.execute(this);
JsonObject json = response.getResponse();
if (!json.has("DataSet")) {
throw new UFileServiceException(200, "DataSet missing.");
}
JsonArray dataSet = json.getAsJsonArray("DataSet");
if (dataSet.size() != 1) {
throw new UFileServiceException(200, "Multiple bucket exists in GetBucketResponse.");
}
JsonObject jsonBucket = dataSet.get(0).getAsJsonObject();
if (!jsonBucket.has("BucketName")) {
throw new UFileServiceException(200, "Bucket Name missing.");
}
String bucketName = jsonBucket.get("BucketName").getAsString();
if (!jsonBucket.has("BucketId")) {
throw new UFileServiceException(200, "Bucket Id missing.");
}
String bucketId = jsonBucket.get("BucketId").getAsString();
return new UBucket(bucketId, bucketName);
}
}
| true |
a2ff80d5704e5f63c8fa46c8a1c0c9c2453c4624 | Java | mateuspiresl/mps-lab-6 | /ProjBanco/src/bank/Client.java | UTF-8 | 535 | 3.03125 | 3 | [] | no_license | package bank;
public class Client
{
public String name, cpf;
public Client(String name, String cpf)
{
this.name = name;
this.cpf = cpf;
}
public Client() {
this("Nome e Sobrenome", "123.456.789-90");
}
public String getName() {
return this.name;
}
public String getCpf() {
return this.cpf;
}
public void setName(String name) {
this.name = name;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
@Override
public String toString() {
return String.format("Cliente: %s, %s", this.name, this.cpf);
}
}
| true |
f685d0e9ec88aef783ee1bfc7a2a6fc7dc06e08c | Java | fsds12/TripAdviserSemiProject | /TripAdviserSemiProject/src/common/JDBCTemplate.java | UTF-8 | 2,159 | 2.78125 | 3 | [] | no_license | package common;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCTemplate {
private static Properties prop;
private static String fileName;
private static String driver;
private static String url;
private static String dbId;
private static String dbPw;
private static Connection conn = null;
static {
prop = new Properties();
fileName = JDBCTemplate.class.getResource("/sql/common/driver.properties").getPath();
try {
prop.load(new FileReader(fileName));
driver = prop.getProperty("driver");
url = prop.getProperty("url");
dbId = prop.getProperty("id");
dbPw = prop.getProperty("pw");
}
catch(IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, dbId, dbPw);
conn.setAutoCommit(false);
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn) {
try {
if(conn != null && !conn.isClosed()) {
conn.close();
}
}
catch(SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement stmt) {
try {
if(stmt != null && !stmt.isClosed()) {
stmt.close();
}
}
catch(SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs) {
try {
if(rs != null && !rs.isClosed()) {
rs.close();
}
}
catch(SQLException e) {
e.printStackTrace();
}
}
public static void commit() {
try {
if(conn != null && !conn.isClosed()) {
conn.commit();
}
}
catch(SQLException e) {
e.printStackTrace();
}
}
public static void rollback() {
try {
if(conn != null && !conn.isClosed()) {
conn.rollback();
}
}
catch(SQLException e) {
e.printStackTrace();
}
}
}
| true |
efe0e8dae0d8e43a1a7381fda75c0d0e439e8bac | Java | cubecnelson/WeClean | /WeClean source/weClean/src/main/java/com/ligootech/weclean/helper/DatabaseHelper.java | UTF-8 | 4,548 | 2.640625 | 3 | [] | no_license | package com.ligootech.weclean.helper;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.ligootech.weclean.model.District;
public class DatabaseHelper extends SQLiteOpenHelper{
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "wecleanligootech";
// Table Names
public static final String TABLE_DISTRICT = "District";
// prescription Table - column names
private static final String DISTRICT_ID = "districtid";
private static final String DISTRICT = "district";
// Prescription table create statement
private static final String CREATE_TABLE_DISTRICT = "CREATE TABLE "
+ TABLE_DISTRICT + "(" + DISTRICT_ID
+ " INTEGER AUTO_INCREMENT," + DISTRICT + " TEXT" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
db.execSQL(CREATE_TABLE_DISTRICT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DISTRICT);
}
/*
* Creating a prescription
*/
public long createdistricttable(District district) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DISTRICT_ID, district.getdistrictid());
values.put(DISTRICT, district.getdistrict());
// insert row
long district_id = db.insert(TABLE_DISTRICT, null, values);
return district_id;
}
/*
* get single prescription
*/
public District getdistrict(String district) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_DISTRICT + " WHERE "
+ DISTRICT + " = '" + district+"'";
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c != null)
c.moveToFirst();
District td = new District();
td.setdistrictid(c.getInt(c.getColumnIndex(DISTRICT_ID)));
td.setdistrict((c.getString(c.getColumnIndex(DISTRICT))));
return td;
}
/**
* getting all prescriptions
* */
public List<District> getAlldistrict() {
List<District> districts = new ArrayList<District>();
String selectQuery = "SELECT * FROM " + TABLE_DISTRICT;
Log.e(LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
District td = new District();
td.setdistrictid(c.getInt(c
.getColumnIndex(DISTRICT_ID)));
td.setdistrict((c.getString(c.getColumnIndex(DISTRICT))));
// adding to prescription list
districts.add(td);
} while (c.moveToNext());
}
return districts;
}
/**
* /* getting prescription count
*/
public int getloginCount() {
String countQuery = "SELECT * FROM " + TABLE_DISTRICT;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
/*
* Updating a prescription
*/
public int updatelogin(District district) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DISTRICT, district.getdistrict());
// updating row
return db
.update(TABLE_DISTRICT, values, DISTRICT_ID
+ " = ?", new String[] { String.valueOf(district
.getdistrictid()) });
}
/*
* Deleting a prescription
*/
public void deletelogin(long tado_id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_DISTRICT, DISTRICT_ID + " = ?",
new String[] { String.valueOf(tado_id) });
}
// ------------------------ "tags" table methods ----------------//
public void deleteTableRows(String table) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + table);
}
// closing database
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen())
db.close();
}
}
| true |
9bf318a0b136b71ee0b5c77611b33f934fe0a120 | Java | Maltcommunity/fongo-mongo-3.8 | /src/test/java/com/github/fakemongo/FongoMapReduceTest.java | UTF-8 | 34,747 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package com.github.fakemongo;
import com.github.fakemongo.impl.Util;
import com.github.fakemongo.junit.FongoRule;
import com.mongodb.*;
import com.mongodb.util.FongoJSON;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
public class FongoMapReduceTest {
private static final Logger LOG = LoggerFactory.getLogger(FongoMapReduceTest.class);
public final FongoRule fongoRule = new FongoRule(false);
public final ExpectedException exception = ExpectedException.none();
@Rule
public TestRule rules = RuleChain.outerRule(exception).around(fongoRule);
// see http://no-fucking-idea.com/blog/2012/04/01/using-map-reduce-with-mongodb/
@Test
public void testMapReduceSimple() {
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit(this.url, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {count: res}; };";
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
Assertions.assertThat(result.getDuration()).isGreaterThanOrEqualTo(0);
Assertions.assertThat(result.getEmitCount()).isEqualTo(5);
Assertions.assertThat(result.getOutputCount()).isEqualTo(2);
Assertions.assertThat(result.getInputCount()).isEqualTo(5);
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"count\" : 2.0}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void testMapReduceEmitObject() {
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };";
coll.mapReduce(map, reduce, "result", new BasicDBObject());
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void testMapReduceJoinOneToMany() {
DBCollection trash = fongoRule.newCollection();
DBCollection dates = fongoRule.newCollection();
fongoRule.insertJSON(trash, "[" +
" {date: \"1\", trash_data: \"13\" },\n" +
" {date: \"1\", trash_data: \"1\" },\n" +
" {date: \"2\", trash_data: \"100\" },\n" +
" {date: \"2\", trash_data: \"256\" }]");
fongoRule.insertJSON(dates, "[{date: \"1\", dateval: \"10\"}, {date:\"2\", dateval: \"20\"}]");
String mapTrash = "function() { emit({date: this.date}, {value : [{dateval: null, trash_data:this.trash_data, date:this.date}]});};";
String mapDates = "function() { emit({date:this.date}, {value : [{dateval:this.dateval}]});};";
String reduce = "function(key, values){" +
" var dateval = null;\n" +
" for (var j in values) {\n" +
" var valArr = values[j].value;\n" +
" for (var jj in valArr) {\n" +
" var value = valArr[jj];\n" +
" if (value.dateval !== null) {\n" +
" dateval = value.dateval;\n" +
" }\n" +
" }\n" +
" }" +
" var outValues = [];\n" +
" for (var j in values) {\n" +
" var valArr = values[j].value;\n" +
" for (var jj in valArr) {\n" +
" var orig = valArr[jj];\n" +
" var copy = {};\n" +
" for (var jjj in orig) {\n" +
" copy[jjj] = orig[jjj];\n" +
" }\n" +
" if (dateval !== null) {\n" +
" copy[\"dateval\"] = dateval;\n" +
" }\n" +
" outValues.push(copy);\n" +
" }\n" +
" }\n" +
" return {value:outValues};" +
"};";
trash.mapReduce(mapTrash, reduce, "result", MapReduceCommand.OutputType.REDUCE, new BasicDBObject());
dates.mapReduce(mapDates, reduce, "result", MapReduceCommand.OutputType.REDUCE, new BasicDBObject());
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
Map<String, DBObject> byId = new HashMap<String, DBObject>();
for (DBObject res : results) {
byId.put(FongoJSON.serialize(res.get("_id")), res);
}
List<DBObject> expected = fongoRule.parse("[" +
"{\"_id\":{\"date\":\"1\"}, \"value\":" +
"{\"value\":[{\"dateval\":\"10\"}, {\"trash_data\":\"13\", \"date\":\"1\", \"dateval\":\"10\"}, " +
"{\"trash_data\":\"1\", \"date\":\"1\", \"dateval\":\"10\"}]}}, " +
"{\"_id\":{\"date\":\"2\"}, \"value\":" +
"{\"value\":[{\"dateval\":\"20\"}, {\"trash_data\":\"100\", \"date\":\"2\", \"dateval\":\"20\"}, " +
"{\"trash_data\":\"256\", \"date\":\"2\", \"dateval\":\"20\"}]}}]");
for (DBObject e : expected) {
List<DBObject> values = (List<DBObject>) (((DBObject) e.get("value")).get("value"));
DBObject id = (DBObject) e.get("_id");
DBObject actual = byId.get(FongoJSON.serialize(id));
List<DBObject> actualValues = (List<DBObject>) (((DBObject) actual.get("value")).get("value"));
Assertions.assertThat(actualValues).containsAll(values);
Assertions.assertThat(actualValues.size()).isEqualTo(values.size());
}
Assertions.assertThat(expected.size()).isEqualTo(results.size());
}
// see http://no-fucking-idea.com/blog/2012/04/01/using-map-reduce-with-mongodb/
@Test
public void testMapReduceWithArray() {
DBCollection coll = fongoRule.newCollection();
fongoRule.insertJSON(coll, "[{url: \"www.google.com\", date: 1, trash_data: 5, arr: ['a',2] },\n" +
" {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13, arr: ['b',4] },\n" +
" {url: \"www.google.com\", date: 1, trash_data: 1, arr: ['c',6] },\n" +
" {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69, arr: ['d',8] },\n" +
" {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256, arr: ['e',10] }]");
String map = "function(){ emit(this.url, this.arr); };";
String reduce = "function(key, values){ var res = []; values.forEach(function(v){ res = res.concat(v); }); return {mergedArray: res}; };";
coll.mapReduce(map, reduce, "result", new BasicDBObject());
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"mergedArray\" : [\"a\",2.0,\"c\",6.0]}}, " +
"{ \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"mergedArray\" : [\"b\",4.0,\"d\",8.0,\"e\",10.0]}}]"), results);
}
@Test
public void should_use_outputdb() {
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit(this.url, 1); };";
String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };";
MapReduceCommand mapReduceCommand = new MapReduceCommand(coll, map, reduce, "result", MapReduceCommand.OutputType.MERGE, new BasicDBObject());
mapReduceCommand.setOutputDB("otherColl");
coll.mapReduce(mapReduceCommand);
List<DBObject> results = fongoRule.getDb("otherColl").getCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"count\" : 2.0}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void testZipMapReduce() throws IOException {
DBCollection coll = fongoRule.newCollection();
fongoRule.insertFile(coll, "/zips.json");
String map = "function () {\n" +
" var pitt = [-80.064879, 40.612044];\n" +
" var phil = [-74.978052, 40.089738];\n" +
"\n" +
" function distance(a, b) {\n" +
" var dx = a[0] - b[0];\n" +
" var dy = a[1] - b[1];\n" +
" return Math.sqrt(dx * dx + dy * dy);\n" +
" }\n" +
"\n" +
" if (distance(this.loc, pitt) < distance(this.loc, phil)) {\n" +
" emit(\"pitt\",1);\n" +
" } else {\n" +
" emit(\"phil\",1);\n" +
" }\n" +
"}\n";
String reduce = "function(name, values) { return Array.sum(values); };";
MapReduceOutput output = coll.mapReduce(map, reduce, "resultF", new BasicDBObject("state", "MA"));
List<DBObject> results = output.getOutputCollection().find().toArray();
assertEquals(fongoRule.parse("[{ \"_id\" : \"phil\" , \"value\" : 474.0}]"), results);
}
/**
* Inline output = in memory.
*/
@Test
public void testMapReduceInline() {
// Given
DBCollection coll = newCollectionWithUrls();
// When
String map = "function(){ emit(this.url, 1); };";
String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };";
MapReduceOutput output = coll.mapReduce(map, reduce, null, MapReduceCommand.OutputType.INLINE, new BasicDBObject());
// Then
assertEquals(fongoRule.parse("[{ \"_id\" : \"www.google.com\" , \"value\" : { \"count\" : 2.0}}, { \"_id\" : \"www.no-fucking-idea.com\" , \"value\" : { \"count\" : 3.0}}]"), output.results());
}
@Test
public void testMapReduceMapInError() {
ExpectedMongoException.expectMongoCommandException(exception, 16722);
DBCollection coll = newCollectionWithUrls();
String map = "function(){ ;";
String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ res += 1}); return {count: res}; };";
coll.mapReduce(map, reduce, "result", new BasicDBObject());
}
@Test
public void testMapReduceReduceInError() {
ExpectedMongoException.expectMongoCommandException(exception, 16722);
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit(this.url, 1); };";
String reduce = "function(key, values){ values.forEach(function(v){ res += 1}); return {count: res}; };";
coll.mapReduce(map, reduce, "result", new BasicDBObject());
}
/**
* http://exceptionallyexceptionalexceptions.blogspot.fr/2012/03/mongodb-mapreduce-scope-variables.html
*/
@Test
public void should_scope_permit_to_initialize() {
DBCollection coll = fongoRule.newCollection();
fongoRule.insertJSON(coll, "[{\n" +
"\t\"_id\": \"4f0c56f1b8eea0b686189c90\",\n" +
"\t\"meh\": \"meh\",\n" +
"\t\"feh\": \"feh\",\n" +
"\t\"arrayOfStuff\": [\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Elgin City\",\n" +
"\t\t\t\"date\": \"100\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Rangers\",\n" +
"\t\t\t\"date\": \"200\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Arsenal\",\n" +
"\t\t\t\"date\": \"300\"\n" +
"\t\t}\n" +
"\t]\n" +
"},\n" +
"{\n" +
"\t\"_id\": \"4f0c56f1b8eea0b686189c99\",\n" +
"\t\"meh\": \"meh meh meh meh\",\n" +
"\t\"feh\": \"feh feh feh feh feh feh\",\n" +
"\t\"arrayOfStuff\": [\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Satriani\",\n" +
"\t\t\t\"date\": \"100\"\n" +
"\t\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Vai\",\n" +
"\t\t\t\"date\": \"200\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Johnson\",\n" +
"\t\t\t\"date\": \"300\"\n" +
"\t\t}\n" +
"\t]\n" +
"}]");
String map = "function() {" +
"if(this.arrayOfStuff) {" +
"this.arrayOfStuff.forEach(function(stuff) {" +
"if(stuff.date > from && stuff.date < to) {" +
"emit({day: stuff.date}, {count:1});" +
"}" +
"});" +
"}" +
"};";
String reduce = "function(key , values) {" +
"var total = 0;" +
"values.forEach(function(v) {" +
"total += v.count;" +
"});" +
"return {count : total};" +
"};";
DBObject query = new BasicDBObject();
query.put("meh", "meh");
MapReduceCommand cmd = new MapReduceCommand(coll, map, reduce, null, MapReduceCommand.OutputType.INLINE, query);
Map scope = new HashMap();
scope.put("from", 100);
scope.put("to", 301);
cmd.setScope(scope);
MapReduceOutput out = coll.mapReduce(cmd);
Assertions.assertThat(out.results()).isEqualTo(fongoRule.parseList("[{\"_id\":{\"day\":\"200\"}, \"value\":{\"count\":1.0}}, " +
"{\"_id\":{\"day\":\"300\"}, \"value\":{\"count\":1.0}}]"));
}
@Test
public void should_scope_permit_to_initialize_NumberLong() {
DBCollection coll = fongoRule.newCollection();
fongoRule.insertJSON(coll, "[{\n" +
"\t\"_id\": \"4f0c56f1b8eea0b686189c90\",\n" +
"\t\"meh\": \"meh\",\n" +
"\t\"feh\": \"feh\",\n" +
"\t\"arrayOfStuff\": [\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Elgin City\",\n" +
"\t\t\t\"date\": \"100\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Rangers\",\n" +
"\t\t\t\"date\": \"200\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Arsenal\",\n" +
"\t\t\t\"date\": \"300\"\n" +
"\t\t}\n" +
"\t]\n" +
"},\n" +
"{\n" +
"\t\"_id\": \"4f0c56f1b8eea0b686189c99\",\n" +
"\t\"meh\": \"meh meh meh meh\",\n" +
"\t\"feh\": \"feh feh feh feh feh feh\",\n" +
"\t\"arrayOfStuff\": [\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Satriani\",\n" +
"\t\t\t\"date\": \"100\"\n" +
"\t\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Vai\",\n" +
"\t\t\t\"date\": \"200\"\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"name\": \"Johnson\",\n" +
"\t\t\t\"date\": \"300\"\n" +
"\t\t}\n" +
"\t]\n" +
"}]");
String map = "function() {" +
"if(this.arrayOfStuff) {" +
"this.arrayOfStuff.forEach(function(stuff) {" +
"if(stuff.date > o.from.toNumber() && stuff.date < o.to.toNumber()) {" +
"emit({day: stuff.date}, {count:1});" +
"}" +
"});" +
"}" +
"};";
String reduce = "function(key , values) {" +
"var total = 0;" +
"values.forEach(function(v) {" +
"total += v.count;" +
"});" +
"return {count : total};" +
"};";
DBObject query = new BasicDBObject();
query.put("meh", "meh");
MapReduceCommand cmd = new MapReduceCommand(coll, map, reduce, null, MapReduceCommand.OutputType.INLINE, query);
Map scope = new HashMap();
scope.put("o", new BasicDBObject("to", 301L).append("from", 100L));
cmd.setScope(scope);
MapReduceOutput out = coll.mapReduce(cmd);
Assertions.assertThat(out.results()).isEqualTo(fongoRule.parseList("[{\"_id\":{\"day\":\"200\"}, \"value\":{\"count\":1.0}}, " +
"{\"_id\":{\"day\":\"300\"}, \"value\":{\"count\":1.0}}]"));
}
@Test
public void should_printjson_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); printjson(res); return {\"count\": res}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void should_print_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); print(res); return {\"count\": res}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void should_printjsononeline_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); printjsononeline(res); return {\"count\": res}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void should_assert_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); assert(true); return {\"count\": res}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 3.0}}]"), results);
}
@Test
public void should_assert_return_an_error() {
ExpectedMongoException.expectMongoCommandException(exception, 16722);
exception.expectMessage("Error: assert failed");
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); assert(res == 2); return {\"count\": res}; };";
// When
coll.mapReduce(map, reduce, "result", new BasicDBObject());
}
@Test
public void should_isNumber_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": isNumber(res) ? 1 : 2}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 1.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 1.0}}]"), results);
}
@Test
public void should_isString_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": isString(\"\" + res) ? 1 : 2}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 1.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 1.0}}]"), results);
}
@Test
public void should_isString_return_false() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": isString(res) ? 1 : 2}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 2.0}}]"), results);
}
@Test
public void should_isObject_work() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": isObject({res:res}) ? 1 : 2}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 1.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 1.0}}]"), results);
}
@Test
public void should_isObject_return_false_for_string() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": isObject(\"\" + res) ? 1 : 2}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 2.0}}]"), results);
}
@Test
public void should_isObject_return_false_for_double() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": isObject(res) ? 1 : 2} };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(fongoRule.parse("[{\"_id\" : {url: \"www.google.com\"} , \"value\" : { \"count\" : 2.0}}, { \"_id\" : {url: \"www.no-fucking-idea.com\"} , \"value\" : { \"count\" : 2.0}}]"), results);
}
@Test
public void should_tojson_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); ; return tojson({\"count\": res}); };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
// Some difference with real mongo on space
assertEquals(fongoRule.parse("[{ \"_id\" : { \"url\" : \"www.google.com\"} , \"value\" : \"{\\\"count\\\":2}\"}, { \"_id\" : { \"url\" : \"www.no-fucking-idea.com\"} , \"value\" : \"{\\\"count\\\":3}\"}]"), results);
}
@Test
public void should_tojsononeline_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); ; return tojsononeline({\"count\": res}); };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
// Some difference with real mongo on space
assertEquals(fongoRule.parse("[{ \"_id\" : { \"url\" : \"www.google.com\"} , \"value\" : \"{\\\"count\\\":2}\"}, { \"_id\" : { \"url\" : \"www.no-fucking-idea.com\"} , \"value\" : \"{\\\"count\\\":3}\"}]"), results);
}
@Test
public void should_NumberInt_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberInt(res)}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 2D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 3D))),
results);
}
@Test
public void should_NumberInttoNumber_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberInt(res).toNumber()}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 2D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 3D))),
results);
}
@Test
public void should_NumberIntvalueOf_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberInt(res).valueOf()}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 2D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 3D))),
results);
}
@Test
public void should_NumberInttoString_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); printjson(res); return {\"count\": NumberInt(res).toString()}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", "NumberInt(2)")),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", "NumberInt(3)"))),
results);
}
@Test
public void should_NumberLong_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberLong(res)}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 2D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 3D))),
results);
}
@Test
public void should_internal_NumberLong_work() {
// Given
DBCollection coll = fongoRule.insertJSON(fongoRule.newCollection(), "[{url: \"www.google.com\", date: 1411004152944 }]");
String map = "function(){ emit(this.url, {date: this.date}); };";
String reduce = "function(key, values){ var res = []; values.forEach(function(v){ res.push(v.date); }); return res; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", "www.google.com").append("value", Arrays.asList((double) 1411004152944L))),
results);
}
@Test
public void should_NumberLongtoNumber_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberLong(res).toNumber()}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 2D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 3D))),
results);
}
@Test
public void should_NumberLongvalueOf_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberLong(res).valueOf()}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 2D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 3D))),
results);
}
@Test
public void should_NumberLongtoString_works() {
// Given
DBCollection coll = newCollectionWithUrls();
String map = "function(){ emit({url: this.url}, 1); };";
String reduce = "function(key, values){ var res = 0.0; values.forEach(function(v){ res += 1.0}); return {\"count\": NumberLong(res).toString()}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", "NumberLong(2)")),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", "NumberLong(3)"))),
results);
}
@Test
public void should_NumberLongvalueOf_with_array_of_long_works() {
// Given
final DBCollection coll = fongoRule.newCollection();
coll.insert(new BasicDBObject("url", "www.google.com").append("date", Util.wrap(asList(1L, 2L, 3L, 4L))),
new BasicDBObject("url", "www.google.com").append("date", Util.wrap(asList(2L, 3L, 4L))),
new BasicDBObject("url", "www.no-fucking-idea.com").append("date", Util.wrap(asList(2L, 3L, 4L))),
new BasicDBObject("url", "www.no-fucking-idea.com").append("date", Util.wrap(asList(12L, 3L, 4L))));
String map = "function(){ emit({url: this.url}, this.date); };";
String reduce = "function(key, values){ var res = 0; values.forEach(function(v){ v.forEach(function(l) { res += l.toNumber()})}); return {\"count\": res}; };";
// When
final MapReduceOutput result = coll.mapReduce(map, reduce, "result", new BasicDBObject());
// Then
List<DBObject> results = fongoRule.newCollection("result").find().toArray();
assertEquals(asList(new BasicDBObject("_id", new BasicDBObject("url", "www.google.com")).append("value", new BasicDBObject("count", 19D)),
new BasicDBObject("_id", new BasicDBObject("url", "www.no-fucking-idea.com")).append("value", new BasicDBObject("count", 28D))),
results);
}
private DBCollection newCollectionWithUrls() {
return fongoRule.insertJSON(fongoRule.newCollection(), "[{url: \"www.google.com\", date: 1, trash_data: 5 },\n" +
" {url: \"www.no-fucking-idea.com\", date: 1, trash_data: 13 },\n" +
" {url: \"www.google.com\", date: 1, trash_data: 1 },\n" +
" {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 69 },\n" +
" {url: \"www.no-fucking-idea.com\", date: 2, trash_data: 256 }]");
}
} | true |
8f7f10065f693a5c1316ad6e03f75f98848ba10b | Java | PPPPPOSSTE/Bigdata | /JavaSE/src/test/java/com/ftrue/day19thread/thread/demo07/Demo07Thread.java | UTF-8 | 954 | 3.53125 | 4 | [] | no_license | package com.ftrue.day19thread.thread.demo07;
/**
* @ClassName: Demo05Thread
* @Description:
* @Author: zhiqi zhang on 2021/7/21 11:32
* @Version: 1.0
*/
/**
同步方法:
修饰符 synchronized 返回值类型 方法名 () {}
特点:
同步方法在同一时间只能被唯一线程对象所调用,其他线程处理阻塞状态(排队)
换种说法:在同一时间,栈内存中只能存在唯一的同步方法,
只有当同步方法执行完毕出栈,其它线程才能继续调用
*/
public class Demo07Thread {
public static void main(String[] args) {
//创建线程任务对象
Ticket ticket = new Ticket();
//创建三个窗口对象
Thread t1 = new Thread(ticket, "窗口1");
Thread t2 = new Thread(ticket, "窗口2");
Thread t3 = new Thread(ticket, "窗口3");
//同时卖票
t1.start();
t2.start();
t3.start();
}
}
| true |
917ea9a138335da3b7b4b0f941e2bc8ce5553f8d | Java | SETCCEresearch/smpconnector | /src/main/java/org/holodeckb2b/esensconnector/persistency/SimpleSBDHData.java | UTF-8 | 5,139 | 1.773438 | 2 | [] | no_license | /* */ package org.holodeckb2b.esensconnector.persistency;
/* */
/* */ import java.io.Serializable;
/* */ import javax.persistence.Column;
/* */ import javax.persistence.Entity;
/* */ import javax.persistence.GeneratedValue;
/* */ import javax.persistence.Id;
/* */ import javax.persistence.NamedQueries;
/* */ import javax.persistence.Table;
/* */ import org.holodeckb2b.common.util.Utils;
/* */ import org.holodeckb2b.esensconnector.submit.ISBDHHandler;
/* */
/* */
/* */ @Entity
/* */ @Table(name="SBDH_INFO")
/* */ @NamedQueries({@javax.persistence.NamedQuery(name="GetSBDHInfoForMsgId", query="SELECT si FROM SimpleSBDHData si WHERE si.ebmsMessageId = :ebMSMsgId AND si.direction = :direction ")})
/* */ public class SimpleSBDHData
/* */ implements Serializable
/* */ {
/* */ @Id
/* */ @GeneratedValue
/* */ long OID;
/* */ String ebmsMessageId;
/* */ Direction direction;
/* */ String receiverId;
/* */ String receiverIdScheme;
/* */ String senderId;
/* */ String senderIdScheme;
/* */ String instanceId;
/* */ @Column(length=1024)
/* */ String documentId;
/* */ @Column(length=1024)
/* */ String documentName;
/* */ String documentInstanceIdentifier;
/* */ @Column(length=1024)
/* */ String processId;
/* */ byte[] digest;
/* */ public SimpleSBDHData() {}
/* */
/* */ public static enum Direction
/* */ {
/* 42 */ IN, OUT;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ private Direction() {}
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* 103 */ boolean remEvidenceRequired = false;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public SimpleSBDHData(ISBDHHandler docData, byte[] digest, String ebMSMessageId, Direction direction)
/* */ {
/* 118 */ if (Utils.isNullOrEmpty(ebMSMessageId)) {
/* 119 */ throw new IllegalArgumentException("ebMS messageId MUST NOT be null or empty");
/* */ }
/* 121 */ this.direction = direction;
/* 122 */ this.ebmsMessageId = ebMSMessageId;
/* 123 */ this.digest = digest;
/* 124 */ this.documentId = docData.getDocumentId();
/* 125 */ this.documentName = docData.getDocumentName();
/* 126 */ this.documentInstanceIdentifier = docData.getDocumentInstanceIdentifier();
/* 127 */ this.instanceId = docData.getInstanceId();
/* 128 */ this.processId = docData.getProcessId();
/* 129 */ this.remEvidenceRequired = docData.isNonRepudiationRequired();
/* 130 */ this.receiverId = docData.getFirstReceiverIdValue();
/* 131 */ this.receiverIdScheme = docData.getFirstReceiverIdScheme();
/* 132 */ this.senderId = docData.getFirstSenderIdValue();
/* 133 */ this.senderIdScheme = docData.getFirstSenderIdScheme();
/* */ }
/* */
/* */ public String getEbmsMessageId() {
/* 137 */ return this.ebmsMessageId;
/* */ }
/* */
/* */ public byte[] getDigest() {
/* 141 */ return this.digest;
/* */ }
/* */
/* */ public String getReceiverId() {
/* 145 */ return this.receiverId;
/* */ }
/* */
/* */ public String getReceiverIdScheme() {
/* 149 */ return this.receiverIdScheme;
/* */ }
/* */
/* */ public String getSenderId() {
/* 153 */ return this.senderId;
/* */ }
/* */
/* */ public String getSenderIdScheme() {
/* 157 */ return this.senderIdScheme;
/* */ }
/* */
/* */ public String getInstanceId() {
/* 161 */ return this.instanceId;
/* */ }
/* */
/* */ public String getDocumentId() {
/* 165 */ return this.documentId;
/* */ }
/* */
/* */ public String getDocumentName() {
/* 169 */ return this.documentName;
/* */ }
/* */
/* */ public String getDocumentInstanceIdentifier() {
/* 173 */ return this.documentInstanceIdentifier;
/* */ }
/* */
/* */ public String getProcessId() {
/* 177 */ return this.processId;
/* */ }
/* */
/* */ public boolean isREMEvidenceRequired() {
/* 181 */ return this.remEvidenceRequired;
/* */ }
/* */ }
/* Location: C:\Users\jure\Desktop\esensconnector-0.7-SNAPSHOT.jar!\org\holodeckb2b\esensconnector\persistency\SimpleSBDHData.class
* Java compiler version: 7 (51.0)
* JD-Core Version: 0.7.1
*/ | true |
80323190b38ea730f6dee3f0006f4e2d504e3d53 | Java | LuoDi-Nate/ownChat | /src/test/java/com/diwa/serverTest/TestSendPackageToServer.java | UTF-8 | 1,063 | 2.28125 | 2 | [] | no_license | package com.diwa.serverTest;
import com.diwa.common.dto.MessageDto;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/**
* Created by di on 30/4/15.
*/
public class TestSendPackageToServer {
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
DatagramSocket ds = new DatagramSocket();
MessageDto md = new MessageDto();
md.setOperatorNickName("diwa");
md.setOption(0);
md.setContext("lalala");
String sendStr = objectMapper.writeValueAsString(md);
System.out.println(sendStr);
byte[] sendByte = sendStr.getBytes();
System.out.println(sendByte);
DatagramPacket dp = new DatagramPacket(sendByte, sendByte.length, InetAddress.getByName("127.0.0.1"), 9999);
ds.send(dp);
ds.close();
}
}
| true |
248da7c584da97aeefb15f5401b9ccbc60c8d10c | Java | genepattern/genepattern-server | /test/src/org/genepattern/drm/TestMemoryUnit.java | UTF-8 | 1,611 | 2.109375 | 2 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | /*******************************************************************************
* Copyright (c) 2003-2022 Regents of the University of California and Broad Institute. All rights reserved.
*******************************************************************************/
package org.genepattern.drm;
import static org.junit.Assert.assertEquals;
import org.genepattern.drm.Memory.Unit;
import org.junit.Test;
public class TestMemoryUnit {
@Test
public void preferredUnitBytes() {
assertEquals("512 bytes", Unit.b, Unit.getPreferredUnit( 512L ));
}
@Test
public void preferredUnitKb_exact() {
assertEquals("1024 bytes", Unit.kb, Unit.getPreferredUnit( 1024L ));
}
@Test
public void preferredUnitMb_exact() {
assertEquals("1048576 bytes", Unit.mb, Unit.getPreferredUnit( 1048576L ));
}
@Test
public void preferredUnitMb() {
assertEquals("2048576 bytes", Unit.mb, Unit.getPreferredUnit( 2048576L ));
}
@Test
public void preferredUnitGb() {
assertEquals("3073741824 bytes", Unit.gb, Unit.getPreferredUnit(3073741824L));
}
@Test
public void preferredUnitTb() {
assertEquals("4099511627776 bytes", Unit.tb, Unit.getPreferredUnit(4099511627776L));
}
@Test
public void preferredUnitPb_exact() {
assertEquals("1125899906842624 bytes", Unit.pb, Unit.getPreferredUnit(1125899906842624L));
}
@Test
public void preferredUnitPb() {
assertEquals("58125899906842624 bytes", Unit.pb, Unit.getPreferredUnit(58125899906842624L));
}
}
| true |
1a40126a735a2f457a70aa3f3ebcbe4f0280dc2b | Java | pyt8756/CashFlow | /mylibrary/src/main/java/com/pyt/mylibrary/utils/RxUtils.java | UTF-8 | 1,128 | 2.4375 | 2 | [] | no_license | package com.pyt.mylibrary.utils;
import android.view.View;
import com.jakewharton.rxbinding2.view.RxView;
import java.util.concurrent.TimeUnit;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
/**
* rx utils
* Created by pengyutao on 2017/6/10.
*/
public class RxUtils {
public static void click(final View view, int second, final View.OnClickListener listener) {
if (view == null || listener == null) {
throw new IllegalArgumentException("view or runnable can not be null");
}
RxView.clicks(view)
.throttleFirst(second, TimeUnit.SECONDS)
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Object>() {
@Override
public void accept(@NonNull Object o) throws Exception {
listener.onClick(view);
}
});
}
public static void click(View view, View.OnClickListener listener) {
click(view, 1, listener);
}
}
| true |
70f29f46d751a15dff53768b9f371d80ae59a63f | Java | hcoles/pitest | /pitest/src/main/java/org/pitest/testapi/Description.java | UTF-8 | 2,236 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2010 Henry Coles
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.pitest.testapi;
import java.io.Serializable;
import java.util.Objects;
public final class Description implements Serializable {
private static final long serialVersionUID = 1L;
private final String testClass;
private final String name;
public Description(final String name) {
this(name, (String) null);
}
public Description(final String name, final Class<?> testClass) {
this(name, testClass.getName());
}
public Description(final String name, final String testClass) {
this.testClass = internIfNotNull(testClass);
this.name = name;
}
private String internIfNotNull(final String string) {
if (string == null) {
return null;
}
return string.intern();
}
public String getFirstTestClass() {
return this.testClass;
}
public String getQualifiedName() {
if ((this.testClass != null) && !this.testClass.equals(this.getName())) {
return this.getFirstTestClass() + "." + this.getName();
} else {
return this.getName();
}
}
public String getName() {
return this.name;
}
@Override
public int hashCode() {
return Objects.hash(testClass, name);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final Description other = (Description) obj;
return Objects.equals(testClass, other.testClass)
&& Objects.equals(name, other.name);
}
@Override
public String toString() {
return "Description [testClass=" + this.testClass + ", name=" + this.name
+ "]";
}
}
| true |
5f00d852a653fb40336ed1ed7312b886a9908c87 | Java | OneCode182/reto3 | /src/main/java/usa/ciclo3/reto3/repositories/ClientRepo.java | UTF-8 | 914 | 2.15625 | 2 | [] | no_license | /** < - - - - - - - - { } - - - - - - - - > */
package usa.ciclo3.reto3.repositories;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import usa.ciclo3.reto3.models.Client;
import usa.ciclo3.reto3.repositories.interfaces.ClientInterface;
@Repository
public class ClientRepo {
/** < - - - - - - - - { Atributos } - - - - - - - - > */
@Autowired
private ClientInterface crud;
/** < - - - - - - - - { Metodos } - - - - - - - - > */
public List<Client> getAll() {
return (List<Client>) crud.findAll();
}
public Optional<Client> getClient(int id) {
return crud.findById(id);
}
public Client save(Client client) {
return crud.save(client);
}
}
| true |
bc4171894b1e0db94159c54c7ae0d4e5011f4c51 | Java | martixZero/spring-cloud-alibaba | /spring-cloud-alibaba-nacos-config/src/test/java/org/springframework/cloud/alibaba/nacos/NacosConfigHealthIndicatorTests.java | UTF-8 | 2,079 | 1.78125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.alibaba.nacos;
import org.junit.Test;
import org.springframework.boot.actuate.health.Health;
import org.springframework.cloud.alibaba.nacos.endpoint.NacosConfigHealthIndicator;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author pbting
* @date 2019-01-17 2:58 PM
*/
public class NacosConfigHealthIndicatorTests extends NacosPowerMockitBaseTests {
@Test
public void nacosConfigHealthIndicatorInstance() {
NacosConfigHealthIndicator nacosConfigHealthIndicator = this.context
.getBean(NacosConfigHealthIndicator.class);
assertThat(nacosConfigHealthIndicator != null).isEqualTo(true);
}
@Test
public void testHealthCheck() {
NacosConfigHealthIndicator nacosConfigHealthIndicator = this.context
.getBean(NacosConfigHealthIndicator.class);
Health.Builder builder = Health.up();
Method method = ReflectionUtils.findMethod(NacosConfigHealthIndicator.class,
"doHealthCheck", Health.Builder.class);
ReflectionUtils.makeAccessible(method);
assertThat(method != null).isEqualTo(true);
try {
method.invoke(nacosConfigHealthIndicator, builder);
assertThat(builder != null).isEqualTo(true);
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
}
} | true |
9646449c1a7152496bf27658027ca79ed1d9c3e6 | Java | zhtyu6/Practice | /src/Main2029.java | UTF-8 | 888 | 3.21875 | 3 | [] | no_license | import java.util.Scanner;
public class Main2029 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
sc.nextLine();
for (int i = 1; i <= n; i++) {
String a = sc.nextLine();
char[] b = a.toCharArray();
if (b.length % 2 == 1) {
int x = 0;
int c = (b.length) / 2;
for (int j = 0; j < c; j++) {
if (b[j] == b[b.length - 1 - j]) {
x++;
}
}
if (b.length / 2 == x) {
System.out.println("yes");
} else {
System.out.println("no");
}
} else {
int x = 0;
int c = (b.length) / 2;
for (int j = 0; j < c; j++) {
if (b[j] == b[b.length - 1 - j]) {
x++;
}
}
if (b.length / 2 == x) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}
}
}
| true |
47dae142380cbbe05fe2f88cf4c5f5e34f24b9d0 | Java | jakwer/driving-licence-app | /src/main/java/com/jakub/werbowy/drivinglicenceapp/licence/DrivingLicenceCategoryEntity.java | UTF-8 | 1,475 | 2.421875 | 2 | [] | no_license | package com.jakub.werbowy.drivinglicenceapp.licence;
import com.google.common.base.Objects;
import com.jakub.werbowy.drivinglicenceapp.licence.dto.CategoryNumber;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Entity
@Table(name = "DRIVING_LICENCE_CATEGORY")
@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
class DrivingLicenceCategoryEntity {
@Id
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
private CategoryNumber number;
@NotNull
private LocalDateTime releaseDate;
@NotNull
private LocalDateTime expirationDate;
@ManyToOne
@JoinColumn(name="driving_licence_id")
private DrivingLicenceEntity drivingLicence;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DrivingLicenceCategoryEntity that = (DrivingLicenceCategoryEntity) o;
return number == that.number &&
Objects.equal(releaseDate, that.releaseDate) &&
Objects.equal(expirationDate, that.expirationDate) &&
Objects.equal(drivingLicence, that.drivingLicence);
}
@Override
public int hashCode() {
return Objects.hashCode(number, releaseDate, expirationDate, drivingLicence);
}
}
| true |
c1d335570fa263e470190f4e7544279628e8767a | Java | verve111/alfresco3.4.d | /root/projects/repository/source/java/org/alfresco/repo/node/index/IndexRemoteTransactionTracker.java | UTF-8 | 1,972 | 1.710938 | 2 | [] | no_license | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.node.index;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Component to check and recover the indexes.
*
* @deprecated Deprecated as of 1.4.5. Use {@linkplain IndexTransactionTracker}
*
* @author Derek Hulley
*/
public class IndexRemoteTransactionTracker extends AbstractReindexComponent
{
private static Log logger = LogFactory.getLog(IndexRemoteTransactionTracker.class);
/**
* Dumps an error message.
*/
public IndexRemoteTransactionTracker()
{
logger.warn(
"The component 'org.alfresco.repo.node.index.IndexRemoteTransactionTracker' " +
"has been replaced by 'org.alfresco.repo.node.index.IndexTransactionTracker' \n" +
"See the extension sample file 'index-tracking-context.xml.sample'. \n" +
"See http://wiki.alfresco.com/wiki/High_Availability_Configuration_V1.4_to_V2.1#Lucene_Index_Synchronization.");
}
/**
* As of release 1.4.5, 2.0.5 and 2.1.1, this property is no longer is use.
*/
public void setRemoteOnly(boolean remoteOnly)
{
}
@Override
protected void reindexImpl()
{
}
} | true |
5de6918af3b76b7a5deed383e8cb8c76de57ca0b | Java | EdgarLiu2/java_leetcode | /src/main/java/edgar/spring/learning1/app/AppConfig.java | UTF-8 | 162 | 1.546875 | 2 | [
"Apache-2.0"
] | permissive | package edgar.spring.learning1.app;
import edgar.spring.learning1.spring.ComponentScan;
@ComponentScan("edgar.springlearning.app")
public class AppConfig {
}
| true |
817fdbd517974341c65bce3aef6bac0ba77c7076 | Java | wujintao630/springcloud-platform | /scp-test/src/main/java/com/tonytaotao/scp/test/mapper/CommodityStorageMapper.java | UTF-8 | 288 | 1.5 | 2 | [
"Apache-2.0"
] | permissive | package com.tonytaotao.scp.test.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.tonytaotao.scp.test.entity.CommodityStorage;
/**
* 商品库存Mapper
* @author tonytaotao
*/
public interface CommodityStorageMapper extends BaseMapper<CommodityStorage> {
}
| true |
0c533d07bfe2a0e02b6762bd15907d29a017a74c | Java | faraaz-ahmed/java-spring-examples | /CalculatorSoapWs/src/com/demo/spring/Calculator.java | UTF-8 | 384 | 2.53125 | 3 | [] | no_license | package com.demo.spring;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.xml.ws.Endpoint;
@WebService
public class Calculator {
@WebMethod
public int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println("Web Service Started!");
Endpoint.publish("http://localhost:8282/service/cal", new Calculator());
}
} | true |
f1a42241c330c3d991eaad12d8493b10a5907786 | Java | chromium/chromium | /chrome/android/java/src/org/chromium/chrome/browser/compositor/bottombar/contextualsearch/ContextualSearchPanelMetrics.java | UTF-8 | 10,988 | 1.796875 | 2 | [
"BSD-3-Clause"
] | permissive | // Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.bottombar.contextualsearch;
import org.chromium.base.TimeUtils;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel.PanelState;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel.StateChangeReason;
import org.chromium.chrome.browser.contextualsearch.ContextualSearchHeuristics;
import org.chromium.chrome.browser.contextualsearch.ContextualSearchUma;
import org.chromium.chrome.browser.contextualsearch.QuickActionCategory;
import org.chromium.chrome.browser.contextualsearch.ResolvedSearchTerm;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.sync.SyncServiceFactory;
/**
* This class is responsible for all the logging triggered by activity of the
* {@link ContextualSearchPanel}. Typically this consists of tracking user activity
* logging that to UMA when the interaction ends as the panel is dismissed.
*/
public class ContextualSearchPanelMetrics {
// Flags for logging.
private boolean mDidSearchInvolvePromo;
private boolean mWasSearchContentViewSeen;
private boolean mIsPromoActive;
private boolean mHasExitedPeeking;
private boolean mHasExitedExpanded;
private boolean mHasExitedMaximized;
private boolean mIsSerpNavigation;
private boolean mWasActivatedByTap;
@ResolvedSearchTerm.CardTag
private int mCardTag;
private boolean mWasQuickActionShown;
private int mQuickActionCategory;
private boolean mWasQuickActionClicked;
// Time when the panel was triggered (not reset by a chained search).
// Panel transitions are animated so mPanelTriggerTimeNs will be less than mFirstPeekTimeNs.
private long mPanelTriggerTimeFromTapNs;
// Time when the panel peeks into view (not reset by a chained search).
// Used to log total time the panel is showing (not closed).
private long mFirstPeekTimeNs;
// Time when a search request was started. Reset by chained searches.
// Used to log the time it takes for a Search Result to become available.
private long mSearchRequestStartTimeNs;
// The current set of heuristics that should be logged with results seen when the panel closes.
private ContextualSearchHeuristics mResultsSeenExperiments;
/** Whether the Search was prefetched or not. */
private boolean mWasPrefetch;
/**
* Whether we were able to start painting the document in the Content View so the user could
* actually see the SRP.
*/
private boolean mDidFirstNonEmptyPaint;
/**
* Log information when the panel's state has changed.
* @param fromState The state the panel is transitioning from.
* @param toState The state that the panel is transitioning to.
* @param reason The reason for the state change.
* @param profile The current {@link Profile}.
*/
public void onPanelStateChanged(@PanelState int fromState, @PanelState int toState,
@StateChangeReason int reason, Profile profile) {
// Note: the logging within this function includes the promo, unless specifically
// excluded.
boolean isStartingSearch = isStartingNewContextualSearch(toState, reason);
boolean isEndingSearch = isEndingContextualSearch(fromState, toState, isStartingSearch);
boolean isChained = isStartingSearch && isOngoingContextualSearch(fromState);
boolean isSameState = fromState == toState;
boolean isFirstExitFromPeeking = fromState == PanelState.PEEKED && !mHasExitedPeeking
&& (!isSameState || isStartingSearch);
boolean isFirstExitFromExpanded = fromState == PanelState.EXPANDED && !mHasExitedExpanded
&& !isSameState;
boolean isFirstExitFromMaximized =
fromState == PanelState.MAXIMIZED && !mHasExitedMaximized && !isSameState;
if (isEndingSearch) {
long panelViewDurationMs =
(System.nanoTime() - mFirstPeekTimeNs) / TimeUtils.NANOSECONDS_PER_MILLISECOND;
ContextualSearchUma.logPanelViewDurationAction(panelViewDurationMs);
if (!mIsPromoActive) {
ContextualSearchUma.logResultsSeen(mWasSearchContentViewSeen, mWasActivatedByTap);
}
ContextualSearchUma.logCardTagSeen(mWasSearchContentViewSeen, mCardTag);
if (mWasQuickActionShown) {
ContextualSearchUma.logQuickActionResultsSeen(mWasSearchContentViewSeen,
mQuickActionCategory);
ContextualSearchUma.logQuickActionClicked(
mWasQuickActionClicked, mQuickActionCategory);
}
if (mResultsSeenExperiments != null) {
mResultsSeenExperiments.logResultsSeen(
mWasSearchContentViewSeen, mWasActivatedByTap);
if (!isChained) mResultsSeenExperiments = null;
}
if (mWasActivatedByTap) {
ContextualSearchUma.logTapResultsSeen(
mWasSearchContentViewSeen, SyncServiceFactory.getForProfile(profile));
}
ContextualSearchUma.logAllResultsSeen(mWasSearchContentViewSeen);
if (mWasSearchContentViewSeen) {
ContextualSearchUma.logAllSearches(/* wasRelatedSearches */ false);
}
ContextualSearchUma.logCountedSearches(
mWasSearchContentViewSeen, mDidFirstNonEmptyPaint, mWasPrefetch);
}
if (isStartingSearch) {
mFirstPeekTimeNs = System.nanoTime();
mWasActivatedByTap = reason == StateChangeReason.TEXT_SELECT_TAP;
}
@StateChangeReason
int reasonForLogging = mIsSerpNavigation ? StateChangeReason.SERP_NAVIGATION : reason;
// Log individual user actions so they can be sequenced.
ContextualSearchUma.logPanelStateUserAction(toState, reasonForLogging);
// We can now modify the state.
if (isFirstExitFromPeeking) {
mHasExitedPeeking = true;
} else if (isFirstExitFromExpanded) {
mHasExitedExpanded = true;
} else if (isFirstExitFromMaximized) {
mHasExitedMaximized = true;
}
if (reason == StateChangeReason.SERP_NAVIGATION) {
mIsSerpNavigation = true;
}
if (isEndingSearch) {
mDidSearchInvolvePromo = false;
mWasSearchContentViewSeen = false;
mHasExitedPeeking = false;
mHasExitedExpanded = false;
mHasExitedMaximized = false;
mIsSerpNavigation = false;
mWasQuickActionShown = false;
mQuickActionCategory = QuickActionCategory.NONE;
mCardTag = ResolvedSearchTerm.CardTag.CT_NONE;
mWasQuickActionClicked = false;
mPanelTriggerTimeFromTapNs = 0;
mDidFirstNonEmptyPaint = false;
mWasPrefetch = false;
}
}
/**
* Sets that the contextual search involved the promo.
*/
public void setDidSearchInvolvePromo() {
mDidSearchInvolvePromo = true;
}
/**
* Sets that the Search Content View was seen.
*/
public void setWasSearchContentViewSeen() {
mWasSearchContentViewSeen = true;
}
/**
* Sets whether the promo is active.
*/
public void setIsPromoActive(boolean shown) {
mIsPromoActive = shown;
}
/**
* @param cardTag The indicator tag for the kind of card shown.
*/
public void setCardShown(@ResolvedSearchTerm.CardTag int cardTag) {
mCardTag = cardTag;
}
/**
* @param wasQuickActionShown Whether a quick action was shown in the Contextual Search Bar.
* @param quickActionCategory The {@link QuickActionCategory} for the quick action.
*/
public void setWasQuickActionShown(boolean wasQuickActionShown, int quickActionCategory) {
mWasQuickActionShown = wasQuickActionShown;
if (mWasQuickActionShown) mQuickActionCategory = quickActionCategory;
}
/**
* Sets |mWasQuickActionClicked| to true.
*/
public void setWasQuickActionClicked() {
mWasQuickActionClicked = true;
}
/**
* Should be called when the panel first starts showing due to a tap.
*/
public void onPanelTriggeredFromTap() {
mPanelTriggerTimeFromTapNs = System.nanoTime();
}
/**
* Called to record the time when a search request started, for resolve and prefetch timing.
*/
public void onSearchRequestStarted() {
mSearchRequestStartTimeNs = System.nanoTime();
}
/**
* Notifies that we were able to start painting the document in the Content View so the user can
* actually see the SRP.
* @param didPrefetch Whether this was a prefetched SRP.
*/
public void onFirstNonEmptyPaint(boolean didPrefetch) {
mDidFirstNonEmptyPaint = true;
mWasPrefetch = didPrefetch;
}
/**
* Sets the experiments to log with results seen.
* @param resultsSeenExperiments The experiments to log when the panel results are known.
*/
public void setResultsSeenExperiments(ContextualSearchHeuristics resultsSeenExperiments) {
mResultsSeenExperiments = resultsSeenExperiments;
}
/**
* Determine whether a new contextual search is starting.
* @param toState The contextual search state that will be transitioned to.
* @param reason The reason for the search state transition.
* @return Whether a new contextual search is starting.
*/
private boolean isStartingNewContextualSearch(
@PanelState int toState, @StateChangeReason int reason) {
return toState == PanelState.PEEKED
&& (reason == StateChangeReason.TEXT_SELECT_TAP
|| reason == StateChangeReason.TEXT_SELECT_LONG_PRESS);
}
/**
* Determine whether a contextual search is ending.
* @param fromState The contextual search state that will be transitioned from.
* @param toState The contextual search state that will be transitioned to.
* @param isStartingSearch Whether a new contextual search is starting.
* @return Whether a contextual search is ending.
*/
private boolean isEndingContextualSearch(
@PanelState int fromState, @PanelState int toState, boolean isStartingSearch) {
return isOngoingContextualSearch(fromState)
&& (toState == PanelState.CLOSED || isStartingSearch);
}
/**
* @param fromState The state the panel is transitioning from.
* @return Whether there is an ongoing contextual search.
*/
private boolean isOngoingContextualSearch(@PanelState int fromState) {
return fromState != PanelState.UNDEFINED && fromState != PanelState.CLOSED;
}
}
| true |
2be58105487d0863e0533f07a30b95cff4d10e6b | Java | divyajalikoppa/Leetcode | /Interview Bit/Arrays/Flip.java | UTF-8 | 3,043 | 3.890625 | 4 | [] | no_license | /* Question:
You are given a binary string(i.e. with characters 0 and 1) S consisting of characters S1, S2, …, SN. In a single operation, you can choose two indices L and R such that 1 ≤ L ≤ R ≤ N and flip the characters SL, SL+1, …, SR. By flipping, we mean change character 0 to 1 and vice-versa.
Your aim is to perform ATMOST one operation such that in final string number of 1s is maximised. If you don’t want to perform the operation, return an empty array. Else, return an array consisting of two elements denoting L and R. If there are multiple solutions, return the lexicographically smallest pair of L and R.
Notes:
Pair (a, b) is lexicographically smaller than pair (c, d) if a < c or, if a == c and b < d.
For example,
S = 010
Pair of [L, R] | Final string
_______________|_____________
[1 1] | 110
[1 2] | 100
[1 3] | 101
[2 2] | 000
[2 3] | 001
We see that two pairs [1, 1] and [1, 3] give same number of 1s in final string. So, we return [1, 1].
Another example,
If S = 111
No operation can give us more than three 1s in final string. So, we return empty array []. */
//Solution
public class Solution {
public ArrayList<Integer> flip(String A) {
int n=A.length();
int l=0,r=0,L=0,R=0;
int ans=Integer.MIN_VALUE;
int s=0,c=0;
ArrayList<Integer> ansF=new ArrayList<>();
for(int i=0;i<n;i++)
{ if(A.charAt(i)=='1')
c++;
}
if(c==n) return ansF;
for(int i=0;i<n;i++){
if(A.charAt(i)=='0')
{s++; r=i;}
else{
s--;
if(s<0){
s=0;
l=i+1;
r=i+1;
}
}
if(ans<s){
ans=s;
L=l;
R=r;
}
}
ansF.add(L+1);ansF.add(R+1);
return ansF;
}
}
//Solution 2 - if not a string you can replace 0 by 1 and 1 by -1 you can then cal contagious maxm subarray by kadane's algo
//Solution 3
int n = A.length();
int c0=0,c1=0,left=Integer.MAX_VALUE,right=0;
boolean flag=false;
int ansl=0,ansr=0,prev=-1;
for(int i=0;i<A.length();i++){
char c =A.charAt(i);
if(c=='1')c1+=1;
else c0+=1;
if(c0>0)flag =true;
if(c1>c0){
c0=0;
c1=0;
left = Integer.MAX_VALUE;
right=0;
}
else if(c=='0'){
left = Math.min(left,i);
right=i;
if(c0-c1>prev){
ansl = left;
ansr=right;
prev=c0-c1;
}
}
}
if(!flag) return new ArrayList<>(0);
res.add(ansl+1);
res.add(ansr+1);
return res;
| true |
76c82bfdd7bbf4b16519bbc4117cb2b9623b6c7d | Java | PotatoDoge/hotelManager | /src/Tools/TableEmpleadoDepa.java | UTF-8 | 1,047 | 2.359375 | 2 | [] | no_license | package Tools;
public class TableEmpleadoDepa {
private String claveEmpleado;
private String claveDepa;
private String puesto;
private double sueldo;
public TableEmpleadoDepa(String claveEmpleado, String claveDepa, String puesto, double sueldo) {
this.claveEmpleado = claveEmpleado;
this.claveDepa = claveDepa;
this.puesto = puesto;
this.sueldo = sueldo;
}
public String getClaveEmpleado() {
return claveEmpleado;
}
public void setClaveEmpleado(String claveEmpleado) {
this.claveEmpleado = claveEmpleado;
}
public String getClaveDepa() {
return claveDepa;
}
public void setClaveDepa(String claveDepa) {
this.claveDepa = claveDepa;
}
public String getPuesto() {
return puesto;
}
public void setPuesto(String puesto) {
this.puesto = puesto;
}
public double getSueldo() {
return sueldo;
}
public void setSueldo(double sueldo) {
this.sueldo = sueldo;
}
}
| true |
8db2f294fb99cf702ef76174e424591f83b47163 | Java | ventulus95/BaekjoonAnswer | /codeBaekJoon/푼 문제/2018/no5063_TGN.java | UTF-8 | 782 | 2.8125 | 3 | [] | no_license | package codeBaekJoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class no5063_TGN {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T= Integer.parseInt(br.readLine());
while(T-->0){
String t =br.readLine();
StringTokenizer st = new StringTokenizer(t, " ");
int r = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
if(e-c>r){
System.out.println("advertise");
}
if(e-c==r){
System.out.println("does not matter");
}
if(e-c<r){
System.out.println("do not advertise");
}
}
}
}
| true |
c4e70e715bbe7fefcc0625c0e0bfe1d49a0d0290 | Java | areina/elfeed-cljsrn | /react-native-app/android/app/src/main/java/com/elfeedcljsrn/MainActivity.java | UTF-8 | 1,868 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | package com.elfeedcljsrn;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
import com.facebook.react.defaults.DefaultReactActivityDelegate;
import org.devio.rn.splashscreen.SplashScreen;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is
* used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ElfeedCljsrn";
}
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this);
super.onCreate(null);
}
/**
* Returns the instance of the {@link ReactActivityDelegate}. Here we use a
* util class {@link DefaultReactActivityDelegate} which allows you to easily
* enable Fabric and Concurrent React (aka React 18) with two boolean flags.
*/
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new DefaultReactActivityDelegate(
this, getMainComponentName(),
// If you opted-in for the New Architecture, we enable the Fabric
// Renderer.
DefaultNewArchitectureEntryPoint.getFabricEnabled(), // fabricEnabled
// If you opted-in for the New Architecture, we enable Concurrent React
// (i.e. React 18).
DefaultNewArchitectureEntryPoint
.getConcurrentReactEnabled() // concurrentRootEnabled
);
}
}
| true |
f6fe1035b0efd30ff1023b26325a747319ab4cc5 | Java | juliencauwet/climb | /src/main/java/com/julien/climbers/controllers/RoutesController.java | UTF-8 | 977 | 2.21875 | 2 | [] | no_license | package com.julien.climbers.controllers;
import com.julien.climbers.entities.Region;
import com.julien.climbers.service.RegionService;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class RoutesController {
@Autowired
private RegionService regionService;
@RequestMapping(value = "/routes", method = RequestMethod.GET)
public String routes(@RequestParam(value = "name", required = false, defaultValue = "Julien") String name, Model model){
List<Region> regionsList = regionService.getRegion();
model.addAttribute("reglist", regionsList);
model.addAttribute("name", name);
return "routes";
}
}
| true |
b43148cfc8199d798c363d906ac900b60e30c14c | Java | m41na/zesty-router | /router-view/src/main/java/com/practicaldime/router/view/twig/JTwigViewEngine.java | UTF-8 | 2,218 | 2.1875 | 2 | [] | no_license | package com.practicaldime.router.view.twig;
import com.practicaldime.router.core.view.ViewEngine;
import com.practicaldime.router.core.view.ViewProcessor;
import org.jtwig.JtwigModel;
import org.jtwig.JtwigTemplate;
import org.jtwig.resource.reference.ResourceReference;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
public class JTwigViewEngine implements ViewEngine {
private static JTwigViewEngine instance;
private final ViewConfiguration config;
private final ViewProcessor<JtwigTemplate, ResourceReference> view;
private final String templateDir;
private final String templateExt;
private JTwigViewEngine(String templateDir, String templateExt) {
super();
this.templateDir = templateDir;
this.templateExt = templateExt;
this.config = new JTwigViewConfiguration();
this.view = new JTwigViewProcessor(config);
}
public static JTwigViewEngine create(String templateDir, String templateExt) throws IOException {
if (instance == null) {
synchronized (JTwigViewEngine.class) {
instance = new JTwigViewEngine(templateDir, templateExt);
}
}
return instance;
}
public static JTwigViewEngine instance() throws IOException {
return instance;
}
public static ViewConfiguration getConfiguration() throws IOException {
return instance().config;
}
public static ViewProcessor<JtwigTemplate, ResourceReference> getProcessor() throws IOException {
return instance().view;
}
@Override
public String templateDir() {
return this.templateDir;
}
@Override
public String templateExt() {
return this.templateExt;
}
@Override
public String merge(String template, Map<String, Object> model) throws Exception {
String baseDir = System.getProperty("user.dir");
Path path = Paths.get(baseDir, templateDir);
JtwigTemplate resolved = view.resolve(path.resolve(template + "." + templateExt).toString(), "", ResourceReference.file(templateDir));
return resolved.render(JtwigModel.newModel(model));
}
}
| true |
63fc3067df33746cbaeeb3d39471fa9a15adb357 | Java | meisasin/everyday-algorithm | /src/main/java/_20200417/SolutionTest.java | UTF-8 | 648 | 2.34375 | 2 | [] | no_license | package _20200417;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class SolutionTest {
@Test
public void testCanJump() {
assertThat(new Solution().canJump(new int[]{ 2, 3, 1, 1, 4 }), equalTo(true));
assertThat(new Solution().canJump(new int[]{ 3, 2, 1, 0, 4 }), equalTo(false));
assertThat(new Solution().canJump(new int[]{ 2, 0 }), equalTo(true));
assertThat(new Solution().canJump(new int[]{ 2, 1, 0, 0 }), equalTo(false));
assertThat(new Solution().canJump(new int[]{ 2, 5, 0, 3 }), equalTo(true));
}
}
| true |
1261d423d0e7a0053dd8ac6d833e1aa69b14482e | Java | onurtokat/hal-streaming | /src/main/java/com/sun/jersey/server/probes/UriRuleProbeProvider.java | UTF-8 | 379 | 1.546875 | 2 | [] | no_license | //
// Decompiled by Procyon v0.5.30
//
package com.sun.jersey.server.probes;
import java.net.URI;
public class UriRuleProbeProvider
{
public static void requestStart(final URI requestUri) {
}
public static void ruleAccept(final String ruleName, final CharSequence path, final Object resourceClass) {
}
public static void requestEnd() {
}
}
| true |
d92ab16e98c713e74c1375bec54ac3dd4e437c6c | Java | christie3198/vision | /app/src/main/java/com/example/signupapp/ui/home/HomeFragment.java | UTF-8 | 1,132 | 1.929688 | 2 | [] | no_license | package com.example.signupapp.ui.home;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.fragment.app.Fragment;
import com.example.signupapp.R;
public class HomeFragment extends Fragment {
Activity context;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
context = getActivity();
View v = inflater.inflate(R.layout.fragment_home, container, false);
Button mapButton = v.findViewById(R.id.mapButton);
mapButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("geo:19.2199536,72.8485876,17z?hl=en"));
startActivity(i);
}
});
return v;
}
} | true |
153cb5e42236ae84e8c2490f9989325c00e1711f | Java | mark-bw/tut5 | /src/main/java/CItut/Calc.java | UTF-8 | 311 | 2.90625 | 3 | [] | no_license | package CItut;
public class Calc{
static int add (int x, int y){
return x + y;
}
static int subtract (int x, int y){
return x - y;
}
public static void main( String[] args )
{
System.out.println(add(3,4));
System.out.println(add(5,6));
}
}
| true |
8014c169436735e96a87dfcf788f96cf4a9b40e7 | Java | Oussez/TDF | /Task_Distrib_FW/src/da/gui/JFrameGui.java | UTF-8 | 3,153 | 2.015625 | 2 | [] | no_license | package da.gui;
import java.util.Date;
import jade.core.AID;
import jade.core.ContainerID;
import jade.domain.introspection.BornAgent;
import jade.domain.introspection.DeadAgent;
import jade.domain.introspection.MovedAgent;
import jade.gui.GuiEvent;
import javax.swing.JFrame;
import da.mas.management.AgentTaskDispatcher;
import da.mas.management.PlatformEventListener;
import da.mas.task.TaskTransportDataObject;
import da.mas.task.TaskWorkflowEvent;
public class JFrameGui extends JFrame implements
PlatformEventListener,
TaskWorkflowEvent,
PlatformGuiInterface
{
protected AgentTaskDispatcher guiAgent;
public JFrameGui(AgentTaskDispatcher agent) {
this.guiAgent = agent;
agent.addPlatformEventListener(this);
agent.addTaskWorkflowListener(this);
}
protected void addTask(TaskTransportDataObject ttdo){
GuiEvent event = new GuiEvent(this, 1);
event.addParameter(ttdo);
guiAgent.postGuiEvent(event);
}
protected void addLocalAgent(String containerId){
GuiEvent event = new GuiEvent(this, 3);
event.addParameter(containerId);
guiAgent.postGuiEvent(event);
}
protected void addRemoteAgent(String containerId){
GuiEvent event = new GuiEvent(this, 4);
event.addParameter(containerId);
guiAgent.postGuiEvent(event);
}
protected void startStopWorkflow(Object obj){
GuiEvent event = new GuiEvent(obj, 2);
guiAgent.postGuiEvent(event);
}
protected void setLoggingMode(String mode){
GuiEvent event = new GuiEvent(this, 5);
event.addParameter(mode);
guiAgent.postGuiEvent(event);
}
@Override
public void taskAdded(TaskTransportDataObject ttdo, Date createdAt) {
// TODO Auto-generated method stub
}
@Override
public void beforePreLocalTask(AID agentId, String taskId,
String containerId) {
// TODO Auto-generated method stub
}
@Override
public void afterPreLocalTask(AID agentId, String taskId, String containerId) {
// TODO Auto-generated method stub
}
@Override
public void beforeRemoteTask(AID agentId, String taskId, String containerId) {
// TODO Auto-generated method stub
}
@Override
public void afterRemoteTask(AID agentId, String taskId, String containerId) {
// TODO Auto-generated method stub
}
@Override
public void beforePostLocalTask(AID agentId, String taskId,
String containerId) {
// TODO Auto-generated method stub
}
@Override
public void afterPostLocalTask(AID agentId, String taskId,
String containerId) {
// TODO Auto-generated method stub
}
@Override
public void taskDone(TaskTransportDataObject ttdo) {
// TODO Auto-generated method stub
}
@Override
public void onContainerAdded(ContainerID container) {
// TODO Auto-generated method stub
}
@Override
public void onContainerRemoved(ContainerID container) {
// TODO Auto-generated method stub
}
@Override
public void onAgentBorn(BornAgent bornAgent) {
// TODO Auto-generated method stub
}
@Override
public void onAgentMove(MovedAgent movedAgent) {
// TODO Auto-generated method stub
}
@Override
public void onAgentDead(DeadAgent deadAgent) {
// TODO Auto-generated method stub
}
}
| true |
bc02e22b36d1b4a6f5c87fe0eb43f3db8b2141e3 | Java | amandeep-verma/java_learning | /2(mar)/src/mar2/MainRunner1.java | UTF-8 | 577 | 3.46875 | 3 | [] | no_license | package mar2;
// printing the class variables without initializing them
class MainRunner1
{
public static void main(String[] args)
{
Pen P1=new Pen();
System.out.println(P1.color);
System.out.println(P1.price);
System.out.println(P1.cname);
System.out.println("-------------");
P1.writing();
System.out.println("main method end");
}
}
class Pen
{
String color;
double price;
String cname;
void writing()
{
System.out.println(color+" color pen is writing");
System.out.println("company name is "+cname);
System.out.println("Price is "+ price);
}
}
| true |
397c402ca64e0e4868ca69cd3d38dd00b8747399 | Java | rafall404/Simple_ChatApp_Java | /src/viewModel/chat/ChatVM.java | UTF-8 | 1,100 | 2.703125 | 3 | [] | no_license | package viewModel.chat;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import model.Message;
import model.ObservableModel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class ChatVM implements PropertyChangeListener {
private StringProperty message;
private ObservableList<Message> chatList;
private ObservableModel model;
public ChatVM(ObservableModel model){
this.model=model;
message = new SimpleStringProperty();
chatList = FXCollections.observableArrayList();
model.addListener(this);
}
public StringProperty getMessage(){
return message;
}
public ObservableList<Message> getChatList(){
return chatList;
}
public void sendMessage(){
model.addMessageToChat(message.get(), "");
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
chatList.add((Message) evt.getNewValue());
}
}
| true |
c3a89dfd982393dfc85cde628945cdbd6b2b748f | Java | chiendarrendor/AlbertsAdalogicalAenigmas | /ada83/src/Solver.java | UTF-8 | 464 | 2.390625 | 2 | [
"MIT"
] | permissive | import grid.logic.flatten.FlattenLogicer;
public class Solver extends FlattenLogicer<Board> {
public Solver(Board b) {
b.forEachCell((x,y)-> {
addLogicStep(new CellLogicStep(x,y));
});
for (char rid : b.getRegionIds()) {
if (!b.regionHasClue(rid)) continue;
addLogicStep(new RegionLogicStep(b.getRegionCells(rid),b.getRegionClue(rid)));
}
addLogicStep(new PathsLogicStep());
}
}
| true |
357d234a91c6e8ae66bae6368d1e22afd0f231d8 | Java | Rishi74744/MyPractice | /src/com/questions/hackerrank/SaveThePrisoner.java | UTF-8 | 728 | 3.140625 | 3 | [] | no_license | package com.questions.hackerrank;
import java.util.Scanner;
public class SaveThePrisoner {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int count = 0;
for(int i = 0; i<t ; i++){
long n = sc.nextInt();
long m = sc.nextInt();
long s = sc.nextInt();
long prisonerNum = 1;
if(m == n){
if(s == 1){
prisonerNum = n;
}else{
prisonerNum = s - 1;
}
}else if(m < n){
long l = m + s;
if(l > n){
prisonerNum = n - l - 1;
}else if(l < n){
prisonerNum = l - 1;
}else{
prisonerNum = n - 1;
}
}else{
long x = m % n;
prisonerNum = x + s - 1;
}
System.out.println(prisonerNum);
}
}
}
| true |
f75a298707d72acdf6ce20b69026a5a1d8bde2e1 | Java | beginsmauel/spring-from-the-trenches | /protected-method-scheduled-job/spring-sec-32/src/main/java/net/petrikainulainen/spring/trenches/scheduling/service/MessageService.java | UTF-8 | 313 | 2.015625 | 2 | [
"Apache-2.0"
] | permissive | package net.petrikainulainen.spring.trenches.scheduling.service;
import org.springframework.security.access.prepost.PreAuthorize;
/**
* @author Petri Kainulainen
*/
public interface MessageService {
/**
* @return The message.
*/
@PreAuthorize("hasRole('ROLE_USER')")
public String getMessage();
}
| true |
131e774ae79f6a0a83b6056bceaf94176dc170c7 | Java | vaghesethu/c-basics | /Hop n Hop/Main.java | UTF-8 | 199 | 2.296875 | 2 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
//Type your code here.
int x,y;
std::cin>>x>>y;
int b,c;
b=(x-3);
c=(y-4);
if(b<c)
std::cout<<c;
else
std::cout<<b;
} | true |
f275d0ae85827d852c802008101154b511e4d17e | Java | kingdas/lesson1 | /pro27A/yc27812oa/src/com/yc/oa/controller/EmployeeController.java | UTF-8 | 719 | 1.984375 | 2 | [] | no_license | package com.yc.oa.controller;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yc.framework.BaseController;
import com.yc.oa.model.Employee;
import com.yc.oa.service.EmployeeService;
@Controller
@RequestMapping("emp")
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping("login")
public String login(Employee emp, HttpSession s) {
Employee e = employeeService.login(emp);
if (e != null) {
s.setAttribute("emp", e);
return "index";
}
return "redirect:/login.jsp";
}
}
| true |
b7c5643b3837de1afcb435ad39f6819cafae3127 | Java | Golpette/networkgeneration | /networkgeneration_steve/Compound.java | UTF-8 | 505 | 3.125 | 3 | [] | no_license |
public class Compound {
private int label;
private String formula;
private int charge;
// Constructor
Compound(int l, String f, int c){
this.label = l;
this.formula = f;
this.charge = c;
}
// Getters
public int getLabel(){
return this.label;
}
public String getFormula(){
return this.formula;
}
public int getCharge(){
return this.charge;
}
// toString
public String toString(){
return "{"+label+","+formula+","+charge+"}";
}
}
| true |