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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
86a2b69617f75d53b7cc68e5618156e72741d57a | Java | dinislam-nur/factory | /src/main/java/ru/iteco/factory/bmw/BmwInterior.java | UTF-8 | 323 | 2.34375 | 2 | [] | no_license | package ru.iteco.factory.bmw;
import ru.iteco.factory.api.AbstractInterior;
public class BmwInterior extends AbstractInterior {
public BmwInterior(String name, String color, String material) {
super(name, color, material);
}
public BmwInterior() {
this("elite", "white", "leather");
}
}
| true |
a7607c81d414c5d053de99cbefe715d7b06bb68c | Java | drsnowflake/FantasyAdventure_Java | /src/main/java/Spells/Offensive/MagicMissile.java | UTF-8 | 241 | 2.546875 | 3 | [] | no_license | package Spells.Offensive;
import Interfaces.ISpell;
public class MagicMissile implements ISpell {
public int numOfDice() {
return 2;
}
public int diceSize() {
return 4;
}
public void cast() {
}
}
| true |
705ff2817d350a7537e42df73d2f7e6b11cdbe40 | Java | laurent-g/triangulation | /src/main/java/eu/georget/triangulation/core/ILocatable.java | UTF-8 | 298 | 2.15625 | 2 | [] | no_license | package eu.georget.triangulation.core;
/**
* Locatable is an interface providing location information
*
* @author laurent
*
* @see Location
*/
public interface ILocatable {
/**
* Return a location
*
* @return Location
*
* @see Location
*/
public Location getLocation();
}
| true |
91ea232a3d5c4d97f53528174e088e0b36d3637e | Java | galihandy/spring-api-template | /src/main/java/com/example/domain/user/ProfileController.java | UTF-8 | 1,284 | 2.046875 | 2 | [] | no_license | package com.example.domain.user;
import com.example.core.model.Profile;
import com.example.domain.user.repositories.ProfileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.projection.ProjectionFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* Created by galih.a.pradana on 7/30/2016.
*/
@RestController
@RequestMapping(value = "/profiles")
public class ProfileController {
@Autowired
private ProfileRepository profileRepository;
@RequestMapping
public List<Profile> getProfiles() {
System.out.println("SIZE PROFILES " + profileRepository.findAll().size());
return profileRepository.findAll();
}
@RequestMapping(value = "/no_desc")
public List<Profile> getProfilesNoDesc() {
System.out.println("SIZE PROFILES " + profileRepository.findAll().size());
return profileRepository.findAll();
}
@RequestMapping(value = "/{userId}")
public Profile getProfile(@RequestParam int userId) {
return profileRepository.findByUserId(userId);
}
}
| true |
e8aff478a3f6ca6cc2aa9970e5bbd8f01a95bd45 | Java | activej/activej | /extra/cloud-dataflow/src/main/java/io/activej/dataflow/node/impl/Upload.java | UTF-8 | 1,985 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2020 ActiveJ LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.activej.dataflow.node.impl;
import io.activej.common.annotation.ExposedInternals;
import io.activej.dataflow.DataflowServer;
import io.activej.dataflow.graph.StreamId;
import io.activej.dataflow.graph.StreamSchema;
import io.activej.dataflow.graph.Task;
import io.activej.dataflow.node.AbstractNode;
import io.activej.dataflow.stats.BinaryNodeStat;
import io.activej.dataflow.stats.NodeStat;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.List;
/**
* Represents a node, which uploads data to a stream.
*
* @param <T> data items type
*/
@ExposedInternals
public final class Upload<T> extends AbstractNode {
public final StreamSchema<T> streamSchema;
public final StreamId streamId;
public BinaryNodeStat stats;
public Upload(int index, StreamSchema<T> streamSchema, StreamId streamId) {
super(index);
this.streamSchema = streamSchema;
this.streamId = streamId;
}
@Override
public Collection<StreamId> getInputs() {
return List.of(streamId);
}
@Override
public void createAndBind(Task task) {
task.bindChannel(streamId, task.get(DataflowServer.class).upload(streamId, streamSchema, stats = new BinaryNodeStat()));
}
@Override
public @Nullable NodeStat getStats() {
return stats;
}
@Override
public String toString() {
return "Upload{type=" + streamSchema + ", streamId=" + streamId + '}';
}
}
| true |
3704c42edc15fd959e941fe5156f3a0a1cb8cd31 | Java | StanislawNagorski/AgendaCheckWeb | /src/main/java/AgendaCheckWeb/Servlets/DownloadServlet.java | UTF-8 | 2,274 | 2.390625 | 2 | [
"MIT"
] | permissive | package AgendaCheckWeb.Servlets;
import AgendaCheckWeb.ReportGenerator;
import AgendaCheckWeb.Utils.ServletUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import static AgendaCheckWeb.Utils.ServletUtils.*;
@WebServlet (name = "DownloadReport", value = "/downloadReport")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//File reportFile = writeReportFile(req);
File reportFile = (File) req.getAttribute(REPORT_FILE);
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
resp.setContentType("APPLICATION/OCTET-STREAM");
resp.setHeader("Content-Disposition","attachment; filename=" + reportFile.getName());
//use inline if you want to view the content in browser, helpful for pdf file
//resp.setHeader("Content-Disposition","inline; filename=" + reportFile.getName());
FileInputStream fileInputStream = new FileInputStream(reportFile);
int i;
while ((i=fileInputStream.read()) != -1) {
out.write(i);
}
fileInputStream.close();
out.close();
req.getRequestDispatcher("/uploader.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
// private File writeReportFile(HttpServletRequest request) throws IOException {
// File gessef = (File) request.getAttribute(GESSEF_FILE);
// File planQ = (File) request.getAttribute(PLANQ_FILE);
// double prodTarget = (double) request.getAttribute(PRODUCTIVITY_TARGET);
//
// ReportGenerator rg = new ReportGenerator(gessef,planQ,prodTarget);
// String downloadPath = getServletContext().getRealPath("") + UPLOAD_DIRECTORY;
//
// return rg.writeFullReport(downloadPath);
// }
}
| true |
4640fe7c8bd63c9a172fb55fe0290d6504e87799 | Java | 201811671102/huya | /HeartReleaseSock/src/main/java/com/cs/heart_release_sock/base/utils/ChannelUtil.java | UTF-8 | 2,452 | 2.234375 | 2 | [] | no_license | package com.cs.heart_release_sock.base.utils;
import com.cs.heart_release_sock.manager.ConnManager;
import com.cs.heart_release_sock.pojo.MessageRecord;
import com.cs.heart_release_sock.protocol.Packet;
import com.cs.heart_release_sock.protocol.Protocol;
import com.cs.heart_release_sock.service.MessageRecordService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Date;
/**
*
* @date 2020/5/21
* @author wangpeng1@huya.com
* @description 服务端回包工具类,封装回包逻辑
*/
@Slf4j
@Configuration
public class ChannelUtil {
public static void write(ChannelHandlerContext ctx, Packet packet) {
ByteBuf buf = ctx.alloc().directBuffer();
BinaryWebSocketFrame resp = new BinaryWebSocketFrame(buf.writeBytes(packet.toByteArray()));
ctx.executor().execute(new Runnable() {
@Override
public void run() {
ctx.writeAndFlush(resp);
}
});
}
public static void write(Channel channel, Packet packet) {
if(channel != null && channel.isWritable()) {
ByteBuf buf = channel.alloc().directBuffer();
BinaryWebSocketFrame resp = new BinaryWebSocketFrame(buf.writeBytes(packet.toByteArray()));
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
channel.writeAndFlush(resp);
}
});
}
}
/**
*
* @param channel
* @param data 是Packet封装好的字节数组
*/
public static void write(Channel channel, byte[] data) {
if(channel != null && channel.isWritable()) {
ByteBuf buf = channel.alloc().directBuffer();
BinaryWebSocketFrame resp = new BinaryWebSocketFrame(buf.writeBytes(data));
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
channel.writeAndFlush(resp);
}
});
}
}
}
| true |
5c64e2f3132ca1a76cefd311d1237181673ee1b5 | Java | ViVaHa/Leetcode_InterviewBit_java | /InterviewBit/max_non_array_neg_sub_array.java | UTF-8 | 1,938 | 2.78125 | 3 | [] | no_license | public class Solution {
public ArrayList<Integer> maxset(ArrayList<Integer> A) {
if(A.size()==0){
return new ArrayList<Integer>();
}
long maxSubArray=-1;
long sumTillNow=-1;
int finalStart=-1;
int finalEnd=-1;
int maxLength=0;
int startIndex=-1;
int i;
int start=-1,end=-1;
for(i=0;i<A.size();i++){
if(A.get(i)>=0){
if(sumTillNow==-1){
start=i;
sumTillNow=0;
}
sumTillNow+=A.get(i);
}else{
if(sumTillNow>=0){
end=i-1;
if(sumTillNow>maxSubArray){
finalStart=start;
finalEnd=end;
maxSubArray=sumTillNow;
maxLength=end-start+1;
}else if(sumTillNow==maxSubArray){
if(end-start+1>maxLength){
finalStart=start;
finalEnd=end;
maxLength=end-start+1;
}
}
}
sumTillNow=-1;
}
}
if(sumTillNow>-1){
if(sumTillNow>maxSubArray){
finalStart=start;
finalEnd=i-1;
}else if(sumTillNow==maxSubArray){
if(i-1-start+1>maxLength){
finalStart=start;
finalEnd=i-1;
}
}
}
//System.out.println(finalStart);
if(finalStart==-1 && finalEnd==-1){
return new ArrayList<Integer>();
}else{
ArrayList<Integer> list = new ArrayList<>();
for(i=finalStart;i<=finalEnd;i++){
list.add(A.get(i));
}
return list;
}
}
}
| true |
26bc91fb9d1ce92a3d355782f4ab664cd8705a9f | Java | AndreeaNenciuCrasi/just-katas | /src/com/company/codewars7/CreditCardMask.java | UTF-8 | 1,716 | 3.640625 | 4 | [] | no_license | package com.example.codewars7;
//Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it.
//
// Your task is to write a function maskify, which changes all but the last four characters into '#'.
//
// Examples
// Maskify.Maskify("4556364607935616"); // should return "############5616"
// Maskify.Maskify("64607935616"); // should return "#######5616"
// Maskify.Maskify("1"); // should return "1"
// Maskify.Maskify(""); // should return ""
//
//// "What was the name of your first pet?"
// Maskify.Maskify("Skippy"); // should return "##ippy"
// Maskify.Maskify("Nananananananananananananananana Batman!"); // should return "####################################man!"
public class CreditCardMask {
public static String maskify(String str) {
if (str.length() <= 4) return str;
String result = "";
for (int i = 0; i < str.length()-4; i++) {
result += "#";
}
return result + str.substring(str.length()-4);
}
}
public static String maskify(String str) {
char[] strChars = str.toCharArray();
for( int i = 0; i < strChars.length - 4; i++ ) {
strChars[i] = '#';
}
return new String(strChars);
}
public static String maskify(String str) {
return str.length()<=4 ? str : str.substring(0,str.length()-4).replaceAll(".","#") + str.substring(str.length()-4);
}
| true |
e15277ba4f7fb4ae0af2557470bcddac403f6595 | Java | apache/servicecomb-java-chassis | /dynamic-config/config-apollo/src/main/java/org/apache/servicecomb/config/archaius/sources/ApolloConfigurationSourceImpl.java | UTF-8 | 5,071 | 1.796875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicecomb.config.archaius.sources;
import static com.netflix.config.WatchedUpdateResult.createIncremental;
import static org.apache.servicecomb.config.client.ConfigurationAction.CREATE;
import static org.apache.servicecomb.config.client.ConfigurationAction.DELETE;
import static org.apache.servicecomb.config.client.ConfigurationAction.SET;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.configuration.Configuration;
import org.apache.servicecomb.config.ConfigMapping;
import org.apache.servicecomb.config.client.ApolloClient;
import org.apache.servicecomb.config.client.ApolloConfig;
import org.apache.servicecomb.config.client.ConfigurationAction;
import org.apache.servicecomb.config.spi.ConfigCenterConfigurationSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableMap;
import com.netflix.config.WatchedUpdateListener;
import com.netflix.config.WatchedUpdateResult;
public class ApolloConfigurationSourceImpl implements ConfigCenterConfigurationSource {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigCenterConfigurationSource.class);
private final Map<String, Object> valueCache = new ConcurrentHashMap<>();
private final List<WatchedUpdateListener> listeners = new CopyOnWriteArrayList<>();
private static final String APOLLO_CONFIG_URL_KEY = "apollo.config.serverUri";
public ApolloConfigurationSourceImpl() {
}
private final UpdateHandler updateHandler = new UpdateHandler();
@VisibleForTesting
UpdateHandler getUpdateHandler() {
return updateHandler;
}
@Override
public int getOrder() {
return ORDER_BASE * 3;
}
@Override
public boolean isValidSource(Configuration localConfiguration) {
if (localConfiguration.getProperty(APOLLO_CONFIG_URL_KEY) == null) {
LOGGER.warn("Apollo configuration source is not configured!");
return false;
}
return true;
}
@Override
public void init(Configuration localConfiguration) {
ApolloConfig.setConcurrentCompositeConfiguration(localConfiguration);
init();
}
private void init() {
ApolloClient apolloClient = new ApolloClient(updateHandler);
apolloClient.refreshApolloConfig();
}
@Override
public void addUpdateListener(WatchedUpdateListener watchedUpdateListener) {
listeners.add(watchedUpdateListener);
}
@Override
public void removeUpdateListener(WatchedUpdateListener watchedUpdateListener) {
listeners.remove(watchedUpdateListener);
}
private void updateConfiguration(WatchedUpdateResult result) {
for (WatchedUpdateListener l : listeners) {
try {
l.updateConfiguration(result);
} catch (Throwable ex) {
LOGGER.error("Error in invoking WatchedUpdateListener", ex);
}
}
}
@Override
public Map<String, Object> getCurrentData() throws Exception {
return valueCache;
}
public List<WatchedUpdateListener> getCurrentListeners() {
return listeners;
}
public class UpdateHandler {
public void handle(ConfigurationAction action, Map<String, Object> config) {
if (config == null || config.isEmpty()) {
return;
}
Map<String, Object> configuration = ConfigMapping.getConvertedMap(config);
if (CREATE.equals(action)) {
valueCache.putAll(configuration);
updateConfiguration(createIncremental(ImmutableMap.copyOf(configuration),
null,
null));
} else if (SET.equals(action)) {
valueCache.putAll(configuration);
updateConfiguration(createIncremental(null,
ImmutableMap.copyOf(configuration),
null));
} else if (DELETE.equals(action)) {
configuration.keySet().forEach(valueCache::remove);
updateConfiguration(createIncremental(null,
null,
ImmutableMap.copyOf(configuration)));
} else {
LOGGER.error("action: {} is invalid.", action.name());
return;
}
LOGGER.warn("Config value cache changed: action:{}; item:{}", action.name(), configuration.keySet());
}
}
}
| true |
812139787ad83988e61b216ebcebd0d1b518c025 | Java | Bo-Deng/Venom17-18 | /TeamCode/src/main/java/org/firstinspires/ftc/teamcode/JewelDetectTest.java | UTF-8 | 8,555 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | package org.firstinspires.ftc.teamcode;
/*
import android.graphics.Bitmap;
import android.os.Environment;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import for_camera_opmodes.OpModeCamera;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.CvException;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import static org.opencv.imgproc.Imgproc.circle;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
//Created by Bo on 9/30/2017.
@Autonomous (name = "JewelDetect", group = "test")
public class JewelDetectTest extends OpModeCamera {
public void startOpenCV() { //loads openCV library from phone via openCVManager
BaseLoaderCallback openCVLoaderCallback = null;
try {
openCVLoaderCallback = new BaseLoaderCallback(hardwareMap.appContext) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
telemetry.addData("OpenCV", "OpenCV Manager connected!");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
} catch (NullPointerException e) {
telemetry.addData("Could not find OpenCV Manager!", "Please install the app from the Google Play Store.");
}
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_3_0, this.hardwareMap.appContext, openCVLoaderCallback)) {
telemetry.addData("Cannot connect to OpenCV Manager", "Failure");
}
}
public Mat imgMat; //Mat = matrix
public Mat CMat; //holds image data
private double dp = 1; //ratio of input resolution to output resolution
private double minDst = 100; //min distance between centers of detected circles
int loopCount = 0; //debugging purposes
public void init() {
startOpenCV(); //load opencvlibrary
startCamera(); //camera init
telemetry.addData("Camera", "Initialized");
telemetry.update();
}
public void loop() {
if (imageReady()) { //when image received from camera
scanCircles();
telemetry.addData("Num of Circles", CMat.cols()); //return number of circles (# of columns = # of circles)
if (CMat.cols() == 2) {
if (JewelColorRED(CMat, 0)) {
if ((getCircleData(CMat, 0)[0]) > (getCircleData(CMat, 1)[0])) {
telemetry.addData("The RED jewel is to the", "RIGHT");
}
else {
telemetry.addData("The RED jewel is to the", "LEFT");
}
}
else {
if ((getCircleData(CMat, 0)[0]) > (getCircleData(CMat, 1)[0])) {
telemetry.addData("The BLUE jewel is to the", "RIGHT");
}
else {
telemetry.addData("The BLUE jewel is to the", "LEFT");
}
}
}
telemetry.update();
if (loopCount < 10 && CMat.cols() == 2) { //saves first 10 successful images to phone gallery
writeToFile(imgMat, CMat); // use this method to print circles in CMat onto the image in imgMat before saving to device
loopCount++;
}
} else {
telemetry.addData("Image not loaded", "Loop count: " + loopCount);
telemetry.update();
}
}
public void writeToFile(Mat mat, Mat circles) { //debugging only; prints images into data files on phone, access through camera roll/gallery
// Draw the circles detected
Imgproc.cvtColor(mat, mat, Imgproc.COLOR_GRAY2RGB, 0); //convert to rgb (so the circle that gets drawn is colored)
int numberOfCircles = (circles.rows() == 0) ? 0 : circles.cols(); //confusing copypasta (retrieves data from mat, draw circle based on data, converts mat to bitmap, saves to system directory = Gallery)
try {
for (int i = 0; i < numberOfCircles; i++) {
double[] circleCoordinates = circles.get(0, i);
int x = (int) circleCoordinates[0];
int y = (int) circleCoordinates[1];
Point center = new Point(x, y);
int r = (int) circleCoordinates[2];
// draw the circle center
circle(mat, center, 5, new Scalar(0, 255, 0), -1);
// draw the circle outline
circle(mat, center, r, new Scalar(0, 0, 255), 6);
}
} catch (Exception e) {
}
Bitmap bmp = null;
try {
bmp = Bitmap.createBitmap(mat.cols(), mat.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(mat, bmp);
} catch (CvException e) {
telemetry.addData("Exception", "creating bitmap: " + e);
}
mat.release();
FileOutputStream out = null;
String filename = "frame" + loopCount + ".png";
File sd = new File(Environment.getExternalStorageDirectory() + "/frames");
boolean success = true;
if (!sd.exists()) {
success = sd.mkdir();
}
if (success) {
File dest = new File(sd, filename);
try {
out = new FileOutputStream(dest);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
} catch (Exception e) {
e.printStackTrace();
telemetry.addData("Exception", "creating bitmap:" + e);
} finally {
try {
if (out != null) {
out.close();
telemetry.addData("File Saved", "Loop Count: " + loopCount);
}
} catch (IOException e) {
telemetry.addData("Error", e);
e.printStackTrace();
}
}
}
}
public Boolean JewelColorRED(Mat circle, int n) { //print what color each ball is (corresponds with JewelSide)
Bitmap img = convertYuvImageToRgb(yuvImage, width, height, 1);
int redValue = 0;
int blueValue = 0;
int pix;
double[] list = getCircleData(circle, n);
if (list != null) {
for (int i = 0; i < list[2]; i++){
pix = img.getPixel((int) list[0] - i, (int) list[1] - i);
redValue += red(pix);
blueValue += blue(pix);
}
for (int i = 0; i < list[2]; i++){
pix = img.getPixel((int) list[0] + i, (int) list[1] + i);
redValue += red(pix);
blueValue += blue(pix);
}
}
else {
telemetry.addData("List is", "NULL");
return null;
}
if (redValue > blueValue)
return true;
return false;
}
public double[] getCircleData(Mat circle, int circnum) { //returns list with specific circle info
double[] list;
try {
list = circle.get(0, circnum);
return list;
} catch (NullPointerException e){
telemetry.addData("No Data Found", e);
return null;
}
}
public void scanCircles() { //simplified loop
if (imageReady()) {
Bitmap img = convertYuvImageToRgb(yuvImage, width, height, 1);
imgMat = new Mat(new Size(img.getWidth(), img.getHeight()), CvType.CV_8UC1);
Utils.bitmapToMat(img, imgMat);
Imgproc.cvtColor(imgMat, imgMat, Imgproc.COLOR_RGB2GRAY, 0);
CMat = new Mat(imgMat.size(), CvType.CV_8UC1);
Imgproc.HoughCircles(imgMat, CMat, Imgproc.CV_HOUGH_GRADIENT, dp, minDst, 70, 35, 75, 125);
telemetry.addData("Image Scan","Successful");
telemetry.update();
} else {
telemetry.addData("Image Scan","Failure");
telemetry.update();
}
}
} */ | true |
c7af2392f257923ed0a7e9d40782aaa3c36027be | Java | langlant/Lexer | /src/Parser.java | UTF-8 | 8,952 | 2.8125 | 3 | [] | no_license |
public class Parser {
private String errorMessage = "";
Lexer lexer = new Lexer("C:\\Users\\Langley\\Desktop\\CIS_675\\digraph.txt");
public String dot_parse() {
graph_parse();
if(errorMessage =="") {
return "Text has no errors!";
} else {
System.out.println(errorMessage);
return errorMessage;
}
}
public void graph_parse() {
if(lexer.currentToken() == TokenType.STRICT) {
lexer.next();
if(lexer.currentToken() == TokenType.DIGRAPH) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.LBRACE) {
lexer.next();
if(stmnt_list()) {
lexer.next();
if(!(lexer.currentToken() == TokenType.RBRACE)) {
lexer.next();
} else if(lexer.currentToken() == TokenType.RBRACE) {
return;
}
}
}
}
} else if(lexer.currentToken() == TokenType.GRAPH) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.LBRACE) {
lexer.next();
if(stmnt_list()) {
lexer.next();
if(!(lexer.currentToken() == TokenType.RBRACE)) {
lexer.next();
} else if(lexer.currentToken() == TokenType.RBRACE) {
return;
}
} else {
errorMessage = "Graph: Must include statement list";
}
} else {
errorMessage ="Graph: ID must be followed by a left brace";
}
} else {
errorMessage = "Graph: must include ID";
}
} else {
errorMessage = "Graph: No Digraph or Graph";
}
}
}
public Boolean stmnt_list() {
if(stmnt()) {
lexer.next();
if(lexer.currentToken() == TokenType.SEMI) {
while(lexer.currentToken() == TokenType.SEMI) {
lexer.next();
if(stmnt()) {
lexer.next();
}
}
}
} else {
errorMessage = "Statment List: No statement list";
return false;
}
return true;
}
public Boolean stmnt() {
if(node_stmnt()) {
lexer.next();
} else if(edge_stmnt()) {
lexer.next();
} else if(attr_stmnt()) {
lexer.next();
} else if(subgraph()) {
lexer.next();
} else if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.EQUAL) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
}
}
}else {
errorMessage = "Statement: No statement";
return false;
}
return true;
}
public Boolean attr_stmnt() {
if(lexer.currentToken() == TokenType.GRAPH) {
lexer.next();
if(attr_list()) {
lexer.next();
}
}else if(lexer.currentToken() == TokenType.NODE) {
lexer.next();
if(attr_list()) {
lexer.next();
}
}else if(lexer.currentToken() == TokenType.NODE) {
lexer.next();
if(attr_list()) {
lexer.next();
}
}else if(lexer.currentToken() == TokenType.EDGE) {
lexer.next();
if(attr_list()) {
lexer.next();
}
}else {
errorMessage = "Attribute Statement: Not a proper statement";
return false;
}
return true;
}
public Boolean attr_list() {
if(lexer.currentToken() == TokenType.LBRACKET) {
lexer.next();
if(a_list()) {
while(lexer.currentToken() == TokenType.RBRACKET) {
lexer.next();
if(lexer.currentToken() == TokenType.LBRACKET) {
lexer.next();
}
}
} else {
errorMessage = "Attribute List: Must have an a list";
return false;
}
} else {
errorMessage = "Attribute List: Must begin with left bracket";
return false;
}
return true;
}
public Boolean a_list() {
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.EQUAL) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.SEMI || lexer.currentToken() == TokenType.COMMA) {
lexer.next();
while(lexer.currentToken() == TokenType.SEMI || lexer.currentToken() == TokenType.COMMA) {
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.EQUAL) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
}
}
}
}
} else {
errorMessage = "A List: Must end with a comma or semi-colon";
return false;
}
} else {
errorMessage = "A List: Must be followed by ID";
return false;
}
} else {
errorMessage = "A List: ID must be follwed by =";
return false;
}
} else {
errorMessage = "A List: Must begin with ID";
return false;
}
return true;
}
public Boolean edge_stmnt() {
if(node_id() || subgraph()) {
lexer.next();
if(edge_RHS()) {
lexer.next();
if(attr_list()) {
lexer.next();
}
} else {
errorMessage = "Edge Statement: Must have edgeRHS";
return false;
}
}
return true;
}
public Boolean edge_RHS() {
if(lexer.currentToken() == TokenType.EDGEOP) {
lexer.next();
if(node_id()) {
lexer.next();
while(lexer.currentToken() == TokenType.EDGEOP || lexer.currentToken() == TokenType.ARROW) {
lexer.next();
if(node_id() || subgraph()) {
lexer.next();
}
}
} else {
errorMessage = "Edge RHS: Edgepop must be followed by node id or subgraph";
return false;
}
} else {
errorMessage = "Edge RHS: Must begin with edgepop";
return false;
}
return true;
}
public Boolean node_stmnt() {
if(node_id()) {
lexer.next();
if(attr_list()) {
lexer.next();
}
} else {
errorMessage = "Node Statment: Must begin with node id";
return false;
}
return true;
}
public Boolean node_id() {
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(port()) {
lexer.next();
} else {
errorMessage = "Node ID: Must be followed by port";
return false;
}
}else {
errorMessage = "Node ID: node id must begin with ID";
return false;
}
return true;
}
public Boolean port() {
if(lexer.currentToken() == TokenType.COLON) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(compass_pt()) {
lexer.next();
}
}else if(compass_pt()) {
lexer.next();
if(compass_pt()) {
lexer.next();
}
}
else {
errorMessage = "Port: Must follow a colon with an ID or compass_pt";
return false;
}
} else {
errorMessage = "Port: Must begin with colon";
return false;
}
return true;
}
public Boolean subgraph() {
if(lexer.currentToken() == TokenType.SUBGRAPH) {
lexer.next();
if(lexer.currentToken() == TokenType.ID) {
lexer.next();
if(lexer.currentToken() == TokenType.LBRACE) {
lexer.next();
if(stmnt_list()) {
lexer.next();
if(lexer.currentToken() == TokenType.RBRACE) {
lexer.next();
} else {
errorMessage = "Subgraph: Must end with }";
return false;
}
} else {
errorMessage = "Subgraph: Must have a statement list";
return false;
}
} else {
errorMessage = "Subgraph: ID ust be followed by {";
return false;
}
} else {
errorMessage = "Subgraph: should have an ID";
return false;
}
} else {
errorMessage = "Subgraph: Must begin with subgraph";
return false;
}
return true;
}
public Boolean compass_pt() {
if(lexer.currentToken() == TokenType.N) {
lexer.next();
} else if(lexer.currentToken() == TokenType.NE) {
lexer.next();
}else if(lexer.currentToken() == TokenType.E) {
lexer.next();
} else if(lexer.currentToken() == TokenType.SE) {
lexer.next();
} else if(lexer.currentToken() == TokenType.S) {
lexer.next();
} else if(lexer.currentToken() == TokenType.SW) {
lexer.next();
} else if(lexer.currentToken() == TokenType.W) {
lexer.next();
} else if(lexer.currentToken() == TokenType.NW) {
lexer.next();
} else if(lexer.currentToken() == TokenType.C) {
lexer.next();
} else {
errorMessage = "Compass: Must declare a direction";
return false;
}
return true;
}
}
| true |
2a58dc72c4cf66052cf3a457d109e37476479421 | Java | doyounghyeon/JAVA_kit1 | /com.kita.first/src/com/kita/first/For2.java | UTF-8 | 281 | 2.921875 | 3 | [] | no_license | package com.kita.first;
public class For2 {
public static void main(String[] args) {
for(int i=0; i<5; i++) {
for(int j=0; j<3; j++) {
for(int r = 0; r<3; r++) {
System.out.printf("%d, %d, %d\n",i, j, r);
}
}
}
}
}
| true |
45e3ab217d50690ea116a79ba6c7c827aefd3f8c | Java | zhlxs/tuanduiruzhu | /src/main/java/com/cn/umessage/service/impl/DepositInfoServiceImpl.java | UTF-8 | 706 | 2.015625 | 2 | [] | no_license | package com.cn.umessage.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.cn.umessage.dao.DepositInfoMapper;
import com.cn.umessage.pojo.DepositInfo;
import com.cn.umessage.service.IDepositInfoService;
@Service("depositInfoService")
public class DepositInfoServiceImpl implements IDepositInfoService{
@Resource
public DepositInfoMapper depositInfoDao;
@Override
public int insert(DepositInfo record) {
// TODO Auto-generated method stub
return depositInfoDao.insert(record);
}
@Override
public DepositInfo selectByPrimaryKey(String accnt) {
// TODO Auto-generated method stub
return depositInfoDao.selectByPrimaryKey(accnt);
}
}
| true |
bf812b4581944a0201f5a07bb58372d8e5728dba | Java | Gowthammiriyala/Corona | /src/main/java/com/coronaconsulatation/service/ServiceMasterImpl.java | UTF-8 | 2,422 | 2.46875 | 2 | [] | no_license | package com.coronaconsulatation.service;
import java.util.List;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.coronaconsulatation.Exception.IdNotFoundException;
import com.coronaconsulatation.Exception.PatientException;
import com.coronaconsulatation.entities.Services;
import com.coronaconsulatation.repository.ServiceRepository;
@Service
public class ServiceMasterImpl implements IServiceMaster{
@Autowired
private ServiceRepository serviceRepository;
@Override
public boolean createService(Services service) {
if(service.getAdditionalServices()==null){
throw new ServiceException("Given Service Object is Null");
}
if(service!=null)
{
serviceRepository.save(service);
return true;
}
return false;
}
@Override
public boolean updateService(int serviceid,Services service) {
Services ser = serviceRepository.findById(serviceid).get();
if(ser==null) {
throw new IdNotFoundException("Given Id is Not found, Please Enter valid Id");
}
else if (ser!=null) {
serviceRepository.save(ser);
return true;
}
return false;
}
@Override
public boolean deleteService(int serviceid) {
Services ser =serviceRepository.findById(serviceid).get();
if(ser==null) {
throw new IdNotFoundException("Given Id is Not found, Please Enter valid Id");
}
else if(ser!=null) {
serviceRepository.deleteById(serviceid);;
return true;
}
return false;
}
@Override
public Services getService(int serviceid) {
Services ser= serviceRepository.findById(serviceid).get();
if(ser==null) {
throw new IdNotFoundException("Given Id is Not found, Please Enter valid Id");
}
else if(ser!=null) {
return ser;
}
return null;
}
@Override
public List<Services> getAllServices() {
List<Services> service= serviceRepository.findAll();
if(service!=null) {
return service;
}
return null;
}
@Override
public boolean updateAdditionalServiceName(int serviceid, String additionalServiceName) {
Services ser = serviceRepository.findById(serviceid).get();
if(ser==null) {
throw new IdNotFoundException("Given Id is Not found, Please Enter valid Id");
}
else if (ser!=null) {
ser.setAdditionalServices(additionalServiceName);
serviceRepository.save(ser);
return true;
}
return false;
}
} | true |
effe2c99369419e10771753f1ef3f9ed8147eacb | Java | Selman81/Java-S-r-c--Kursu-Otomasyonu | /src/parametre/parametre.java | UTF-8 | 454 | 2.96875 | 3 | [] | no_license | package parametre;
public class parametre {
public static void main(String[] args) {
int carpim1 = carp(12, 13);
int carpim2 = carp(7, 9, 123);
double carp = carp(2.50, 2.75);
}
public static int carp(int x, int y) {
return x + y;
}
public static int carp(int x, int y, int z) {
return x + y + z;
}
public static double carp(double x, double y) {
return x + y;
}
} | true |
1d9e2c51ec76f738e20c2a6f1d8c115d7cb3e75b | Java | nikvaytechnology-hub/saipooja-patient | /app/src/main/java/com/nikvay/saipooja_patient/view/adapter/PreScriptionDateAdapter.java | UTF-8 | 3,504 | 1.992188 | 2 | [] | no_license | package com.nikvay.saipooja_patient.view.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nikvay.saipooja_patient.R;
import com.nikvay.saipooja_patient.model.PreScriptionDateModel;
import com.nikvay.saipooja_patient.model.PrescriptionListDateModel;
import com.nikvay.saipooja_patient.utils.StaticContent;
import com.nikvay.saipooja_patient.view.activity.PreScriptionDateDetailsActivity;
import com.nikvay.saipooja_patient.view.activity.PreSriptionActivity;
import java.util.ArrayList;
public class PreScriptionDateAdapter extends RecyclerView.Adapter<PreScriptionDateAdapter.MyViewholder> {
ArrayList<PreScriptionDateModel>preScriptionDateModelArrayList;
ArrayList<PrescriptionListDateModel>preListDateModelArrayList;
Context mContext;
PrescriptionListDateModel prescriptionListDateModel ;
public PreScriptionDateAdapter(PreSriptionActivity preSriptionActivity,
ArrayList<PreScriptionDateModel> preScriptionDateModelArrayList) {
this.preScriptionDateModelArrayList =preScriptionDateModelArrayList;
this.mContext =preSriptionActivity;
}
@NonNull
@Override
public MyViewholder onCreateViewHolder(@NonNull ViewGroup parent, int position) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_prescrption_adapter,parent,false);
return new PreScriptionDateAdapter.MyViewholder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewholder holder, final int position) {
PreScriptionDateModel preScriptionDateModel = preScriptionDateModelArrayList.get(position);
preListDateModelArrayList = preScriptionDateModel.getPrescriptionListDateModelArrayList();
holder.txtDoctorName.setText(preScriptionDateModel.getName());
holder.txtDate.setText(preScriptionDateModel.getDate());
holder.txtViewDetail.setText(preScriptionDateModel.getS_name());
holder.rel_preHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext, PreScriptionDateDetailsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(StaticContent.IntentKey.PRESCRIPTION_DATE, preScriptionDateModelArrayList.get(position));
intent.putExtra(StaticContent.IntentKey.ACTIVITY_TYPE, StaticContent.IntentValue.ACTIVITY_PSCRIPTION_DATE_DETAILS);
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return preScriptionDateModelArrayList.size();
}
public class MyViewholder extends RecyclerView.ViewHolder {
RelativeLayout rel_preHistory;
TextView txtDoctorName,txtDate,txtViewDetail;
public MyViewholder(@NonNull View itemView) {
super(itemView);
rel_preHistory = itemView.findViewById(R.id.rel_preHistory);
txtDoctorName = itemView.findViewById(R.id.txtDoctorName);
txtDate = itemView.findViewById(R.id.txtDate);
txtViewDetail = itemView.findViewById(R.id.txtViewDetail);
}
}
}
| true |
47b7ad02c1b6cbcc384f2b196ff27d658ac0db80 | Java | dkdud8140/Biz_403_2021_03_Java | /Java_020_wordQuiz/src/com/callor/word/service/impl/WordServiceImplV1.java | UTF-8 | 6,579 | 3.234375 | 3 | [] | no_license | package com.callor.word.service.impl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import com.callor.word.domain.WordVO;
import com.callor.word.servie.WordService;
import com.dkdud8140.standard.InputService;
import com.dkdud8140.standard.MenuService;
import com.dkdud8140.standard.impl.InputServiceImplV1;
public class WordServiceImplV1 implements WordService{
protected InputService is;
protected MenuService ms;
protected Scanner scan;
protected Random rnd ;
protected List<WordVO> wordList; //word들의 리스트
protected int nWordCount ; //wordList의 개수를 담을 변수
protected final int 영어 = 0;
protected final int 한글 = 1;
// word.txt 파일을 기본으로 하여 객체생성을 하기 위한 생성자
public WordServiceImplV1() {
this("src/com/callor/word/word.txt");
}
// 객체를 생성할 때 파일 이름을 전달하여
// word 파일을 지정하기
public WordServiceImplV1(String wordFile) {
is = new InputServiceImplV1();
// ms = new MenuServiceImplV1();
scan = new Scanner(System.in);
rnd = new Random();
wordList = new ArrayList<WordVO>();
this.loadWords(wordFile);
//nWordCount는 wordList의 사이즈를 담고 있을 변수인데
//가급적 쉽게 발견할 수 있도록 하기 위하여 여기에 놓는다.
nWordCount = wordList.size();
}
/*
* 게임이 시작되면 1. wordList에서 임의 단어 1개를 추출하고 2. 단어의 영문 스펠링을 나누어 3. 무작위로 섞고 4. 섞인 단어를
* 보여주고 5. 정답 맞추기
*/
public void startGame() {
/*
* getShuffleWord() 메소드가 리턴하는 셔플된 영단어를
* 그대로 inputWord에게 toss
*
* inputWord()를 호출하고 다시 getShuffleWord() 호출하여 수행할 수 있는 코드를
*
* getShuffleWord()를 호출하여 데이터만(섞인 영단어) 되돌려 받고
* 다시 그 데이터를 inputWord()에 전달하여 수행하는 코드로 변경
*
* 첫번째 방법은 inputWord()와 getShuffleWord()가
* 결합도가 높아져 한 메소드의 코드를 변경하면
* 다른 코드도 변경해야ㅕ하는 부분이 많아진다
*
* 두 번째 방법은 데이터만 연결된 형태로 변경한 것으로
* 한 메소드의 코드를 변경하여도
* 다른 메소드코드는 변경하지 않아도 되는 구조가 되었다
*
* 첫번째 코드는 결합도가 높은 코드
* 두번째 코드는 결합도는 낮추고 응집도를 높인 코드가 된다,
*
* 소프트웨어공학에서 좋은 코드라고 하는 예입니당.
*
*/
String viewWord[] = this.getShuffleWord();
this.inputWord(viewWord);
}
//start게임을 getShuffleWord로 변경
//1. wordList에서 단어를 한 개 추출하고
//2. shuffleEnglish()에게 단어를 전달하고
//셔플된 알팝[ㅅ 배열을 리턴받아 그대로 리턴하기
public String[] getShuffleWord() {
//랜덤 클래스를 사용한 코드가 startGame(), shuffleWord()에 나타났다
//랜덤 클래스를 사용한 객체 선언을
//필드(멤버,클래스)영역으로 보내자
//생성자에서 초기화 하자
//Random rnd = new Random();
//wordList의 개수(size)를 담을 변수를
//두개의 메소드에서 사용을 하고 있다.
//이 변수도 필드 영역으로 보내자~
//int nWordCount = wordList.size();
// 0 ~ ( wordList.size() - 1 )범위의 임의 정수 만들기
int nWordIndex = rnd.nextInt(nWordCount);
// 생성된 인덱스 값으로 wordList 중에 단어 1개를 추출
// wordVO에 담기
WordVO wordVO = wordList.get(nWordIndex);
//영문단얼르 매개변수로 전달하고
//알파벳 단위로 분리되고 뒤섞인 단어를 리턴박아
// shuffleEnglish에 저장
String shuffleEnglish[] = this.shuffleWord(wordVO.getEnglish());
//System.out.println(Arrays.toString(shuffleEnglish));
return shuffleEnglish ;
}
protected String inputWord(String[] viewWord) {
System.out.println("=".repeat(50));
System.out.println("뤼팡의 영단어 게임 V1");
System.out.println("-".repeat(50));
System.out.println("다음 단어를 바르게 배열하여 입력!");
//shuffle된 영단어 보여주기
//this.startGame();
System.out.println(Arrays.toString(viewWord));
System.out.println(">> ");
String strInput = scan.nextLine();
System.out.println("=".repeat(50));
return strInput ;
}
/*
* 영문단어를 매개변수로 받아서
* 알파벳 단위로 자르고
* 뒤섞어 배열로 만든 후 리턴
*/
protected String[] shuffleWord(String strEnglish) {
// 영문단어를 스펠링 단위로 잘라서 배열로 생성
String shuffleEnglish[] = strEnglish.split("");
int nCount = shuffleEnglish.length;
// 몇 번 섞을래? 1000번 섞는다요
// shuffle
for (int i = 0; i < 10000; i++) {
// 임의의 인덱스 값 2개를 만들고
int index1 = rnd.nextInt(nCount);
int index2 = rnd.nextInt(nCount);
// index1에 저장된 값과 index2에 저장된 값을 바꾸기
String temp = shuffleEnglish[index1];
shuffleEnglish[index1] = shuffleEnglish[index2];
shuffleEnglish[index2] = temp;
}
return shuffleEnglish ;
}
protected void loadWords(String wordFile) {
// TODO word.txt 파일을 읽어 wordList 만들어두기
FileReader fileReader = null;
BufferedReader buffer = null;
try {
fileReader = new FileReader(wordFile);
buffer = new BufferedReader(fileReader);
while (true) {
String reader = buffer.readLine();
if (reader == null)
break;
String words[] = reader.split(":");
WordVO wordVO = new WordVO();
wordVO.setEnglish(words[영어]);
wordVO.setKorea(words[한글]);
wordList.add(wordVO) ;
}
//여기에서 wordList 사이즈를 계선하여
// nWordCount 변수에 담을 수도 잇지만
//복잡한 코드 속에 잇는 관계로
// 코드가 셋팅되는 것을 보기가 다소 불편하여
// 생성자 부분으로 이동하였다.
// nWordCount = wordList.size();
buffer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true |
9102e1394cac46c7a8c2b7da7a427230263df447 | Java | AndreiMarica/ISP-Project-ELN | /src/main/java/App.java | UTF-8 | 3,597 | 2.8125 | 3 | [] | no_license | /**
* Clasa App.
*/
public class App {
//camp numar de linii
private NumarLinii numarLinii;
//camp complexitate ciclomatica
private ComplexitateCiclomatica complexitateCiclomatica;
//camp culaj intre clase
private CuplajIntreClase cuplajIntreClase;
//camp densitate de comentarii
private DensitateDeComentarii densitateDeComentarii;
//camp dependenta intre pachete
private DependentaIntrePachete dependentaIntrePachete;
//camp nivel de mostenire
private NivelDeMostenire nivelDeMostenire;
//camp plaja de clase
private PlajaDeClase plajaDeClase;
/**
* Constructorul default al clasei App
*/
public App(){
this.numarLinii= new NumarLinii();
this.complexitateCiclomatica= new ComplexitateCiclomatica();
this.cuplajIntreClase = new CuplajIntreClase();
this.densitateDeComentarii = new DensitateDeComentarii();
this.dependentaIntrePachete = new DependentaIntrePachete();
this.nivelDeMostenire = new NivelDeMostenire();
this.plajaDeClase = new PlajaDeClase();
}
/**
* Constructorul cu parametrii aferent clasei App
*
* @param numarLinii
* @param complexitateCiclomatica
* @param cuplajIntreClase
* @param densitateDeComentarii
* @param dependentaIntrePachete
* @param nivelDeMostenire
* @param plajaDeClase
*/
public App(NumarLinii numarLinii, ComplexitateCiclomatica complexitateCiclomatica, CuplajIntreClase cuplajIntreClase, DensitateDeComentarii densitateDeComentarii, DependentaIntrePachete dependentaIntrePachete, NivelDeMostenire nivelDeMostenire, PlajaDeClase plajaDeClase) {
this.numarLinii = numarLinii;
this.complexitateCiclomatica = complexitateCiclomatica;
this.cuplajIntreClase = cuplajIntreClase;
this.densitateDeComentarii = densitateDeComentarii;
this.dependentaIntrePachete = dependentaIntrePachete;
this.nivelDeMostenire = nivelDeMostenire;
this.plajaDeClase = plajaDeClase;
}
public void metrica(String solicitare){
//todo implementare
}
public void suspendare(){
//todo implementare
}
public void resume(){
//todo implementare
}
/**
* returneaza obiectul ce reprezinta numarul de linii de cod
* @return
*/
public NumarLinii getNumarLinii(){
return this.numarLinii;
}
/**
* returneaza obiectul ce reprezinta complexitatea ciclomatica
* @return
*/
public ComplexitateCiclomatica getComplexitateCiclomatica(){
return this.complexitateCiclomatica;
}
/**
* returneaza obiectul ce reprezinta cuplajul intre clase
* @return
*/
public CuplajIntreClase getCuplajIntreClase() {
return cuplajIntreClase;
}
/**
* returneaza obiectul ce reprezinta densitatea de comentarii
* @return
*/
public DensitateDeComentarii getDensitateDeComentarii() {
return densitateDeComentarii;
}
/**
* returneaza obiectul ce reprezinta dependenta intre pachete
* @return
*/
public DependentaIntrePachete getDependentaIntrePachete() {
return dependentaIntrePachete;
}
/**
* returneaza obiectul ce reprezinta nivelul de mostenire
* @return
*/
public NivelDeMostenire getNivelDeMostenire() {
return nivelDeMostenire;
}
/**
* returneaza obiectul ce reprezinta plaja de clase
* @return
*/
public PlajaDeClase getPlajaDeClase() {
return plajaDeClase;
}
}
| true |
352d7cb6d1a071eaaa04ca9ea6be46a31a613221 | Java | ramkondadasu/HrOnlineReports | /src/main/java/texas/dot/hronline/services/JobcodeProfileDataMvwServiceImpl.java | UTF-8 | 1,336 | 2.25 | 2 | [] | no_license | package texas.dot.hronline.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import texas.dot.hronline.domain.JobcodeProfileDataMvw;
import texas.dot.hronline.repositories.JobcodeProfileDataMvwRepository;
@Service
public class JobcodeProfileDataMvwServiceImpl implements JobcodeProfileDataMvwService {
private JobcodeProfileDataMvwRepository jobcodeProfileDataMvwRepository;
@Autowired
public JobcodeProfileDataMvwServiceImpl(JobcodeProfileDataMvwRepository jobcodeProfileDataMvwRepository) {
this.jobcodeProfileDataMvwRepository = jobcodeProfileDataMvwRepository;
}
@Override
public List<JobcodeProfileDataMvw> findByJobcode(@Param("singlejobcode29") String singlejobcode29){
List<JobcodeProfileDataMvw> jobcodeProfileDataMvws = new ArrayList<>();
jobcodeProfileDataMvwRepository.findByJobcode(singlejobcode29).forEach(jobcodeProfileDataMvws::add); // fun with Java 8
jobcodeProfileDataMvws.forEach(System.out::println);
for(int i=0;i<jobcodeProfileDataMvws.size();i++){
System.out.println(jobcodeProfileDataMvws.get(i).getJobTitle());
}
return jobcodeProfileDataMvws;
}
}
| true |
c418e160d6c232eb47b9e401a4599ac9f7176acb | Java | simpleypc/netty | /src/main/java/com/netty/aio/TimeServerHandlerExecutePool.java | UTF-8 | 1,039 | 3.140625 | 3 | [] | no_license | package com.netty.aio;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 伪异步I/O
* Created by ypc on 2017/3/15.
* 首先创建一个时间服务器处理类的线程池,当接收到新的客户端连接时,
* 将请求 Socket 封装成一个 Task,然后调用线程池的 execute 方法执行,
* 从而避免了每个请求都创建一个新的线程。
*/
public class TimeServerHandlerExecutePool {
private ExecutorService executor;
public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) {
executor = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(),
maxPoolSize,
120L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(queueSize));
}
public void execute(Runnable task){
executor.execute(task);
}
}
| true |
26e819043f9199b895b2476bad01196f7e23c365 | Java | mangesh2806/e-society | /src/com/test/action/Test.java | UTF-8 | 2,180 | 2.546875 | 3 | [] | no_license | package com.test.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class Test extends ActionSupport {
private List<String> countryList;
private List<String> stateList;
private List<String> cityList;
private String state;
private String country;
private String city;
private String result;
public String myCustomMethod() {
countryList = new ArrayList<String>();
stateList = new ArrayList<String>();
cityList = new ArrayList<String>();
countryList.add("India");
countryList.add("US");
countryList.add("Japan");
if (country != null) {
if (country.equals("India")) {
stateList.add("Gujarat");
stateList.add("Maharashtra");
stateList.add("Delhi");
} else if (country.equals("US")) {
stateList.add("Washington");
stateList.add("NJ");
stateList.add("NY");
} else if (country.equals("Japan")) {
stateList.add("Tokyo");
stateList.add("Kagoshima");
}
}
if (state != null) {
if (state.equals("Gujarat")) {
cityList.add("Ahmedabad");
cityList.add("Surat");
} else if (state.equals("Maharashtra")) {
cityList.add("Mumbai");
cityList.add("Pune");
}
}
result = "success";
return result;
}
public List<String> getCountryList() {
return countryList;
}
public void setCountryList(List<String> countryList) {
this.countryList = countryList;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public List<String> getStateList() {
return stateList;
}
public void setStateList(List<String> stateList) {
this.stateList = stateList;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public List<String> getCityList() {
return cityList;
}
public void setCityList(List<String> cityList) {
this.cityList = cityList;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
| true |
d9261018d4f32ee8611ca22e52f61a865a030a3b | Java | KunamsettiVaishnavi/Capgemini_Assignments | /Spring-AnnotationDemo/src/main/java/com/abc/beans/Address.java | UTF-8 | 903 | 2.59375 | 3 | [] | no_license | package com.abc.beans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Address {
@Value("New Delhi")
private String cityName;
@Value("Delhi")
private String stateName;
public Address() {
super();
// TODO Auto-generated constructor stub
}
public Address(String cityName, String stateName) {
super();
this.cityName = cityName;
this.stateName = stateName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
@Override
public String toString() {
return "Address [cityName=" + cityName + ", stateName=" + stateName + "]";
}
}
| true |
f424e08156879381886cea830bfde5d4a05acda8 | Java | Pcamerer/School | /MIS307HW/HW1/src/TicketSeller.java | UTF-8 | 894 | 3.703125 | 4 | [] | no_license | import java.util.Scanner;
/**
* Code for P6.12
* @author Prseton Camerer
*/
public class TicketSeller
{
public static void main(String[] args)
{
final int MAX_TICKETS = 100;
Scanner input = new Scanner(System.in);
int availableTickets = 100;
int numberBuyers = 0;
do {
System.out.print("Number of tickets to buy: ");
int ticketsToBuy = input.nextInt();
if (ticketsToBuy < 5 && ticketsToBuy > 0) {
System.out.println("You bought " + ticketsToBuy + " tickets");
availableTickets -= ticketsToBuy;
numberBuyers += 1;
}
else {
System.out.println("You cannot buy more than 4 tickets.");
}
} while (availableTickets > 0);
input.close();
System.out.println("We are sold out!");
System.out.println("Total buyers: " + numberBuyers);
}
} | true |
937c1f1ccfb92bbd2288d7725f8fdf053364fc81 | Java | ryanmueller28/DnDDIce-Ryan | /app/src/main/java/com/example/dnddice/MainActivity.java | UTF-8 | 1,309 | 3.3125 | 3 | [] | no_license | package com.example.dnddice;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import java.util.Random;
class Dice{
/*
* use random for dice
*
*/
public int numFaces;
Random random;
//class constructor
public Dice(int n)
{
this.random = new Random();
numFaces = n;
}
public int roll()
{
//Pass in numFaces, to generate a random result
return random.nextInt(numFaces);
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonPressed(View view) {
//Grab Text from button; grab the int from the string
//make a dice using the int as parameter
//set i = roll
//set view to i
TextView tv = (TextView) findViewById(R.id.Roll);
Dice dice;
Button b = (Button)view;
String buttonText = b.getText().toString();
int i = Integer.parseInt(buttonText.substring(1));
dice = new Dice(i);
int j = dice.roll() + 1;
tv.setText("You rolled a " + j);
}
}
| true |
047848081621a3f41787bd65bc8a56fd7b197809 | Java | 44010039/java-examples | /java-tools/src/main/java/net/java/tools/lang/ProcessResult.java | UTF-8 | 999 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | package net.java.tools.lang;
import java.util.Iterator;
import java.util.List;
import lombok.Getter;
/**
* 命令结果
*/
@Getter
public class ProcessResult {
/**
* 返回代码
*/
private final int exitCode;
/**
* 消息
*/
private final List<String> output;
public ProcessResult(int exitCode, List<String> output) {
this.exitCode = exitCode;
this.output = output;
}
/**
* 消息文本
* @return
*/
public String getOutputText() {
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = output.iterator();
while (iterator.hasNext()) {
sb.append(iterator.next());
if (iterator.hasNext()) {
sb.append(System.lineSeparator());
}
}
return sb.toString();
}
public boolean isError() {
return this.exitCode != 0;
}
public boolean isOk() {
return !this.isError();
}
}
| true |
f213cf326e01968fcff7b0f479f308e47e19622f | Java | Kuojian21/kj-repo | /kj-repo-demo/src/main/java/com/kj/repo/demo/aop/AopTest.java | UTF-8 | 270 | 1.851563 | 2 | [] | no_license | package com.kj.repo.demo.aop;
import com.kj.repo.infra.utils.SpringBeanFactoryUtil;
public class AopTest {
public static void main(String[] args) {
AopTarget aopTarget = SpringBeanFactoryUtil.getBean(AopTarget.class);
aopTarget.target();
}
}
| true |
f7da526ec72b0f53c3b88aa1d39fe9f9b40b1665 | Java | amit0510/SocketApp | /app/src/main/java/com/webbions/socketsend/MainActivity.java | UTF-8 | 5,719 | 2.546875 | 3 | [] | no_license | package com.webbions.socketsend;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = MainActivity.class.getSimpleName();
private ServerSocket serverSocket;
private Socket tempClientSocket;
Thread serverThread = null;
public static final int SERVER_PORT = 9003;
TextView messageTv;
Button next;
EditText txtMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageTv = (TextView) findViewById(R.id.messageTv);
next=findViewById(R.id.next);
txtMsg=findViewById(R.id.txtMsg);
// WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
// String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
// System.out.println("----------------------- IP : " + ip);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this,Client.class);
startActivity(i);
}
});
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
messageTv.append(message + "\n");
}
});
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.start_server) {
System.out.println("------------------ Starting Server...");
messageTv.setText("");
updateMessage("Starting Server...");
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
return;
}
if (view.getId() == R.id.send_data) {
sendMessage("Server : " + txtMsg.getText());
updateMessage(getTime() + " | Server : " + txtMsg.getText());
}
}
private void sendMessage(String message) {
try {
if (null != tempClientSocket) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(tempClientSocket.getOutputStream())),
true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket;
try {
serverSocket = new ServerSocket(SERVER_PORT);
} catch (IOException e) {
e.printStackTrace();
}
if (null != serverSocket) {
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
tempClientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
updateMessage("Server Started...");
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
System.out.println("------------- Message Received from Client : " + read);
if (null == read || "Disconnect".contentEquals(read)) {
Thread.interrupted();
read = "Client Disconnected";
updateMessage(getTime() + " | Client : " + read);
break;
}
updateMessage(getTime() + " | Client : " + read);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != serverThread) {
sendMessage("Disconnect");
serverThread.interrupt();
serverThread = null;
}
}
} | true |
a97f3e183a1709b8790d8151d3fdb5e4b14b1cbb | Java | bellmit/b2b | /Common/src/main/java/com/b2b/enums/ItemSizeEnum.java | UTF-8 | 1,010 | 2.71875 | 3 | [] | no_license | package com.b2b.enums;
import java.util.Map;
import com.google.common.collect.Maps;
public enum ItemSizeEnum {
SIZE("SIZE", "规格"),
BUY_SIZE("BUY_SIZE", "批发规格"),
SALE_SIZE("SALE_SIZE", "零售规格");
private String name;
private String value;
private ItemSizeEnum(String name, String value) {
this.name = name;
this.value = value;
}
private static Map<String, ItemSizeEnum> sizeNameMap = Maps.newHashMap();
static {
for (ItemSizeEnum itemSizeEnum : ItemSizeEnum.values()) {
sizeNameMap.put(itemSizeEnum.name, itemSizeEnum);
}
}
public static ItemSizeEnum parseName(String name) {
return (null != name) ? sizeNameMap.get(name.toLowerCase()) : null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| true |
186a090febd14f17fdfc44d9d9f33b2a7af92d40 | Java | bluepoet/videoshop | /src/test/java/kr/bluepoet/junit5/videoshop/service/RentServiceTest.java | UTF-8 | 1,575 | 2.25 | 2 | [] | no_license | package kr.bluepoet.junit5.videoshop.service;
import kr.bluepoet.junit5.videoshop.util.TestDatas;
import kr.bluepoet.videoshop.application.RentService;
import kr.bluepoet.videoshop.domain.Rent;
import kr.bluepoet.videoshop.domain.RentRepository;
import name.falgout.jeffrey.testing.junit5.MockitoExtension;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Spy;
import static kr.bluepoet.videoshop.util.DateUtils.parse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.doReturn;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
public class RentServiceTest {
@Spy
RentService rentService = new RentService();
@DisplayName("반납일에 따라 연체료를 계산")
@Test
void calculatePriceByDelayedDays(@Mock RentRepository rentRepository) {
// Given
rentService.setRentRepository(rentRepository);
given(rentRepository.findById(1L)).willReturn(createRent());
doReturn(parse("2017-10-18 20:30:33")).when(rentService).currentTime();
// When
int delayedPrice = rentService.confirmReturnMoney(1L);
// Then
assertEquals(600, delayedPrice);
}
private Rent createRent() {
Rent rent = new Rent();
rent.addRenter(TestDatas.NORMAL_RENTER);
rent.addVideo(TestDatas.createVideos());
rent.setRentDate("2017-10-07 19:30:33");
return rent;
}
}
| true |
351d33a038eb0a88c8155d33eb8461f4ba088a6a | Java | milkyway0308/ServerEdit | /src/skywolf46/ServerEdit/Modules/CraftScript/Data/Classes/Condition/ISTypeComparator.java | UTF-8 | 1,944 | 2.671875 | 3 | [] | no_license | package skywolf46.ServerEdit.Modules.CraftScript.Data.Classes.Condition;
import skywolf46.ServerEdit.Modules.CraftScript.Data.Classes.Condition.Extension.AbstractParsableCondition;
import skywolf46.ServerEdit.Modules.CraftScript.Data.Classes.Native.BooleanClass;
import skywolf46.ServerEdit.Modules.CraftScript.Data.Classes.Native.StringClass;
import skywolf46.ServerEdit.Modules.CraftScript.Data.CompileStatus;
import skywolf46.ServerEdit.Modules.CraftScript.Data.ExecuteState;
import skywolf46.ServerEdit.Modules.CraftScript.Extension.CraftScriptClass;
import skywolf46.ServerEdit.Modules.CraftScript.Util.TripleFunction;
public class ISTypeComparator extends AbstractParsableCondition {
@Override
public String getClassName() {
return "isTypeComparator";
}
@Override
public void applyData(CompileStatus cl, int currentIndex) {
}
@Override
public CraftScriptClass process(ExecuteState state, CompileStatus st, int currentIndex) {
System.out.println(st.get(currentIndex+1).toString());
String type = st.get(currentIndex+1).toString();
return new BooleanClass(st.get(currentIndex-1).getClassName().equals(type) || st.get(currentIndex-1).getFullClassName().equals(type));
}
@Override
public TripleFunction<String, Integer, CompileStatus, CraftScriptClass> getClassParser() {
return (s, i, c) -> {
if(!s.equalsIgnoreCase("is"))
return null;
if (i == 0)
throw new IllegalStateException("[CraftScript|Compile Error] is Type conversion condition cannot locate at 0");
int next = c.length() - i - 1;
if (next <= 0 || next > 1)
throw new IllegalStateException("[CraftScript|Compile Error] is Type conversion condition need one parameter");
c.set(i + 1, new StringClass(c.getString(i + 1)));
return new ISTypeComparator();
};
}
}
| true |
3ecabd57ce50dfeb6ec61be761f2eaff680006e7 | Java | WillDSmith/Vending | /app/src/main/java/com/guhring/vending/models/MachineModelDNU.java | UTF-8 | 1,968 | 2.25 | 2 | [] | no_license | package com.guhring.vending.models;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
/**
* Created by SmithW on 7/21/2016.
*/
public class MachineModelDNU {
private int Id;
private String CustomerName;
private String EndUser;
private String ModelNumber;
private String City;
/* private String ThumbnailUrl;*/
public MachineModelDNU() {
}
public MachineModelDNU(String CustomerName, String EndUser, String ModelNumber, String City ) {
this.CustomerName = CustomerName;
this.EndUser = EndUser;
this.ModelNumber = ModelNumber;
this.City = City;
/*this.ThumbnailUrl = ThumbnailUrl;*/
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getCustomerName() {
return CustomerName;
}
public void setCustomerName(String customerName) {
CustomerName = customerName;
}
public String getEndUser() {
return EndUser;
}
public void setEndUser(String endUser) {
EndUser = endUser;
}
/*public String getThumbnailUrl() {
return ThumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.ThumbnailUrl = thumbnailUrl;
}*/
public String getModelNumber() {
return ModelNumber;
}
public void setModelNumber(String modelNumber) {
ModelNumber = modelNumber;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
/* public static final String MACHINE_ID = "Id";
public static final String MACHINE_CUSTOMERNAME = "CustomerName";
public static final String MACHINE_ENDUSER = "EndUser";
public static final String MACHINE_MODELNUMBER = "ModelNumber";
public static final String MACHINE_CITY = "City";*/
}
| true |
eda30753b0e2912753fe0bb48665a93ba81cc352 | Java | rMozes/detector | /openCVTutorial1CameraPreview/src/main/java/org/opencv/samples/tutorial1/ContourDetector.java | UTF-8 | 10,246 | 2.484375 | 2 | [] | no_license | package org.opencv.samples.tutorial1;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.util.Log;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.utils.Converters;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by richimozes on 6/6/16.
*/
public class ContourDetector {
public ContourDetector() {
}
public Bitmap getPerspective(Bitmap _image, List<Point> _points) {
if (_points == null || _points.size() != 4)
return _image;
Map<Integer, Point> pointMap = getOrderedPoints(_points);
Point topLeft = pointMap.get(0);
Point topRight = pointMap.get(1);
Point bottomLeft = pointMap.get(2);
Point bottomRight = pointMap.get(3);
int resultWidth = (int)(topRight.x - topLeft.x);
int bottomWidth = (int)(bottomRight.x - bottomLeft.x);
if(bottomWidth > resultWidth)
resultWidth = bottomWidth;
int resultHeight = (int)(bottomLeft.y - topLeft.y);
int bottomHeight = (int)(bottomRight.y - topRight.y);
if(bottomHeight > resultHeight)
resultHeight = bottomHeight;
Mat inputMat = new Mat(_image.getHeight(), _image.getHeight(), CvType.CV_8UC1);
Utils.bitmapToMat(_image, inputMat);
Mat outputMat = new Mat(resultWidth, resultHeight, CvType.CV_8UC1);
List<Point> source = new ArrayList<>();
source.add(topLeft);
source.add(topRight);
source.add(bottomLeft);
source.add(bottomRight);
Mat startM = Converters.vector_Point2f_to_Mat(source);
Point ocvPOut1 = new Point(0, 0);
Point ocvPOut2 = new Point(resultWidth, 0);
Point ocvPOut3 = new Point(0, resultHeight);
Point ocvPOut4 = new Point(resultWidth, resultHeight);
List<Point> dest = new ArrayList<>();
dest.add(ocvPOut1);
dest.add(ocvPOut2);
dest.add(ocvPOut3);
dest.add(ocvPOut4);
Mat endM = Converters.vector_Point2f_to_Mat(dest);
Mat perspectiveTransform = Imgproc.getPerspectiveTransform(startM, endM);
Imgproc.warpPerspective(inputMat, outputMat, perspectiveTransform, new Size(resultWidth, resultHeight));
Bitmap output = Bitmap.createBitmap(resultWidth, resultHeight, Bitmap.Config.ARGB_8888);
Utils.matToBitmap(outputMat, output);
int i = 7;
return output;
}
private Map<Integer, Point> getOrderedPoints(List<Point> points) {
Point centerPoint = new Point();
int size = points.size();
for (Point pointF : points) {
centerPoint.x += pointF.x / size;
centerPoint.y += pointF.y / size;
}
Map<Integer, Point> orderedPoints = new HashMap<>();
for (Point pointF : points) {
int index = -1;
if (pointF.x < centerPoint.x && pointF.y < centerPoint.y) {
index = 0;
} else if (pointF.x > centerPoint.x && pointF.y < centerPoint.y) {
index = 1;
} else if (pointF.x < centerPoint.x && pointF.y > centerPoint.y) {
index = 2;
} else if (pointF.x > centerPoint.x && pointF.y > centerPoint.y) {
index = 3;
}
orderedPoints.put(index, pointF);
}
return orderedPoints;
}
public List<Point> findLargestRectangle(Bitmap _bitmap) {
List<Point> points = new ArrayList<>();
Mat imgSource = new Mat();
Utils.bitmapToMat(_bitmap, imgSource);
if (imgSource.empty())
return points;
List<MatOfPoint> contours = new ArrayList<>();
findContours(imgSource, contours);
MatOfPoint2f maxCurve = findLargestContour(contours);
if (maxCurve == null || maxCurve.empty())
return points;
points = convertMatOfPointToPoints(maxCurve);
Log.d("LargestRectangle", "findLargestRectangle: " + points);
return points;
}
public List<Point> findLargestRectangleWithLocalTransform(byte[] _data,
Point _previewSize,
Point _screenSize,
int _format) {
List<Point> points = new ArrayList<>();
Mat imgSource = convertBytesToMat(_data, _previewSize, _format);
if (imgSource == null)
return points;
List<MatOfPoint> contours = new ArrayList<>();
findContours(imgSource, contours);
MatOfPoint2f maxCurve = findLargestContour(contours);
if (maxCurve == null)
return points;
points = convertMatOfPointToPointsWithTransform(maxCurve, new Point(imgSource.cols(),
imgSource.rows()), _screenSize);
return points;
}
public Mat convertBytesToMat(byte[] _data, Point _previewSize, int _previewFormat) {
if (_previewFormat == ImageFormat.NV21 || _previewFormat == ImageFormat.YUY2) {
int width = (int) _previewSize.x;
int height = (int) _previewSize.y;
YuvImage yuv = new YuvImage(_data, _previewFormat, width, height, null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuv.compressToJpeg(new Rect(0, 0, width, height), 100, out);
_data = out.toByteArray();
}
BitmapFactory.Options options = new BitmapFactory.Options();
double size = (_previewSize.x / 640);
if (size < 1)
size = 1;
options.inSampleSize = (int) size;
final Bitmap bitmap = BitmapFactory.decodeByteArray(_data, 0, _data.length, options);
if (bitmap == null)
return null;
Mat imgSource = new Mat();
Utils.bitmapToMat(bitmap, imgSource);
bitmap.recycle();
return imgSource;
}
private void findContours(Mat _imgSource, List<MatOfPoint> _contours) {
Imgproc.cvtColor(_imgSource, _imgSource, Imgproc.COLOR_BGR2GRAY);
Imgproc.Canny(_imgSource, _imgSource, 160, 200, 3, true);
Imgproc.GaussianBlur(_imgSource, _imgSource, new Size(5, 5), 4);
Imgproc.findContours(_imgSource, _contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_NONE);
}
private MatOfPoint2f findLargestContour(List<MatOfPoint> _contours) {
if (_contours.isEmpty())
return null;
double maxArea = -1;
MatOfPoint temp_contour;
MatOfPoint2f approxCurve = new MatOfPoint2f();
MatOfPoint2f maxCurve = new MatOfPoint2f();
for (int idx = 0; idx < _contours.size(); idx++) {
temp_contour = _contours.get(idx);
double contourArea = Imgproc.contourArea(temp_contour);
if (contourArea > maxArea && contourArea > 50000 && !Imgproc.isContourConvex(temp_contour)) {
MatOfPoint2f new_mat = new MatOfPoint2f(temp_contour.toArray());
int contourSize = (int) temp_contour.total();
Imgproc.approxPolyDP(new_mat, approxCurve, contourSize * 0.05, true);
if (approxCurve.total() == 4) {
maxArea = contourArea;
maxCurve = approxCurve;
}
}
}
return maxCurve;
}
private List<Point> convertMatOfPointToPoints(MatOfPoint2f _curve) {
List<Point> points = new ArrayList<>();
if (_curve.empty())
return points;
double[] temDouble = _curve.get(0, 0);
if (temDouble == null)
return points;
Point point1 = new Point(temDouble[0], temDouble[1]);
temDouble = _curve.get(1, 0);
if (temDouble == null)
return points;
Point point2 = new Point(temDouble[0], temDouble[1]);
temDouble = _curve.get(2, 0);
if (temDouble == null)
return points;
Point point3 = new Point(temDouble[0], temDouble[1]);
temDouble = _curve.get(3, 0);
if (temDouble == null)
return points;
Point point4 = new Point(temDouble[0], temDouble[1]);
points.add(point1);
points.add(point2);
points.add(point3);
points.add(point4);
return points;
}
private List<Point> convertMatOfPointToPointsWithTransform(MatOfPoint2f _curve, Point _previewSize, Point _screenSize) {
List<Point> points = new ArrayList<>();
if (_curve.empty())
return points;
double[] temDouble = _curve.get(0, 0);
if (temDouble == null)
return points;
Point point1 = transformCoordinate(new Point(temDouble[0], temDouble[1]), _previewSize, _screenSize);
temDouble = _curve.get(1, 0);
if (temDouble == null)
return points;
Point point2 = transformCoordinate(new Point(temDouble[0], temDouble[1]), _previewSize, _screenSize);
temDouble = _curve.get(2, 0);
if (temDouble == null)
return points;
Point point3 = transformCoordinate(new Point(temDouble[0], temDouble[1]), _previewSize, _screenSize);
temDouble = _curve.get(3, 0);
if (temDouble == null)
return points;
Point point4 = transformCoordinate(new Point(temDouble[0], temDouble[1]), _previewSize, _screenSize);
points.add(point1);
points.add(point2);
points.add(point3);
points.add(point4);
return points;
}
public Point transformCoordinate(Point _point, Point _previewSize, Point _screenSize) {
Point point = new Point();
point.x = (_point.x * _screenSize.x) / _previewSize.x;
point.y = (_point.y * _screenSize.y) / _previewSize.y;
return point;
}
}
| true |
ff1163769e43803abe7f90d2a407f422e7484a65 | Java | Louisxavierj/ProjectBigW | /src/test/java/BigW/Automation.java | UTF-8 | 3,263 | 2.34375 | 2 | [] | no_license | package BigW;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import DataDriven.ExcelIntegration;
public class Automation extends ExcelIntegration{
public static void main(String[] args) throws IOException, AWTException {
//Browser Launch
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\admin\\BigW\\ProjectBigW\\ProjectBigW\\Driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.bigw.com.au/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
//getTitle
String title = driver.getTitle();
System.out.println(title);
//currentUrl
String currentUrl = driver.getCurrentUrl();
System.out.println(currentUrl);
//JavscriptExecutor
JavascriptExecutor js = (JavascriptExecutor)driver;
WebElement register = driver.findElement(By.xpath("//span[contains(text(),'Login/Register')]"));
js.executeScript("arguments[0].click()", register);
//getText
WebElement text = driver.findElement(By.xpath("//p[contains(text(),'allows you to:')]"));
String text2 = text.getText();
System.out.println(text2);
WebElement userEmail = driver.findElement(By.id("j_username"));
userEmail.sendKeys(getData(2, 0));
//getAttribute
String user = userEmail.getAttribute("value");
System.out.println(user);
WebElement PassWord = driver.findElement(By.id("j_password"));
PassWord.sendKeys(getData(2, 1));
String pass = PassWord.getAttribute("value");
System.out.println(pass);
driver.findElement(By.xpath("(//button[@type='submit'])[3]")).click();
//Mouse Over
Actions ac = new Actions(driver);
WebElement book = driver.findElement(By.xpath("(//a[contains(text(),'Books')])[2]"));
ac.moveToElement(book).perform();
driver.findElement(By.xpath("(//a[text()='Childrens Books'])[1]")).click();
WebElement sman = driver.findElement(By.xpath("(//a[@href='http://www.bigw.com.au/product/superman-paint-with-water/p/78451/'])[1]"));
js.executeScript("arguments[0].click()", sman);
driver.findElement(By.id("addToCartButtonNew")).click();
WebElement pinCode = driver.findElement(By.id("productPageLocationInput"));
pinCode.sendKeys(getData(4, 0));
//Robot Class
Robot r = new Robot();
r.keyPress(KeyEvent.VK_DOWN);
r.keyRelease(KeyEvent.VK_DOWN);
r.keyPress(KeyEvent.VK_ENTER);
r.keyRelease(KeyEvent.VK_ENTER);
driver.findElement(By.xpath("(//a[@href='/cart'])[1]")).click();
//ScrollDown
js.executeScript("window.scrollTo(0,document.body.scrollHight)");
//TakesScreenshot
TakesScreenshot tk = (TakesScreenshot)driver;
File temp = tk.getScreenshotAs(OutputType.FILE);
File desc = new File("C:\\Users\\admin\\BigW\\ProjectBigW\\ProjectBigW\\Screenshot\\BigW.png");
FileUtils.copyFile(temp, desc);
}
}
| true |
6e9aee84f9093f64eaba6dc84bc85d28c4040994 | Java | ZdrzalikPrzemyslaw/2048_Game | /2048_APP/module/src/main/java/tech/szymanskazdrzalik/module/dao/Dao.java | UTF-8 | 326 | 1.945313 | 2 | [
"Apache-2.0"
] | permissive | package tech.szymanskazdrzalik.module.dao;
import java.io.IOException;
public interface Dao<T> extends AutoCloseable {
SaveGame read() throws IOException, ClassNotFoundException, SaveGame.SaveGameException;
void write(T t) throws IOException;
/**
* {@inheritDoc}
*/
@Override
void close();
} | true |
cae71820f48f36c5bb72a49bea8b27a4235a1b18 | Java | esteban-mallen/minesweeper-service | /src/main/java/com/stvmallen/minesweeper/repository/CellRepository.java | UTF-8 | 288 | 1.703125 | 2 | [
"MIT"
] | permissive | package com.stvmallen.minesweeper.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.stvmallen.minesweeper.entity.Cell;
@Repository
public interface CellRepository extends CrudRepository<Cell, Long> {
}
| true |
48971a113db51195f493f0e8fd28a250b828d597 | Java | vadimZasovin/android-app-carcase | /carcase-controller/src/main/java/com/imogene/android/carcase/controller/BaseFragment.java | UTF-8 | 6,497 | 2.0625 | 2 | [] | no_license | package com.imogene.android.carcase.controller;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.imogene.android.carcase.commons.util.AppUtils;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
/**
* Created by Admin on 11.04.2017.
*/
public abstract class BaseFragment extends Fragment implements OnBackPressListener {
protected BaseActivity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
activity = (BaseActivity) context;
}
@Override
public void onDetach() {
super.onDetach();
activity = null;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
@LayoutRes int layoutRes = getLayoutRes();
return inflater.inflate(layoutRes, container, false);
}
@LayoutRes
protected abstract int getLayoutRes();
@Override
public boolean onInterceptBackPressed() {
return false;
}
public final void openSoftKeyboard() {
AppUtils.Commons.openSoftKeyboard(this);
}
public final void closeSoftKeyboard() {
AppUtils.Commons.closeSoftKeyboard(this);
}
public final boolean checkNetworkAvailability() {
return activity.checkNetworkAvailability();
}
public final boolean checkApiLevel(int requiredApiLevel) {
return AppUtils.Commons.checkApiLevel(requiredApiLevel);
}
public final int convertDpsInPixels(int dps) {
return activity.convertDpsInPixels(dps);
}
public final float convertDpsInPixels(float dps) {
return activity.convertDpsInPixels(dps);
}
public final void showToast(@StringRes int messageRes, boolean lengthLong) {
activity.showToast(messageRes, lengthLong);
}
public final void showToast(@StringRes int messageRes, int length) {
activity.showToast(messageRes, length);
}
public final void showToast(String message, boolean lengthLong) {
activity.showToast(message, lengthLong);
}
public final void showToast(String message, int length) {
activity.showToast(message, length);
}
public final boolean hasNavigationDrawer(){
try {
NavigationDrawerActivity drawerActivity = (NavigationDrawerActivity) activity;
return drawerActivity.hasNavigationDrawer();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an NavigationDrawerActivity");
}
}
public final boolean isNavigationDrawerOpened(){
try {
NavigationDrawerActivity drawerActivity = (NavigationDrawerActivity) activity;
return drawerActivity.isNavigationDrawerOpened();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an NavigationDrawerActivity");
}
}
public final void openNavigationDrawer(){
try {
NavigationDrawerActivity drawerActivity = (NavigationDrawerActivity) activity;
drawerActivity.openNavigationDrawer();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an NavigationDrawerActivity");
}
}
public final void closeNavigationDrawer(){
try {
NavigationDrawerActivity drawerActivity = (NavigationDrawerActivity) activity;
drawerActivity.closeNavigationDrawer();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an NavigationDrawerActivity");
}
}
public final BottomNavigationView getBottomNavigationView(){
try {
BottomNavigationActivity navigationActivity = (BottomNavigationActivity) activity;
return navigationActivity.getNavigationView();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an BottomNavigationActivity");
}
}
public final boolean hasBottomNavigationView(){
try {
BottomNavigationActivity navigationActivity = (BottomNavigationActivity) activity;
return navigationActivity.hasNavigationView();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an BottomNavigationActivity");
}
}
public int getNavigationDestinationId(){
try {
NavigableActivity navigableActivity = (NavigableActivity) activity;
return navigableActivity.getNavigationDestinationId();
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an NavigableActivity");
}
}
public final void setBottomNavigationDestination(int itemId){
try {
BottomNavigationActivity navigationActivity = (BottomNavigationActivity) activity;
navigationActivity.setNavigationDestination(itemId);
}catch (ClassCastException e){
throw new ClassCastException(
"Activity that hosts this fragment is not an BottomNavigationActivity");
}
}
public void replaceContentFragment(Fragment fragment){
activity.replaceContentFragment(fragment);
}
public final int requestPermission(String permission, boolean withExplanation, int requestCode){
return AppUtils.Permissions.requestPermission(this, requestCode, withExplanation, permission);
}
public final boolean checkPermission(String permission){
return activity.checkPermission(permission);
}
public final boolean isLand(){
return activity.isLand();
}
public final boolean isTablet(){
return activity.isTablet();
}
public final boolean isTabletLand(){
return isLand() && isTablet();
}
} | true |
b66739a9943b1e1ff0768d9917efa57c0c6c7b38 | Java | gartanium/werewolf | /app/src/main/java/com/qd8s/werewolf2/GameHandler/NightFinishedListener.java | UTF-8 | 164 | 1.796875 | 2 | [] | no_license | package com.qd8s.werewolf2.GameHandler;
/**
* Created by Matthew on 7/12/2017.
*/
public interface NightFinishedListener {
public void onNightFinished();
}
| true |
33e23082bede2c65782cbde0895d31037185da98 | Java | rocker6zhang/store | /src/com/estore/test/BeansTest.java | UTF-8 | 717 | 2.296875 | 2 | [] | no_license | package com.estore.test;
import java.math.BigInteger;
import java.util.Date;
import java.util.Vector;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import org.junit.Test;
import com.estore.utils.MD5Utils;
import com.estore.utils.MailUtils;
import com.estore.domain.Product;
import com.estore.domain.User;
import com.estore.utils.*;
public class BeansTest {
User u = new User();
Product p = new Product();
@Test
public void f2() {
u.setUsername("dd");
u.setEmail("dd");
u.setPassword("456");
System.out.println(u.check());
}
@Test
public void f3() {
p.setName("DD");
p.setPrice(1.1);
p.setImgurl("ss.png");
System.out.println(p.check());
}
}
| true |
06c82ba04fd1ca3ce277f94e717f374c68be8efe | Java | BackupTheBerlios/robonobo-svn | /robonobo/tags/0.4.0/wang-server/src/java/com/robonobo/wang/server/DoubleSpendDAO.java | UTF-8 | 244 | 1.898438 | 2 | [] | no_license | package com.robonobo.wang.server;
import java.math.BigInteger;
public interface DoubleSpendDAO {
public abstract boolean isDoubleSpend(String coinId) throws DAOException;
public abstract void add(String coinId) throws DAOException;
} | true |
6788f1b6b582992dfb5dfedd8d406f3c3249ee5a | Java | vgrec/xing-android-sdk | /sdk/src/test/java/com/xing/android/sdk/network/DefaultRequestConfigTest.java | UTF-8 | 3,631 | 2.015625 | 2 | [
"MIT"
] | permissive | /*
* Copyright (c) 2015 XING AG (http://xing.com/)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.xing.android.sdk.network;
import android.os.Build;
import android.util.Pair;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
/**
* @author david.gonzalez
*/
@RunWith(RobolectricTestRunner.class)
@Config(
sdk = Build.VERSION_CODES.LOLLIPOP,
manifest = Config.NONE)
public class DefaultRequestConfigTest {
@Test
public void loggedOutConfigWithoutParameter() throws Exception {
DefaultRequestConfig.Builder builder = new DefaultRequestConfig.Builder();
builder.setLoggedOut(true);
DefaultRequestConfig defaultRequestConfig = builder.build();
assertNotNull(defaultRequestConfig);
assertNull(defaultRequestConfig.getOauthSigner());
}
@Test
public void loggedOutConfigWithOneParameter() throws Exception {
DefaultRequestConfig.Builder builder = new DefaultRequestConfig.Builder();
builder.setLoggedOut(true);
builder.addParam("key1", "value1");
DefaultRequestConfig defaultRequestConfig = builder.build();
assertNotNull(defaultRequestConfig);
List<Pair<String, String>> commonParams = defaultRequestConfig.getCommonParams();
assertNotNull(commonParams);
assertEquals(1, commonParams.size());
Pair<String, String> param = commonParams.get(0);
assertEquals("key1", param.first);
assertEquals("value1", param.second);
}
@Test
public void loggedOutConfigWithTwoParameters() throws Exception {
DefaultRequestConfig.Builder builder = new DefaultRequestConfig.Builder();
builder.setLoggedOut(true);
List<Pair<String, String>> params = new ArrayList<>(2);
params.add(new Pair<>("key1", "value1"));
params.add(new Pair<>("key2", "value2"));
builder.addParams(params);
DefaultRequestConfig defaultRequestConfig = builder.build();
assertNotNull(defaultRequestConfig);
List<Pair<String, String>> commonParams = defaultRequestConfig.getCommonParams();
assertNotNull(commonParams);
assertEquals(2, commonParams.size());
assertArrayEquals(params.toArray(), commonParams.toArray());
}
}
| true |
251f473c861eb09e203333ee64a556ea6215c975 | Java | JonathanKershaw/integration-rest | /src/main/java/com/synopsys/integration/rest/service/IntResponseTransformer.java | UTF-8 | 3,571 | 1.882813 | 2 | [
"Apache-2.0"
] | permissive | /**
* integration-rest
*
* Copyright (c) 2020 Synopsys, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.synopsys.integration.rest.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonObject;
import com.synopsys.integration.exception.IntegrationException;
import com.synopsys.integration.rest.client.IntHttpClient;
import com.synopsys.integration.rest.component.IntRestResponse;
import com.synopsys.integration.rest.request.PageRequestHandler;
import com.synopsys.integration.rest.request.Request;
import com.synopsys.integration.rest.request.Response;
public class IntResponseTransformer {
private final IntHttpClient intHttpClient;
private final IntJsonTransformer intJsonTransformer;
public IntResponseTransformer(final IntHttpClient intHttpClient, final IntJsonTransformer intJsonTransformer) {
this.intHttpClient = intHttpClient;
this.intJsonTransformer = intJsonTransformer;
}
public <R extends IntRestResponse> R getResponses(Request.Builder requestBuilder, PageRequestHandler pageRequestHandler, final Class<R> responseClass, int pageSize) throws IntegrationException {
final List<R> allResponses = new ArrayList<>();
int currentResponseDataCount = 0;
int totalResponseDataCount;
int offset = 0;
do {
final Request request = pageRequestHandler.createPageRequest(requestBuilder, offset, pageSize);
final R response = getResponse(request, responseClass);
allResponses.add(response);
currentResponseDataCount += pageRequestHandler.getCurrentResponseCount(response);
totalResponseDataCount = pageRequestHandler.getTotalResponseCount(response);
offset += pageSize;
} while (totalResponseDataCount > currentResponseDataCount);
return pageRequestHandler.combineResponses(allResponses);
}
public <R extends IntRestResponse> R getResponse(Request request, Class<R> responseClass) throws IntegrationException {
try (final Response response = intHttpClient.execute(request)) {
intHttpClient.throwExceptionForError(response);
return intJsonTransformer.getResponse(response, responseClass);
} catch (final IOException e) {
throw new IntegrationException(e.getMessage(), e);
}
}
public <R extends IntRestResponse> R getResponseAs(String json, Class<R> responseClass) throws IntegrationException {
return intJsonTransformer.getComponentAs(json, responseClass);
}
public <R extends IntRestResponse> R getResponseAs(JsonObject jsonObject, Class<R> responseClass) throws IntegrationException {
return intJsonTransformer.getComponentAs(jsonObject, responseClass);
}
}
| true |
fb0f5fabdfaf7a926f56f2f52849ed651268315d | Java | congyaoyang/recycle | /demo_recycle/src/main/java/com/qianfeng/mapper/ModelInfoMapper.java | UTF-8 | 274 | 1.796875 | 2 | [] | no_license | package com.qianfeng.mapper;
import com.qianfeng.vo.ModelInfoVo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface ModelInfoMapper {
ModelInfoVo selectModelInfoById(@Param("modelId") Integer modelId);
}
| true |
d6e783ad6105f82e15ef68b02dae20010526adc7 | Java | MohammadReza-Ahmadi/concurrent-players | /src/main/java/com/_360t/simple/multiprocesses/TowProcessesCallFromJarApp.java | UTF-8 | 4,620 | 2.96875 | 3 | [] | no_license | package com._360t.simple.multiprocesses;
import com._360t.simple.PlayerRole;
import com._360t.simple.PlayerUtil;
import com._360t.structured.config.JarFromPomConfig;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
/**
* <h3 style="color:#55A3C4"> Two Process App which should be called only through existing jar file of application </h3>
* <p style="color:#3F7A14">
* This class is used to define an endpoint of execution through main method.
* The main method is able to analyze input string args value and extract sending parameters
* and send its parameter to the runner class.
* The runner class will be created base on the input parameters and run into its java process.
*
* @author MohammadReza Ahmadi
* @since 9/3/2020
*/
public class TowProcessesCallFromJarApp {
public static void main(String[] args) throws Exception {
int port = 2021;
int messageNumber = 2;
String initiatorMessage = "Hi 360T";
int delayMilliSeconds = 1000;
String jarFileName;
port = PlayerUtil.getArgsIntValue(args, 0, port);
messageNumber = PlayerUtil.getArgsIntValue(args, 1, messageNumber);
initiatorMessage = PlayerUtil.getArgsStringValue(args, 2, initiatorMessage);
if ((jarFileName = PlayerUtil.getArgsStringValue(args, 4)).isEmpty()) {
jarFileName = JarFromPomConfig.getPropertyValue("simple.two.processes.app").concat(".jar");
}
jarFileName = JarFromPomConfig.getPropertyValue("simple.two.processes.app").concat(".jar");
System.out.println("###### Simple TwoProcessesApp is running ... ######");
final Process initiator = getPlayerProcess(Player.class, PlayerRole.INITIATOR, port, initiatorMessage, messageNumber, delayMilliSeconds,jarFileName);
new Thread(() -> {
printProcessMessage(initiator);
}).start();
final Process receiver = getPlayerProcess(Player.class, PlayerRole.RECEIVER, port, initiatorMessage, messageNumber, delayMilliSeconds,jarFileName);
new Thread(() -> {
printProcessMessage(receiver);
}).start();
}
/**
* getPlayerProcess method which receive couple of parameters and create a java process and run the specified runner class
*
* @param clazz The class type of the specified runner class.
* @param playerRole The role of player.
* @param messageNumber The number of messages will be exchange between both players.
* @param delayMilliSeconds The delly milliseconds which will be exist between every message transmission.
* @param message The initiator message value
* @param jarFileName The jar file name which this program will execute through that.
* @return a java.lang.Process instance which responsible to executing passed runner class.
* @throws IOException The exception is throws when an error is occurred.
*/
private static Process getPlayerProcess(Class clazz, PlayerRole playerRole, int port, String message, int messageNumber, int delayMilliSeconds, String jarFileName) throws IOException {
String jarFileDirectory = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
/** resolve jar file location in the host operation system*/
jarFileDirectory = jarFileDirectory.split("([a-zA-Z0-9\\s_\\\\.\\-\\(\\):])+(.jar)")[0];
/** resolve jar file name based on input parameter name or JarFromConfig property file which is created from maven pom file*/
jarFileName = (jarFileName == null || jarFileName.isEmpty()) ? JarFromPomConfig.getPropertyValue("structured.single.processes.app").concat(".jar") : jarFileName;
return new ProcessBuilder("java", "-cp",
jarFileName,
clazz.getName(),
playerRole.toString(),
String.valueOf(port),
message,
String.valueOf(messageNumber),
String.valueOf(delayMilliSeconds))
.directory(new File(jarFileDirectory))
.inheritIO()
.start();
}
/**
* @param process of each player or processor execution which will be send to this method to read its input stream.
*/
private static void printProcessMessage(Process process) {
try (Scanner scanner = new Scanner(process.getInputStream())) {
while (scanner.hasNext())
System.out.println(scanner.nextLine());
}
}
}
| true |
2a4246ffb0475e54768d5ce4cb9c5f1d1024b787 | Java | ThomBrice/java_project | /src/card/test/BasicCard.java | UTF-8 | 1,680 | 3.796875 | 4 | [] | no_license | package card.test;
import java.text.DecimalFormat;
/**
* La classe BasicCard représente une carte de fidélité basique
* Elle hérite de la classe abstraite Card
*
* Une carte de fidélité basique comporte une cagnotte qui peut être utilisée lors du réglement;
* Lors de chaque achat 5% du montant de la facture vont sur la cagnotte.
*
*/
public class BasicCard extends Card {
/**
* Cagnotte de la carte basique.
*/
private double balance;
DecimalFormat df = new DecimalFormat("0.00");
/**
* Constructeur 1 de la classe BasicCard
* Ce constructeur est appelé lors de la création d'un nouveau compte.
* @see Store#createCard(int)
* @param cardNum : numéro de carte
*/
public BasicCard(int cardNum) {
setBalance(0);
setAdvantage(0.05);
setCardNumber(cardNum);
}
/**
* Constructeur 2 de la classe BasicCard
* Ce constructeur est utilisé pour créer les objets BasicCard déjà existants qui sont stockés dans le fichier .txt
* @param cardNum : numéro de carte
* @param bal : montant de la cagnotte
*/
public BasicCard(int cardNum, double bal) {
setCardNumber(cardNum);
setBalance(bal);
setAdvantage(0.05);
}
/**
* Affiche les détails la carte basique.
*/
@Override
public void printCardDetails(){
System.out.println("\nVous avez la carte de fidelité basique.");
System.out.println("Lors de chaque achat, 5% du montant de la facture vont sur la cagnote de votre carte.");
System.out.println("Vous avez : " + df.format(getBalance()) + "euros sur votre carte. \n");
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
| true |
42f368262d5714ec2e44ed357968ff7768d29836 | Java | xhh1234/diycode2 | /diycode_api/src/main/java/com/mystudy/diycode_api/test/been/Hello.java | UTF-8 | 1,239 | 2.515625 | 3 | [] | no_license | package com.mystudy.diycode_api.test.been;
import java.io.Serializable;
/**
* 测试(测试 token 是否管用)
*/
public class Hello implements Serializable {
private int id; // 当前用户唯一 id
private String login; // 当前用户登录用户名
private String name; // 当前用户昵称
private String avatar_url; // 当前用户的头像链接
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setLogin(String login) {
this.login = login;
}
public String getLogin() {
return this.login;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAvatar_url(String avatar_url) {
this.avatar_url = avatar_url;
}
public String getAvatar_url() {
return this.avatar_url;
}
@Override
public String toString() {
return "Hello{" +
"id=" + id +
", login='" + login + '\'' +
", name='" + name + '\'' +
", avatar_url='" + avatar_url + '\'' +
'}';
}
}
| true |
4dec99cddd43e60c3c6b995b88af2caa5d9825fa | Java | pf-oss/agg_demo | /security/security-demo/src/main/java/com/security/security/controller/TestController.java | UTF-8 | 950 | 2 | 2 | [
"Apache-2.0"
] | permissive | package com.security.security.controller;
// TestController.java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.security.PermitAll;
/**
* @Description:
* @author: pf
* @create: 2020/12/29 18:02
*/
@RestController
@RequestMapping("/" +
"")
public class TestController {
@PermitAll
@GetMapping("/echo")
public String demo() {
return "示例返回";
}
@GetMapping("/home")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String home() {
return "我是首页";
}
@GetMapping("/admin")
public String admin() {
return "我是管理员";
}
@GetMapping("/normal")
public String normal() {
return "我是普通用户";
}
}
| true |
0f354e77a842f8f85301045d0504ac837e53aac6 | Java | bpatel66/Data-Structures-and-Algorithms-Implementations | /Singly Linked List/src/LinkedListExtraTests.java | UTF-8 | 12,371 | 3.296875 | 3 | [] | no_license | import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* Additional JUnits for Homework 1.
*
* @author CS 1332 TAs
* @version 1.0
*/
public class LinkedListExtraTests {
private static final long TIMEOUT = 200;
private SinglyLinkedList<Integer> actual;
private Integer[] expected;
@Before
public void setup() {
actual = new SinglyLinkedList<Integer>();
expected = new Integer[0];
}
/**
* Checks both the structure and the size of the list.
*/
private void checkList() {
assertEquals(expected.length, actual.size());
LinkedListNode<Integer> current = actual.getHead();
for (int i = 0; i < expected.length; i++) {
assertNotEquals(null, current);
assertEquals(expected[i], current.getData());
current = current.getNext();
}
assertEquals(null, current);
if (expected.length == 0) {
assertEquals(null, actual.getTail());
} else {
int length = expected.length;
assertEquals(expected[length - 1], actual.getTail().getData());
}
}
/**
* Creates a list of length size in sorted order. So, if size is 5, then
* the list will be [1, 2, 3, 4, 5]. Updates both the {@code actual} and
* {@code expected} to be this list.
*
* Uses the addToBack method to work.
*
* @param size the size of the list to make
*/
private void createNoDuplicates(int size) {
if (size < 0) {
throw new IllegalArgumentException("Size cannot be negative.");
} else {
expected = new Integer[size];
for (int i = 0; i < size; i++) {
expected[i] = new Integer(i);
actual.addToBack(expected[i]);
}
}
}
/**
* Creates the list [2, 2, 3, 4, 5, 3]. Updates both the {@code actual}
* and {@code expected} to be this list.
*
* Uses the addToBack method to work.
*/
private void createDuplicates() {
expected = new Integer[6];
expected[0] = new Integer(2);
expected[1] = new Integer(2);
expected[2] = new Integer(3);
expected[3] = new Integer(4);
expected[4] = new Integer(5);
expected[5] = new Integer(3);
for (int i = 0; i < expected.length; i++) {
actual.addToBack(expected[i]);
}
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void addAtIndexNegativeException() {
actual.addAtIndex(-1, new Integer(0));
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void addAtIndexPositiveException() {
actual.addAtIndex(1, new Integer(0));
}
@Test(timeout = TIMEOUT, expected = IllegalArgumentException.class)
public void addAtIndexNullException() {
actual.addAtIndex(0, null);
}
@Test(timeout = TIMEOUT)
public void addAtIndexEmptyList() {
// [] -> [1]
expected = new Integer[1];
expected[0] = new Integer(1);
actual.addAtIndex(0, expected[0]);
checkList();
}
@Test(timeout = TIMEOUT)
public void addAtIndexGeneral() {
// [] -> [2] -> [2, 3] -> [0, 2, 3] -> [0, 1, 2, 3] -> [0, 1, 2, 3, 4]
expected = new Integer[5];
for (int i = 0; i < 5; i++) {
expected[i] = new Integer(i);
}
actual.addAtIndex(0, expected[2]);
actual.addAtIndex(1, expected[3]);
actual.addAtIndex(0, expected[0]);
actual.addAtIndex(1, expected[1]);
actual.addAtIndex(4, expected[4]);
checkList();
}
@Test(timeout = TIMEOUT, expected = IllegalArgumentException.class)
public void addToFrontNullException() {
actual.addToFront(null);
}
@Test(timeout = TIMEOUT)
public void addToFrontEmptyList() {
// [] -> [1]
expected = new Integer[1];
expected[0] = new Integer(1);
actual.addToFront(expected[0]);
checkList();
}
@Test(timeout = TIMEOUT)
public void addToFrontGeneral() {
// [] -> [3] -> [2, 3] -> [1, 2, 3] -> [0, 1, 2, 3]
expected = new Integer[4];
for (int i = 0; i < 4; i++) {
expected[i] = new Integer(i);
}
actual.addToFront(expected[3]);
actual.addToFront(expected[2]);
actual.addToFront(expected[1]);
actual.addToFront(expected[0]);
checkList();
}
@Test(timeout = TIMEOUT, expected = IllegalArgumentException.class)
public void addToBackNullException() {
actual.addToBack(null);
}
@Test(timeout = TIMEOUT)
public void addToBackEmptyList() {
// [] -> [1]
expected = new Integer[1];
expected[0] = new Integer(1);
actual.addToBack(expected[0]);
checkList();
}
@Test(timeout = TIMEOUT)
public void addToBackGeneral() {
// [] -> [0] -> [0, 1] -> [0, 1, 2] -> [0, 1, 2, 3]
expected = new Integer[4];
for (int i = 0; i < 4; i++) {
expected[i] = new Integer(i);
}
actual.addToBack(expected[0]);
actual.addToBack(expected[1]);
actual.addToBack(expected[2]);
actual.addToBack(expected[3]);
checkList();
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void removeAtIndexNegativeException() {
actual.removeAtIndex(-1);
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void removeAtIndexEmptyList() {
actual.removeAtIndex(0);
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void removeAtIndexPositiveException() {
createNoDuplicates(2);
actual.removeAtIndex(2);
}
@Test(timeout = TIMEOUT)
public void removeAtIndexOneElement() {
// [0] -> []
createNoDuplicates(1);
assertEquals(expected[0], actual.removeAtIndex(0));
expected = new Integer[0];
checkList();
}
@Test(timeout = TIMEOUT)
public void removeAtIndexGeneral() {
// [0, 1, 2, 3, 4] -> [0, 1, 3, 4] -> [0, 1, 3] -> [1, 3] -> [1]
createNoDuplicates(5);
assertEquals(expected[2], actual.removeAtIndex(2));
assertEquals(expected[4], actual.removeAtIndex(3));
assertEquals(expected[0], actual.removeAtIndex(0));
assertEquals(expected[3], actual.removeAtIndex(1));
expected = new Integer[1];
expected[0] = new Integer(1);
checkList();
}
@Test(timeout = TIMEOUT)
public void removeFromFrontEmptyList() {
assertEquals(null, actual.removeFromFront());
}
@Test(timeout = TIMEOUT)
public void removeFromFrontOneElement() {
// [0] -> []
createNoDuplicates(1);
assertEquals(expected[0], actual.removeFromFront());
expected = new Integer[0];
checkList();
}
@Test(timeout = TIMEOUT)
public void removeFromFrontGeneral() {
// [0, 1, 2, 3, 4] -> [1, 2, 3, 4] -> [2, 3, 4] -> [3, 4] -> [4]
createNoDuplicates(5);
assertEquals(expected[0], actual.removeFromFront());
assertEquals(expected[1], actual.removeFromFront());
assertEquals(expected[2], actual.removeFromFront());
assertEquals(expected[3], actual.removeFromFront());
expected = new Integer[1];
expected[0] = new Integer(4);
checkList();
}
@Test(timeout = TIMEOUT)
public void removeFromBackEmptyList() {
assertEquals(null, actual.removeFromBack());
}
@Test(timeout = TIMEOUT)
public void removeFromBackOneElement() {
// [0] -> []
createNoDuplicates(1);
assertEquals(expected[0], actual.removeFromBack());
expected = new Integer[0];
checkList();
}
@Test(timeout = TIMEOUT)
public void removeFromBackGeneral() {
// [0, 1, 2, 3, 4] -> [0, 1, 2, 3] -> [0, 1, 2] -> [0, 1] -> [0]
createNoDuplicates(5);
assertEquals(expected[4], actual.removeFromBack());
assertEquals(expected[3], actual.removeFromBack());
assertEquals(expected[2], actual.removeFromBack());
assertEquals(expected[1], actual.removeFromBack());
expected = new Integer[1];
expected[0] = new Integer(0);
checkList();
}
@Test(timeout = TIMEOUT, expected = IllegalArgumentException.class)
public void indexOfNullException() {
actual.indexOf(null);
}
@Test(timeout = TIMEOUT)
public void indexOfNoDuplicates() {
// [0, 1, 2, 3, 4]
createNoDuplicates(5);
for (int i = 0; i < 5; i++) {
assertEquals(i, actual.indexOf(expected[i]));
}
assertEquals(-1, actual.indexOf(new Integer(-1)));
assertEquals(-1, actual.indexOf(new Integer(5)));
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT)
public void indexOfValueEquality() {
// [0, 1, 2, 3, 4]
createNoDuplicates(5);
for (int i = 0; i < 5; i++) {
assertEquals(i, actual.indexOf(new Integer(i)));
}
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT)
public void indexOfDuplicates() {
// [2, 2, 3, 4, 5, 3]
createDuplicates();
assertEquals(0, actual.indexOf(expected[0]));
assertEquals(0, actual.indexOf(expected[1]));
assertEquals(2, actual.indexOf(expected[2]));
assertEquals(3, actual.indexOf(expected[3]));
assertEquals(4, actual.indexOf(expected[4]));
assertEquals(2, actual.indexOf(expected[5]));
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void getNegativeException() {
actual.get(-1);
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void getEmptyList() {
actual.get(0);
}
@Test(timeout = TIMEOUT, expected = IndexOutOfBoundsException.class)
public void getPositiveException() {
createNoDuplicates(2);
actual.get(2);
}
@Test(timeout = TIMEOUT)
public void getGeneral() {
// [4, 3, 2, 1, 0]
expected = new Integer[5];
for (int i = 0; i < 5; i++) {
expected[i] = new Integer(4 - i);
actual.addToBack(expected[i]);
}
for (int i = 0; i < 5; i++) {
assertEquals(expected[i], actual.get(i));
}
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT)
public void toArrayEmptyList() {
assertEquals(expected, actual.toArray());
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT)
public void toArrayGeneral() {
createNoDuplicates(5);
assertEquals(expected, actual.toArray());
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT)
public void clearEmptyList() {
actual.clear();
checkList();
}
@Test(timeout = TIMEOUT)
public void clearGeneral() {
createNoDuplicates(5);
actual.clear();
expected = new Integer[0];
checkList();
}
@Test(timeout = TIMEOUT)
public void isEmptyTrue() {
assertEquals(true, actual.isEmpty());
// this method shouldn't modify the list
checkList();
}
@Test(timeout = TIMEOUT)
public void isEmptyFalse() {
createNoDuplicates(5);
assertEquals(false, actual.isEmpty());
// this method shouldn't modify the list
checkList();
}
} | true |
90b876652b9bdc0d64e138b5ad615cdddacfb629 | Java | namdaika19987/dattingdemo | /ProjectDattingNew-master/ProjectDattingNew-master/app/src/main/java/com/example/datting/Chat/AdapterChat/AdapterStatus.java | UTF-8 | 2,024 | 2.21875 | 2 | [] | no_license | package com.example.datting.Chat.AdapterChat;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.datting.Chat.MessageActivity;
import com.example.datting.Model.PeopleClass;
import com.example.datting.R;
import java.util.ArrayList;
public class AdapterStatus extends RecyclerView.Adapter<ViewHolder> {
ArrayList<PeopleClass> peopleClasses;
Context context;
public AdapterStatus(ArrayList<PeopleClass> peopleClasses, Context context) {
this.peopleClasses = peopleClasses;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_status, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
final PeopleClass people = peopleClasses.get(position);
//holder.image_status.setImageResource(people.getImage());
Glide.with(context).load(people.getImage()).into(holder.image_status);
holder.name_status.setText(people.getName());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(context, "hieuthanh", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, MessageActivity.class);
intent.putExtra("image",people.getImage());
intent.putExtra("name", people.getName());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return peopleClasses.size();
}
}
| true |
693b98a7d77ae10b6b6f29e808e9a3a9f137a258 | Java | tzajc/design-patterns | /structures/src/main/java/com/smalaca/facade/system/Facade.java | UTF-8 | 1,343 | 3.03125 | 3 | [] | no_license | package com.smalaca.facade.system;
import com.smalaca.facade.system.first.FirstSubsystem;
import com.smalaca.facade.system.fourth.FourthSubsystem;
import com.smalaca.facade.system.second.SecondSubsystem;
import com.smalaca.facade.system.third.ThirdSubsystem;
public class Facade {
private final FirstSubsystem firstSubsystem;
private final SecondSubsystem secondSubsystem;
private final ThirdSubsystem thirdSubsystem;
private final FourthSubsystem fourthSubsystem;
Facade(
FirstSubsystem firstSubsystem, SecondSubsystem secondSubsystem,
ThirdSubsystem thirdSubsystem, FourthSubsystem fourthSubsystem) {
this.firstSubsystem = firstSubsystem;
this.secondSubsystem = secondSubsystem;
this.thirdSubsystem = thirdSubsystem;
this.fourthSubsystem = fourthSubsystem;
}
public void doSomething() {
firstSubsystem.doSomething();
}
public void doSomethingElse() {
secondSubsystem.doSomethingElse();
}
public void doSomethingDifferent() {
thirdSubsystem.doSomethingDifferent();
}
public void doOtherThing() {
fourthSubsystem.doOtherThing();
}
public void doYetAnotherThing() {
firstSubsystem.doYetAnotherThing();
}
public void doStuff() {
secondSubsystem.doStuff();
}
}
| true |
b39acd3eaa03f74a6284eefae7d98de3dc26f945 | Java | farukcankaya/DynamicForm | /dynamicform/src/main/java/com/farukcankaya/dynamicform/internal/model/fields/RadioField.java | UTF-8 | 678 | 2.578125 | 3 | [] | no_license | package com.farukcankaya.dynamicform.internal.model.fields;
import com.farukcankaya.dynamicform.internal.model.fields.options.FieldOption;
/**
* Created by farukcankaya on 01/10/2017.
*/
public class RadioField extends Field {
/**
* TODO: there should be better way to do this!
*
* @return
*/
@Override
public Object getValue() {
if (super.getValue() == null) {
for (FieldOption fieldOption : getOptions()) {
if (fieldOption.isChecked()) {
setValue(fieldOption.getValue());
break;
}
}
}
return super.getValue();
}
}
| true |
16de0de76cd74ffdd7d95a290ec6fad311d4ec28 | Java | likesm0887/AccountProServer | /src/main/java/com/accountProServer/AccountProServer/adapter/requestModel/company/SetContactPersonRequestModel.java | UTF-8 | 258 | 1.507813 | 2 | [] | no_license | package com.accountProServer.AccountProServer.adapter.requestModel.company;
public class SetContactPersonRequestModel {
public String projectId;
public String name;
public String position;
public String telephone;
public String email;
}
| true |
ebea2f0e22db62cd545cea25f2bb47430ecfc675 | Java | M-Aly/JavaChatApp | /Chat/Gui/src/main/java/com/jets/gui/controller/server/RegisterController.java | UTF-8 | 7,520 | 1.796875 | 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 com.jets.gui.controller.server;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.rmi.RemoteException;
import java.sql.Date;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Observable;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
import javax.swing.plaf.basic.BasicBorders.RadioButtonBorder;
import com.jets.database.dal.dto.User;
import com.jets.database.dal.dto.enums.Country;
import com.jets.database.dal.dto.enums.UserStatus;
import com.jets.database.exception.InvalidInputException;
import com.jets.network.client.service.locator.ServiceLocator;
import com.jets.network.common.serverservice.IntroduceUserInt;
import com.jets.network.exception.NoSuchUserException;
import com.jets.network.exception.StatusChangeFailedException;
import com.jets.network.server.service.impl.IntroduceUser;
import javafx.beans.InvalidationListener;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ToggleGroup;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.*;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.scene.control.RadioButton;
import javafx.scene.image.*;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
/**
*
* @author PC
*/
public class RegisterController implements Initializable {
@FXML
private TextField PhoneNumTxt;
@FXML
private TextField NameTxt=null;
@FXML
private TextField EmailTxt;
@FXML
private ImageView ProfileImageView;
@FXML
private Button UploadPhotobTN;
@FXML
private ComboBox CountryComboBox;
@FXML
private DatePicker BirthdateCalender;
@FXML
private TextArea BioTxtArea;
@FXML
private Button RegisterBtn;
@FXML
private PasswordField PassField;
@FXML
private PasswordField ConfrimPassField;
@FXML
private AnchorPane AnchorPaneID;
@FXML
private Label Phone_lbl;
@FXML
private Label Name_lbl;
@FXML
private Label Password_lbl;
@FXML
private Label Email_lbl;
@FXML
private Label Confirm_lbl;
@FXML
private Label Birth_lbl;
@FXML
private ToggleGroup Gender;
@FXML
private Label Gender_lbl;
@FXML
private Label Country_lbl;
@FXML
private Label Bio_lbl;
@FXML
private RadioButton MaleRadioBtn;
@FXML
private RadioButton FemaleRadioBtn;
Image profileimage;
@Override
public void initialize(URL url, ResourceBundle rb) {
//IntroduceUser introduceUser=new IntroduceUser() ;
MaleRadioBtn.setSelected(true);
for(Country country : Country.values()){
CountryComboBox.getItems().add(country.toString());
}
UploadPhotobTN.setOnAction((e)-> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Image");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
File selectedImage = fileChooser.showOpenDialog(null);
if(selectedImage != null) {
profileimage = new Image(selectedImage.toURI().toString());
ProfileImageView.setImage(profileimage);
}
});
RegisterBtn.setOnAction((e)->{
Name_lbl.setText("*");
Password_lbl.setText("*");
Country_lbl.setText("*");
Confirm_lbl.setText("*");
Phone_lbl.setText("*");
Email_lbl.setText("*");
Bio_lbl.setText("*");
if(!(NameTxt.getText().isEmpty()) && !(ProfileImageView.getImage().equals(null)) && !(PassField.getText().isEmpty()) && !(PhoneNumTxt.getText().isEmpty()) && !(CountryComboBox.getSelectionModel().isEmpty()) && !(BioTxtArea.getText().isEmpty()) && Gender.getSelectedToggle().isSelected()!=true && !BirthdateCalender.getValue().toString().equals(null) && !(EmailTxt.getText().isEmpty()))
{
LocalDate localDate = BirthdateCalender.getValue();
Instant instant = Instant.from(localDate.atStartOfDay(ZoneId.systemDefault()));
java.sql.Date sqlDate = new java.sql.Date(Date.from(instant).getTime());
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) profileimage, "jpg", bos );
byte [] data = bos.toByteArray();
User user= new User(PhoneNumTxt.getText(),
NameTxt.getText(),
(Country)CountryComboBox.getValue(),
PassField.getText(),
true,
UserStatus.AVAILABLE,
data,
BioTxtArea.getText(),
Gender.getSelectedToggle().toString().charAt(0),
sqlDate,
EmailTxt.getText());
IntroduceUserInt introduceUser = (IntroduceUserInt)ServiceLocator.getInstance().getService("introduceuser");
introduceUser.register(user);
} catch (InvalidInputException e1) {
Alert alert = new Alert((javafx.scene.control.Alert.AlertType) AlertType.ERROR);
alert.setTitle("Register Error");
alert.setHeaderText("Results:");
alert.setContentText(e1.getMessage());
alert.showAndWait();
} catch (IOException e1) {
e1.printStackTrace();
} catch (NoSuchUserException e1) {
Alert alert = new Alert((javafx.scene.control.Alert.AlertType) AlertType.ERROR);
alert.setTitle("Register Error");
alert.setHeaderText("Results:");
alert.setContentText("This User is already defined");
alert.showAndWait();
}
}
else {
if(NameTxt.getText().isEmpty())
{
Name_lbl.setText("Name Must be Specifed");
}
if(PhoneNumTxt.getText().isEmpty())
{
Phone_lbl.setText("PhoneNumber Must be Specifed");
}
if(PassField.getText().isEmpty())
{
Password_lbl.setText("Password Must be Specifed");
}
if(ConfrimPassField.getText().isEmpty())
{
Confirm_lbl.setText("ConfirmPassword Must be Specifed");
}
if(EmailTxt.getText().isEmpty())
{
Email_lbl.setText("Email Must be Specifed");
}
if(BioTxtArea.getText().isEmpty())
{
Bio_lbl.setText("BioInformation Must be Specifed");
}
if(CountryComboBox.getSelectionModel().isEmpty())
{
Country_lbl.setText("Country Must be Specifed");
}
}
});
}
} | true |
bf6a6f607153775810a2b275e4acefa68ef7cdf8 | Java | mitkpatel/JavaPrograms | /Assignment3-Mit/Assignment3-mit/src/assignment3_mit/StudentList.java | UTF-8 | 5,905 | 3.390625 | 3 | [] | no_license | package assignment3_mit;
import java.util.Scanner;
public class StudentList {
public static void main(String[] args) {
// Instance Fields or variables
String studentId, studentName, assignmentName;
int userChoice, counterOfStudents = 0, counterOfAssignments = 0;
int assignmentId[] = new int[5];
double max_score, score_obtain, totalScore = 0, netScore = 0;
boolean quit = true, exit = true;
// Creating array of object
Student[] student = new Student[20];
Assignment[][] assignment = new Assignment[20][5];
Scanner sc = new Scanner(System.in);
//Loop for menu driven for user
do {
System.out.println("\nChoose operation you want to perform. (Press between 0 to 3).");
System.out.println("1. Add a new student");
System.out.println("2. Find and display existing student(Enter ID)");
System.out.println("3. Display all the students data");
System.out.println("Enter your choice, press 0 to quit.");
userChoice = Integer.parseInt(sc.nextLine());
quit = false;
switch (userChoice) {
case 1: // Case 1 is for adding new student
student[counterOfStudents] = new Student();
// loop for checking unique student id
do {
System.out.print("Enter student id: ");
studentId = sc.nextLine();
exit = true;
for (int i = 0; i <= counterOfStudents; i++) {
if ((String.valueOf(student[i].getStudentID()).contains(studentId))) {
System.out.printf("Error -- %s is already exist! Please enter new student ID.\n", studentId);
break;
}
else {
student[counterOfStudents].setStudentID(studentId);;
exit = false;
break;
}
}
} while (exit);
// loop for name validation
do {
System.out.print("Enter the name of student: ");
studentName = sc.nextLine();
if (student[counterOfStudents].setStudenName(studentName))
break;
else
System.out.println("Error -- Please enter name first!!!");
} while (true);
String choice = "yes";
for (int j = 0; choice.equalsIgnoreCase("yes");) {
assignment[counterOfStudents][j] = new Assignment();
// loop for checking unique assignment id
do {
System.out.print("Enter assignment id: ");
assignmentId[j] = Integer.parseInt(sc.nextLine());
exit = true;
for (int i = 0; i <= counterOfAssignments; i++) {
if ((String.valueOf(assignment[counterOfStudents][i].
getAssignmentID()).contains(String.valueOf(assignmentId[j]))))
{
System.out.printf("Error -- %d is already exist! Please enter new assignment id first!!!\n",
assignmentId[j]);
break;
}
else {
assignment[counterOfStudents][j].setAssignmentID(assignmentId[j]);
counterOfAssignments++;
exit = false;
break;
}
}
} while (exit);
// loop for name validation
do {
System.out.print("Enter assignment name: ");
assignmentName = sc.nextLine();
if (assignment[counterOfStudents][j].setAssignmentName(assignmentName))
break;
else
System.out.println("Error -- Please enter assignment name first!!!");
} while (true);
// loop for MAX score validation
do {
System.out.print("Enter max score: ");
max_score = Double.parseDouble(sc.nextLine());
if (assignment[counterOfStudents][j].setMaximunScore(max_score)) {
totalScore = totalScore + max_score;
break;
} else
System.out.println("Error -- Please enter score between 1 to 10 !!!");
} while (true);
// loop for obtain score validation
do {
System.out.print("Enter the score student obtain: ");
score_obtain = Double.parseDouble(sc.nextLine());
if (assignment[counterOfStudents][j].setScoreObtain(score_obtain)) {
netScore = netScore + score_obtain;
break;
} else
System.out.println(
"\nError -- Please enter score between " + assignment[counterOfStudents][j].MIN_SCORE
+ " to " + assignment[counterOfStudents][j].maximunScoreTemp);
} while (true);
// terminate the inner for loop if user has no assignment or greather then 5 assignment
System.out.print("\nDo you have more asssignment (yes -- to continue)? ");
choice = sc.nextLine();
if (choice.equalsIgnoreCase("yes")) {
if (j >= 4) {
System.out.println("Sorry, you can't add more than 5 assignments!!!");
choice = "no";
counterOfStudents++;
break;
} else {
j++;
continue;
}
} else {
break;
}
}
counterOfStudents++; //for second student
break;
case 2: // Case 2 is for display particular student record.
System.out.println("Enter student id to find details: ");
String id = sc.nextLine();
for (int i = 0; i < counterOfStudents; i++) {
for (int k = 0; k < counterOfAssignments; k++) {
if ((String.valueOf(student[i].getStudentID()).contains(id))) { //checking id is exits or not
if (assignment[i][k] == null)
break;
else {
System.out.println(student[i]);
System.out.println(assignment[i][k]);
}
}
}
}
break;
case 3: // Case 3 is for display all user data value
for (int k = 0; k < counterOfStudents; k++) {
System.out.println(student[k]);
for (int k2 = 0; k2 < counterOfAssignments; k2++) {
if (assignment[k][k2] == null)
break;
else
System.out.println(assignment[k][k2]);
}
System.out.print("\n");
}
break;
case 0: // Case 0 is for exit from the menu
quit = true;
System.out.println("All done!");
break;
default: // Default value is for validating the user choice
System.out.println("\nWrong choice. Please enter between 0 to 3.");
break;
}
} while (!quit);
}
}
| true |
b1b1c27f05a204aa744e13222e9782175f96e8bc | Java | franaiello/Exercises | /src/main/java/com/aiello/exercise/Palindrome.java | UTF-8 | 2,883 | 4.15625 | 4 | [] | no_license | package com.aiello.exercise;
import java.util.ArrayList;
import java.util.List;
public class Palindrome {
/**
* Accepts a string argument and determines if it is
* a palindrome or not
*
* @param str
* @return
*/
public static boolean isPalindrome(String str) {
if (str == null) {
return false;
}
if (! isCharsEqual(str)) return false;
return true;
}
/**
* Accepts a integer array and finds the largest value
* and returns this value
*
* @param data
* @return
*/
public static int findLargestInt(int[] data) {
int largestInt = 0;
for (int i=0; i < data.length; i++) {
if(data[i]>=largestInt) {
largestInt = data[i];
}
}
return largestInt;
}
/**
* Accepts two string arguments and returns them in reverse order
*
* @param strA
* @param strB
* @return
*/
public static String[] switchingStrings(String strA, String strB) {
String a = strA;
String b = strB;
a = a + b;
b = a.substring(0, a.length() - b.length());
a = a.substring(b.length(), a.length());
return new String[]{ a, b };
}
/**
* Accepts a integer argument and determines if it is
* a palindrome or not
*
* @param value
* @return
*/
public static boolean isPalindrome(Integer value) {
if (value == null) {
return false;
}
String str = value.toString();
if (! isCharsEqual(str)) return false;
return true;
}
public static List<Result> findPalindrome(int from, int to) {
List<Result> list = new ArrayList<Result>();
for (int x = from, y = from; x <= to && y <= to; x++, y++) {
Integer product = x * y;
if (isPalindrome(product.toString())) {
Result result = getResult(x, y, product);
list.add(result);
}
}
return list;
}
private static Result getResult(int x, int y, Integer product) {
Result result = new Result();
result.x = x;
result.y = y;
result.setProduct(product);
return result;
}
/**
* Accepts a string and iterates across each character starting
* from the beginning and end of string and compares each character
* against the other for equality.
*
* @param str
* @return
*/
private static boolean isCharsEqual(String str) {
for (int i = 0, j = str.length() - 1; i < j; i++, j--) {
Character c = str.toLowerCase().charAt(i);
Character c2 = str.toLowerCase().charAt(j);
if (!c.equals(c2)) {
return false;
}
}
return true;
}
}
| true |
128a9bc7b4fa7be3fc68ed5f569c85670652150e | Java | Khal-Shah/Java_And_Data_Structure_Exercises | /Ch09_Objects_Classes/ch9exercises/Ch9_04_RandomNum_Obj.java | UTF-8 | 589 | 3.90625 | 4 | [] | no_license | package ch9exercises;
import java.util.Random;
/* Chapter 9 - Exercise 4:
* (Use the Random class) Write a program that creates a Random object with seed 1000 and displays the first 50
* random integers between 0 and 100 using the nextInt(100) method.
*/
//By Khaled Shah
public class Ch9_04_RandomNum_Obj
{
public static void main(String[] args)
{
Random r1 = new Random(1000);
displayRandoms(r1);
}
public static void displayRandoms (Random r1)
{
for (int i = 1; i <= 50; i++)
{
System.out.print(r1.nextInt(100) + "\t" + ((i % 5 == 0)? "\n" : ""));
}
}
}
| true |
49cefb6326aa61202660062a4e3417289b413256 | Java | 1807-mehrab/p2-netoketo | /NetoKeto/src/main/java/com/revature/config/HibernateConfig.java | UTF-8 | 5,462 | 1.8125 | 2 | [] | no_license | package com.revature.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.revature.repository.CommentDao;
import com.revature.repository.ImageDao;
import com.revature.repository.RecipeDao;
import com.revature.repository.RecipeRatingDao;
import com.revature.repository.UserDao;
import com.revature.services.CommentService;
import com.revature.services.ImageService;
import com.revature.services.LoginService;
import com.revature.services.RecipeRatingService;
import com.revature.services.RecipeService;
import com.revature.services.UserService;
@Configuration
@ComponentScan("com.revature")
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class HibernateConfig extends WebMvcConfigurerAdapter {
@Autowired
private Environment env;
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Bean
public DataSource myDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(new String[] {"com.revature"});
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.dialect" , env.getProperty("hibernate.dialect"));
setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
}
};
}
@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager tm = new HibernateTransactionManager();
tm.setSessionFactory(sessionFactory);
return tm;
}
@Bean
public UserDao userDao(SessionFactory sessionFactory) {
UserDao dao = new UserDao();
dao.setSessionFactory(sessionFactory);
return dao;
}
@Bean
public UserService userService(UserDao dao) {
UserService us = new UserService();
us.setDao(dao);
return us;
}
@Bean
public LoginService loginService(UserDao dao) {
LoginService ls = new LoginService();
ls.setDao(dao);
return ls;
}
@Bean
public RecipeDao recipeDao(SessionFactory sessionFactory) {
RecipeDao dao = new RecipeDao();
dao.setSessionFactory(sessionFactory);
return dao;
}
@Bean
public RecipeService recipeService(RecipeDao dao) {
RecipeService rs = new RecipeService();
rs.setDao(dao);
return rs;
}
@Bean
public CommentDao commentDao(SessionFactory sessionFactory) {
CommentDao dao = new CommentDao();
dao.setSessionFactory(sessionFactory);
return dao;
}
@Bean
public CommentService commentService(CommentDao dao) {
CommentService cs = new CommentService();
cs.setDao(dao);
return cs;
}
@Bean
public RecipeRatingDao recipeRatingDao(SessionFactory sessionFactory) {
RecipeRatingDao dao = new RecipeRatingDao();
dao.setSessionFactory(sessionFactory);
return dao;
}
@Bean
public RecipeRatingService recipeRatingService(RecipeRatingDao dao) {
RecipeRatingService rrs= new RecipeRatingService();
rrs.setDao(dao);
return rrs;
}
@Bean
public ImageDao imageDao(SessionFactory sessionFactory) {
ImageDao dao = new ImageDao();
dao.setSessionFactory(sessionFactory);
return dao;
}
@Bean
public ImageService imageService(ImageDao dao) {
ImageService is= new ImageService();
is.setDao(dao);
return is;
}
} | true |
cde66c124d5567286dde953189ae2a5c7b99a424 | Java | oscarcs/Tatai | /src/views/level/Level.java | UTF-8 | 4,942 | 2.65625 | 3 | [] | no_license | package views.level;
import java.net.URL;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.Collections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.text.Text;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
import game.Game;
import views.game_end.GameEnd;
import views.game_end.GameEndView;
import views.main_container.MainContainer;
/**
* Class for the main game screen in the application.
* @author szhu842, osim082
*/
public class Level implements Initializable {
private HashMap<Integer, Rectangle> progressBar;
@FXML
Rectangle r1, r2, r3, r4, r5, r6, r7, r8, r9, r10;
@FXML
Circle circle;
@FXML
Button recordButton, playButton;
@FXML
Text questionText, answerStatus, receivedAnswerText, questionNumberText;
@FXML
Text attemptText, roundText;
private Game game;
private HashMap<Integer, Boolean> roundData;
/**
* Initialize this scene.
*
* @param location
* @param resources
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
playButton.setDisable(true);
progressBar = new HashMap<Integer, Rectangle>();
progressBar.put(1, r1);
progressBar.put(2, r2);
progressBar.put(3, r3);
progressBar.put(4, r4);
progressBar.put(5, r5);
progressBar.put(6, r6);
progressBar.put(7, r7);
progressBar.put(8, r8);
progressBar.put(9, r9);
progressBar.put(10, r10);
}
/**
* Method that is called to set the game model to this level.
*
* @param game
*/
public void setGame(Game game) {
this.game = game;
game.setLevel(this);
questionText.setText(game.questionText());
attemptText.setText("Attempt " + game.getCurrentAttempt());
answerStatus.setText("Waiting");
receivedAnswerText.setText("We received: ");
questionNumberText.setText("Question " + game.getCurrentRound());
setRoundColour(game.getRoundData());
}
/**
* When the user presses the record button.
*/
@FXML
public void recordHit() {
recordButton.setDisable(true);
playButton.setDisable(true);
answerStatus.setText("Waiting");
answerStatus.setFill(Color.WHITE);
circle.setFill(Color.web("#F7FF58"));
game.record();
}
/**
* When the user presses the record button.
*/
@FXML
public void playHit() {
game.play();
}
/**
* Called when 'next question' button is pressed.
*/
@FXML
public void nextQuestionHit() {
}
/**
* When the recording has completed this method is called.
*/
public void recordingDone() {
recordButton.setDisable(false);
playButton.setDisable(false);
game.process();
}
/**
* When processing is completed this method is called.
*/
public void processingDone() {
//...
}
/**
* When the user fails an attempt but the game is not over, this method is
* called.
*/
public void failedAttempt() {
recordButton.setDisable(false);
attemptText.setText("Attempt: " + game.getCurrentAttempt());
answerWrong();
}
/**
* When the user answers correct this method is called.
*/
public void answerCorrect() {
recordButton.setDisable(true);
playButton.setDisable(true);
answerStatus.setText("Correct");
answerStatus.setFill(Color.web("#2BFF52"));
circle.setFill(Color.web("#2BFF52"));
receivedAnswerText.setText("We received: " + game.getReceivedAnswer());
}
/**
* When the user answers wrong this method is called.
*/
public void answerWrong() {
answerStatus.setText("Incorrect");
answerStatus.setFill(Color.web("#d32c33"));
circle.setFill(Color.web("#d32c33"));
receivedAnswerText.setText("We received: " + game.getReceivedAnswer());
}
/**
* Go to the next question automatically.
*/
public void nextLevel() {
game.removeSound();
// Create a new level and pass the game into it.
LevelView levelView = new LevelView();
MainContainer.instance().changeCenter(levelView);
Level level = (Level) levelView.controller();
level.setGame(game);
}
/**
* When the game is over this method is called.
*/
public void endGame() {
// Create a end game screen and pass the game into it.
GameEndView gameEndView = new GameEndView();
MainContainer.instance().changeCenter(gameEndView);
GameEnd gameEnd = (GameEnd) gameEndView.controller();
gameEnd.setGame(game);
}
/**
* Change the state of the progress bar to reflect the current state.
* @param data the user currently playing data
*/
public void setRoundColour(HashMap<Integer, Boolean> data) {
for (int i = 1; i <= data.size(); i++) {
if (data.get(i)) {
progressBar.get(i).setStyle("-fx-fill: #2BFF52;");
}
else {
progressBar.get(i).setStyle("-fx-fill: #d32c33;");
}
}
}
}
| true |
f3282037a358e385df941c413df09d732236ea79 | Java | Data-to-Insight-Center/sead2 | /services/dataone-api/src/main/java/org/seadva/dataone/ObjectChecksum.java | UTF-8 | 6,726 | 1.617188 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2013 The Trustees of Indiana University
*
* 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.seadva.dataone;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import org.dataconservancy.dcs.index.dcpsolr.DcsSolrField;
import org.dataconservancy.dcs.index.solr.support.SolrQueryUtil;
import org.dataconservancy.dcs.query.api.QueryMatch;
import org.dataconservancy.dcs.query.api.QueryResult;
import org.dataconservancy.dcs.query.api.QueryServiceException;
import org.dataconservancy.model.dcs.DcsEntity;
import org.dataconservancy.model.dcs.DcsEvent;
import org.dataconservancy.model.dcs.DcsFile;
import org.dataconservancy.model.dcs.DcsFixity;
import org.dataone.service.types.v1.Checksum;
import org.dataone.service.types.v1.Event;
import org.jibx.runtime.JiBXException;
import org.seadva.model.pack.ResearchObject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.xml.transform.TransformerException;
import java.net.URLEncoder;
import java.util.List;
/*
* Return checksum for files
*/
@Path("/mn/v1/checksum")
public class ObjectChecksum {
public ObjectChecksum(){
}
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{pid}")
public String getChecksum(@Context HttpServletRequest request,
@HeaderParam("user-agent") String userAgent,
@PathParam("pid") String objectId,
@QueryParam("checksumAlgorithm") String checksumAlgorithm) throws JiBXException, TransformerException {
String test ="<error name=\"NotFound\" errorCode=\"404\" detailCode=\"1060\" pid=\""+ URLEncoder.encode(objectId)+"\" nodeId=\""+SeadQueryService.NODE_IDENTIFIER+"\">\n" +
"<description>The specified object does not exist on this node.</description>\n" +
"<traceInformation>\n" +
"method: mn.getChecksum hint: http://cn.dataone.org/cn/resolve/"+URLEncoder.encode(objectId)+"\n" +
"</traceInformation>\n" +
"</error>";
if(objectId.contains("TestingNotFound")||objectId.contains("Test"))
throw new NotFoundException(test);
objectId = objectId.replace("doi-", "http://dx.doi.org/");
String queryStr = SolrQueryUtil.createLiteralQuery("resourceValue", objectId);
if(checksumAlgorithm!=null)
queryStr+= " AND "+SolrQueryUtil.createLiteralQuery(DcsSolrField.FixityField.ALGORITHM.solrName(), checksumAlgorithm);
QueryResult<DcsEntity> result = null;
try {
result = SeadQueryService.queryService.query(queryStr, 0, -1); //sort by filename
} catch (QueryServiceException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
String ip = null;
if(request!=null)
ip = request.getRemoteAddr();
List<QueryMatch<DcsEntity>> matches = result.getMatches();
if(matches.size()==0){
WebResource webResource = Client.create()
.resource(SeadQueryService.SEAD_DATAONE_URL + "/checksum")
.path(URLEncoder.encode(objectId));
if(checksumAlgorithm!=null) {
webResource = webResource.queryParam("checksumAlgorithm", checksumAlgorithm);
}
ClientResponse response = webResource
.header("user-agent", userAgent)
.header("remoteAddr", ip == null ? "" : ip)
.accept("application/xml")
.type("application/xml")
.get(ClientResponse.class);
if (response.getStatus() == 200) {
Checksum mongoChecksum = (Checksum) SeadQueryService.unmarshal(response.getEntityInputStream(), Checksum.class);
return SeadQueryService.marshal(mongoChecksum);
} else {
throw new NotFoundException(test);
}
}
for(QueryMatch<DcsEntity> entity: matches){
if(entity.getObject() instanceof DcsFile) {
DcsFile file = (DcsFile)entity.getObject();
if(file.getFixity().size()>0){
for(DcsFixity fixity:file.getFixity())
{
Checksum checksum = new Checksum();
if(checksumAlgorithm!=null){
if(SeadQueryService.sead2d1fixity.get(fixity.getAlgorithm()).equals(checksumAlgorithm)){
checksum.setAlgorithm(checksumAlgorithm);
checksum.setValue(fixity.getValue());
DcsEvent readEvent = SeadQueryService.dataOneLogService.creatEvent(Event.READ.xmlValue(), userAgent, ip, entity.getObject());
ResearchObject eventsSip = new ResearchObject();
eventsSip.addEvent(readEvent);
SeadQueryService.dataOneLogService.indexLog(eventsSip);
return SeadQueryService.marshal(checksum);
}
continue;
}
else{
checksum.setAlgorithm(SeadQueryService.sead2d1fixity.get(fixity.getAlgorithm()));
checksum.setValue(fixity.getValue());
DcsEvent readEvent = SeadQueryService.dataOneLogService.creatEvent(Event.READ.xmlValue(), userAgent, ip, entity.getObject());
ResearchObject eventsSip = new ResearchObject();
eventsSip.addEvent(readEvent);
SeadQueryService.dataOneLogService.indexLog(eventsSip);
return SeadQueryService.marshal(checksum);
}
}
}
}
}
return SeadQueryService.marshal(new Checksum());
}
}
| true |
cd9319ce680ffc46df3c5886ad83862844768159 | Java | develar/chromedevtools | /wip/protocol-model/generated/org/jetbrains/wip/protocol/dom/MoveTo.java | UTF-8 | 1,052 | 2.375 | 2 | [
"BSD-3-Clause"
] | permissive | // Generated source
package org.jetbrains.wip.protocol.dom;
/**
* Moves node into the new container, places it before the given anchor.
*/
public final class MoveTo extends org.jetbrains.wip.protocol.WipRequest implements org.jetbrains.jsonProtocol.RequestWithResponse<org.jetbrains.wip.protocol.dom.MoveToResult, org.jetbrains.wip.protocol.ProtocolReponseReader> {
/**
* @param nodeId Id of the node to drop.
* @param targetNodeId Id of the element to drop into.
*/
public MoveTo(int nodeId, int targetNodeId) {
writeInt("nodeId", nodeId);
writeInt("targetNodeId", targetNodeId);
}
/**
* @param v Drop node before given one.
*/
public MoveTo insertBeforeNodeId(int v) {
writeInt("insertBeforeNodeId", v);
return this;
}
@Override
public String getMethodName() {
return "DOM.moveTo";
}
@Override
public MoveToResult readResult(com.google.gson.stream.JsonReaderEx jsonReader, org.jetbrains.wip.protocol.ProtocolReponseReader reader) {
return reader.readDOMMoveToResult(jsonReader);
}
} | true |
7674c54c24d112dd65cfa24969411e2575d5b841 | Java | LKostrzewa/Sudoku | /ModelProject/src/main/java/sudoku/Difficluty.java | UTF-8 | 807 | 3.078125 | 3 | [] | no_license | package sudoku;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public enum Difficluty {
EASY(20),
MEDIUM(40),
HARD(60);
private final int length;
Difficluty(final int len) {
this.length = len;
}
public void clean(final SudokuBoard sudoku) {
List<Integer> list = new ArrayList<>();
int max = SudokuBoard.BOARD_SIZE * SudokuBoard.BOARD_SIZE;
for (int i = 0; i < max; i++) {
list.add(i);
}
Collections.shuffle(list);
int brdSize = SudokuBoard.BOARD_SIZE;
for (int i = 0; i < length; i++) {
//System.out.print(list.get(i)+"\t");
sudoku.set(list.get(i) / brdSize, list.get(i) % brdSize, 0);
}
//System.out.println("\n");
}
}
| true |
b0f070c36e24c4cad38e57687a1cc74097b7b62d | Java | amir-bunjo/Go2Balkan | /src/main/java/ba/go2balkan/services/implementations/CbAccommodationTypeServiceImpl.java | UTF-8 | 1,237 | 2.234375 | 2 | [] | no_license | package ba.go2balkan.services.implementations;
import ba.go2balkan.model.cb.CbAccommodationType;
import ba.go2balkan.repository.CbAccommodationTypeRepository;
import ba.go2balkan.services.interfaces.CbAccommodationTypeService;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CbAccommodationTypeServiceImpl implements CbAccommodationTypeService {
private final CbAccommodationTypeRepository cbAccommodationTypeRepository;
public CbAccommodationTypeServiceImpl(CbAccommodationTypeRepository cbAccommodationTypeRepository) {
this.cbAccommodationTypeRepository = cbAccommodationTypeRepository;
}
@Override
public CbAccommodationType saveOrUpdate(CbAccommodationType cbAccommodationType) {
return cbAccommodationTypeRepository.save(cbAccommodationType);
}
@Override
public boolean delete(CbAccommodationType cbAccommodationType) {
try {
cbAccommodationTypeRepository.delete(cbAccommodationType);
return true;
} catch (Exception e) {
return false;
}
}
@Override
public List<CbAccommodationType> findAll() {
return cbAccommodationTypeRepository.findAll();
}
}
| true |
05146b96062cf68673ec33de3f09030395631fc6 | Java | MicroRefact/coolweatherMs | /11/Interface/RbacUserRightRelationRepository.java | UTF-8 | 125 | 1.554688 | 2 | [] | no_license | public interface RbacUserRightRelationRepository {
public Optional<RbacUserRightRelation> findByUserId(Integer userId);
} | true |
46f37ff60ad7ee61e47f1f58be9215fea7a094d6 | Java | tonyanangel/Skypremium2 | /app/src/main/java/com/skypremiuminternational/app/domain/models/myOrder/Shipping.java | UTF-8 | 852 | 2.15625 | 2 | [] | no_license | package com.skypremiuminternational.app.domain.models.myOrder;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* Created by aeindraaung on 2/7/18.
*/
public class Shipping implements Serializable {
@SerializedName("total")
@Expose
private Total total;
@SerializedName("address")
@Expose
private Address address;
@SerializedName("method")
@Expose
private String method;
public Total getTotal() {
return total;
}
public void setTotal(Total total) {
this.total = total;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
}
| true |
c42120750cf3ceaccd2968ee7d372b24b4d5441f | Java | mnq-naqui/CoreJava | /ExceptionHandling/src/com/lara/J.java | UTF-8 | 324 | 2.375 | 2 | [] | no_license | /** Progaram no 120 Lara Material
*
*/
package com.lara;
public class J {
public static void main(String[] args) {
System.out.println(1);
try {
int i = 12 / 0;
} catch (ArithmeticException e) {
System.out.println(2);
e.printStackTrace();
System.out.println(3);
}
System.out.println(4);
}
}
| true |
cb561a5848cbae90a9b7284abbf30814d3622304 | Java | shihabamin/GitPractice | /src/learnVariables/Variables.java | UTF-8 | 387 | 3.09375 | 3 | [] | no_license | package learnVariables;
import java.util.Scanner;
public class Variables {
public static void main(String[] args) {
int a = 10;
int b = 15;
String s = "Mahi";
a = b;
a = a+a;
System.out.println(" Hi, What is your age? ");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
System.out.println(n+n);
}
}
| true |
deaff2c6caf2c625d9fdd1ae8211d70101534eff | Java | afnancal/HariMitti | /src/main/java/com/afnan/harimitti/dao/DatabaseDaoImpl.java | UTF-8 | 2,473 | 2.296875 | 2 | [] | no_license | package com.afnan.harimitti.dao;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.afnan.harimitti.databasebackup.MysqlExportService;
import com.afnan.harimitti.model.ReturnMsg;
@Repository
public class DatabaseDaoImpl implements DatabaseDao {
@Autowired
private SessionFactory sessionFactory;
protected Session getSession() {
return sessionFactory.getCurrentSession();
}
@Override
public ReturnMsg databaseBackup(String email_id) {
// TODO Auto-generated method stub
ReturnMsg returnMsg = new ReturnMsg();
try {
// required properties for exporting of db
Properties properties = new Properties();
properties.setProperty(MysqlExportService.DB_NAME, "lllc");
properties.setProperty(MysqlExportService.DB_USERNAME, "user");
properties.setProperty(MysqlExportService.DB_PASSWORD, "password");
properties.setProperty(MysqlExportService.JDBC_CONNECTION_STRING, "jdbc:mysql://jws-app-mysql:3306/lllc");
// properties relating to email config
properties.setProperty(MysqlExportService.EMAIL_HOST, "smtp.gmail.com");
properties.setProperty(MysqlExportService.EMAIL_PORT, "587");
properties.setProperty(MysqlExportService.EMAIL_USERNAME, "apps@globopex.com");
properties.setProperty(MysqlExportService.EMAIL_PASSWORD, "apps@123#");
properties.setProperty(MysqlExportService.EMAIL_FROM, "apps@globopex.com");
properties.setProperty(MysqlExportService.EMAIL_TO, email_id);
// set the outputs temp dir
properties.setProperty(MysqlExportService.TEMP_DIR, new File("external").getPath());
MysqlExportService mysqlExportService = new MysqlExportService(properties);
String returnResult = mysqlExportService.export();
returnMsg.setStatus(true);
returnMsg.setMsg(returnResult);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
returnMsg.setStatus(false);
returnMsg.setMsg("" + e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
returnMsg.setStatus(false);
returnMsg.setMsg("" + e);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
returnMsg.setStatus(false);
returnMsg.setMsg("" + e);
}
return returnMsg;
}
}
| true |
86c3de3986c47ae9bb7e0af3108030972cd9f454 | Java | lylgjiavg/DesignPattern | /src/main/java/club/lylgjiang/iterator/version1/Main.java | UTF-8 | 633 | 3.203125 | 3 | [] | no_license | package club.lylgjiang.iterator.version1;
/**
* @Classname Main
* @Description 测试程序行为
* @Date 2019/10/11 17:23
* @Created by Jiavg
*/
public class Main {
public static void main(String[] args) {
BookShelf shelf = new BookShelf(4);
shelf.append(new Book("Java核心技术"));
shelf.append(new Book("算法导论"));
shelf.append(new Book("设计模式"));
shelf.append(new Book("计算机操作系统"));
Iterator iterator = shelf.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
| true |
969fa626064ba02c89004f5f521d9ff728994292 | Java | youkejiang/HFRM | /android/src/com/hoheart/hfc/EasyMusicPlayer.java | GB18030 | 4,594 | 2.453125 | 2 | [] | no_license | package com.hoheart.hfc;
import java.io.IOException;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* һ
*
* @author Hoheart
*
*/
public class EasyMusicPlayer {
public enum State {
NOT_INITED, INITED, READY, PLAYING, PAUSE
}
public interface OnStateChangeListener {
public void onStateChange(State s);
}
private OnSeekBarChangeListener mSeekBarChangeListener = new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int dest = seekBar.getProgress();
int mMax = mPlayer.getDuration();
int sMax = seekBar.getMax();
mPlayer.seekTo(mMax * dest / sMax);
}
};
private Handler mHandle = new Handler() {
@Override
public void handleMessage(Message msg) {
SeekBar seekBar = (SeekBar) mRootView
.findViewById(R.id.PlayerSeekBar);
if (null == seekBar) {
return;
}
int position = mPlayer.getCurrentPosition();
int mMax = mPlayer.getDuration();
int sMax = seekBar.getMax();
int p = 0;
if (mMax > 0) {
p = position * sMax / mMax;
}
seekBar.setProgress(p);
}
};
private Thread mSeekThread = new Thread() {
private int milliseconds = 500;
public void run() {
while (true) {
try {
sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandle.sendEmptyMessage(0);
}
}
};
private MediaPlayer mPlayer = null;
private View mRootView = null;
private OnStateChangeListener mOnStateChangeListener = null;
private State mState = State.NOT_INITED;
public EasyMusicPlayer(Context context) {
mPlayer = new MediaPlayer();
mSeekThread.start();
mRootView = View.inflate(context, R.layout.easy_music_player, null);
attachEvent();
changeState(State.INITED);
}
public void setOnStateChangeListener(OnStateChangeListener l) {
mOnStateChangeListener = l;
}
public void setDataSource(String path) throws IllegalArgumentException,
IllegalStateException, IOException {
mPlayer.stop();
mPlayer.reset();
mPlayer.setDataSource(path);
mPlayer.prepare();
changeState(State.READY);
}
public void pause() {
mPlayer.pause();
changeState(State.PAUSE);
}
public void start() {
mPlayer.start();
changeState(State.PLAYING);
}
public void stop() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
mPlayer.seekTo(0);
}
changeState(State.READY);
}
public void playOrPause() {
if (mPlayer.isPlaying()) {
pause();
} else {
start();
}
}
public View getView() {
return mRootView;
}
public State getState() {
return mState;
}
private void attachEvent() {
SeekBar seekBar = (SeekBar) mRootView.findViewById(R.id.PlayerSeekBar);
seekBar.setOnSeekBarChangeListener(mSeekBarChangeListener);
View btnClose = mRootView.findViewById(R.id.btn_player_close);
btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mRootView.setVisibility(View.GONE);
}
});
View btnPlay = mRootView.findViewById(R.id.btn_player_start);
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playOrPause();
}
});
View btnStop = mRootView.findViewById(R.id.btn_player_stop);
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stop();
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
stop();
}
});
}
private void changeState(State s) {
mState = s;
ImageButton btnPlayerStart = (ImageButton) mRootView
.findViewById(R.id.btn_player_start);
if (State.PLAYING == s) {
btnPlayerStart
.setImageResource(R.drawable.image_btn_pause_selector);
} else {
btnPlayerStart.setImageResource(R.drawable.image_btn_play_selector);
}
if (null != mOnStateChangeListener) {
mOnStateChangeListener.onStateChange(s);
}
}
}
| true |
3fd9ab8623ec3086be02ef5e2281e00dd0b9001b | Java | diniodinev/Hanoi-Towers | /src/main/java/bg/fmi/command/ICommand.java | UTF-8 | 654 | 1.617188 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2013 Dinio Dinev.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Dinio Dinev - initial API and implementation
******************************************************************************/
package bg.fmi.command;
/*
* Interface for declaration of operation execute
*/
public interface ICommand {
public void execute();
}
| true |
feb89c3af63619de8d3b47eb0bb9c5785c505662 | Java | kice/ModularRouters | /src/main/java/me/desht/modularrouters/util/BlockUtil.java | UTF-8 | 12,530 | 1.65625 | 2 | [
"MIT"
] | permissive | package me.desht.modularrouters.util;
import com.google.common.collect.Lists;
import com.mojang.authlib.GameProfile;
import me.desht.modularrouters.logic.filter.Filter;
import net.minecraft.block.*;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.*;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTUtil;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntitySkull;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.util.BlockSnapshot;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.event.ForgeEventFactory;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import net.minecraftforge.items.IItemHandler;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class BlockUtil {
private static final String[] REED_ITEM = new String[]{"block", "field_150935_a", "a"};
private static IBlockState getPlaceableState(EntityPlayer fakePlayer, ItemStack stack, World world, BlockPos pos, EnumFacing facing) {
// With thanks to Vazkii for inspiration from the Rannuncarpus code, although it's changed a lot since...
Item item = stack.getItem();
IBlockState res = null;
if (item instanceof ItemBlock) {
float hitX = (float) (fakePlayer.posX - pos.getX());
float hitY = (float) (fakePlayer.posY - pos.getY());
float hitZ = (float) (fakePlayer.posZ - pos.getZ());
int meta = item.getMetadata(stack.getItemDamage());
res = ((ItemBlock) item).block.getStateForPlacement(world, pos, facing, hitX, hitY, hitZ, meta, fakePlayer, stack);
} else if (item instanceof ItemBlockSpecial) {
res = ((Block) ReflectionHelper.getPrivateValue(ItemBlockSpecial.class, (ItemBlockSpecial) item, REED_ITEM)).getDefaultState();
} else if (item instanceof ItemRedstone) {
res = Blocks.REDSTONE_WIRE.getDefaultState();
} else if (item instanceof ItemDye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.BROWN) {
res = getCocoaBeanState(fakePlayer, world, pos, facing, stack);
if (res != null) {
facing = res.getValue(BlockHorizontal.FACING);
}
} else if (item instanceof IPlantable) {
IBlockState state = ((IPlantable) item).getPlant(world, pos);
res = ((state.getBlock() instanceof BlockCrops) && ((BlockCrops) state.getBlock()).canBlockStay(world, pos, state)) ? state : null;
} else if (item instanceof ItemSkull) {
res = Blocks.SKULL.getDefaultState();
// try to place skull on horizontal surface below if possible
BlockPos pos2 = pos.down();
if (world.getBlockState(pos2).isSideSolid(world, pos2, EnumFacing.UP)) {
facing = EnumFacing.UP;
}
}
if (res != null && res.getProperties().containsKey(BlockDirectional.FACING)) {
res = res.withProperty(BlockDirectional.FACING, facing);
}
return res;
}
private static IBlockState getCocoaBeanState(EntityPlayer fakePlayer, World world, BlockPos pos, EnumFacing facing, ItemStack stack) {
// try to find a jungle log in any horizontal direction
for (EnumFacing f : EnumFacing.HORIZONTALS) {
IBlockState state = world.getBlockState(pos.offset(f));
if (state.getBlock() == Blocks.LOG && state.getValue(BlockOldLog.VARIANT) == BlockPlanks.EnumType.JUNGLE) {
float hitX = (float) (fakePlayer.posX - pos.getX());
float hitY = (float) (fakePlayer.posY - pos.getY());
float hitZ = (float) (fakePlayer.posZ - pos.getZ());
fakePlayer.rotationYaw = getYawFromFacing(f); // fake player must face the jungle log
return Blocks.COCOA.getStateForPlacement(world, pos, f.getOpposite(), hitX, hitY, hitZ, 0, fakePlayer, stack);
}
}
return null;
}
private static float getYawFromFacing(EnumFacing facing) {
switch (facing) {
case WEST: return 90f;
case NORTH: return 180f;
case EAST: return 270f;
case SOUTH: return 0f;
default: return 0f; // shouldn't happen
}
}
private static void handleSkullPlacement(World worldIn, BlockPos pos, ItemStack stack, EnumFacing facing) {
// adapted from ItemSkull#onItemUse()
int i = 0;
if (worldIn.getBlockState(pos).getValue(BlockDirectional.FACING) == EnumFacing.UP) {
i = MathHelper.floor_double((double) (facing.getHorizontalAngle() * 16.0F / 360.0F) + 0.5D) & 15;
}
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity instanceof TileEntitySkull) {
TileEntitySkull tileentityskull = (TileEntitySkull) tileentity;
if (stack.getMetadata() == 3) { // player head
GameProfile gameprofile = null;
if (stack.hasTagCompound()) {
NBTTagCompound nbttagcompound = stack.getTagCompound();
if (nbttagcompound.hasKey("SkullOwner", Constants.NBT.TAG_COMPOUND)) {
gameprofile = NBTUtil.readGameProfileFromNBT(nbttagcompound.getCompoundTag("SkullOwner"));
} else if (nbttagcompound.hasKey("SkullOwner", Constants.NBT.TAG_STRING) && !nbttagcompound.getString("SkullOwner").isEmpty()) {
gameprofile = new GameProfile(null, nbttagcompound.getString("SkullOwner"));
}
}
tileentityskull.setPlayerProfile(gameprofile);
} else {
tileentityskull.setType(stack.getMetadata());
}
tileentityskull.setSkullRotation(i); // skull will face the router fake-player
Blocks.SKULL.checkWitherSpawn(worldIn, pos, tileentityskull);
}
}
/**
* Try to place the given item as a block in the world. This will fail if the block currently at the
* placement position isn't replaceable, or world physics disallows the new block from being placed.
*
* @param toPlace item to place
* @param world the world
* @param pos position in the world to place at
* @param facing direction the placer is facing
* @return the new block state if successful, null otherwise
*/
public static IBlockState tryPlaceAsBlock(ItemStack toPlace, World world, BlockPos pos, EnumFacing facing) {
IBlockState currentState = world.getBlockState(pos);
if (!currentState.getBlock().isReplaceable(world, pos)) {
return null;
}
EntityPlayer fakePlayer = FakePlayer.getFakePlayer((WorldServer) world, pos).get();
if (fakePlayer == null) {
return null;
}
fakePlayer.rotationYaw = getYawFromFacing(facing);
IBlockState newState = getPlaceableState(fakePlayer, toPlace, world, pos, facing);
if (newState != null && newState.getBlock().canPlaceBlockAt(world, pos)) {
BlockSnapshot snap = new BlockSnapshot(world, pos, newState);
BlockEvent.PlaceEvent event = new BlockEvent.PlaceEvent(snap, null, fakePlayer);
MinecraftForge.EVENT_BUS.post(event);
if (!event.isCanceled() && world.setBlockState(pos, newState, 3)) {
ItemBlock.setTileEntityNBT(world, fakePlayer, pos, toPlace);
newState.getBlock().onBlockPlacedBy(world, pos, newState, fakePlayer, toPlace);
if (newState.getBlock() == Blocks.SKULL) {
handleSkullPlacement(world, pos, toPlace, facing);
}
return newState;
}
}
return null;
}
/**
* Try to break the block at the given position. If the block has any drops, but no drops pass the filter, then the
* block will not be broken. Liquid, air & unbreakable blocks (bedrock etc.) will never be broken. Drops will be
* available via the DropResult object, organised by whether or not they passed the filter.
*
* @param world the world
* @param pos the block position
* @param filter filter for the block's drops
* @param silkTouch use silk touch when breaking the block
* @param fortune use fortune when breaking the block
* @return a drop result object
*/
public static BreakResult tryBreakBlock(World world, BlockPos pos, Filter filter, boolean silkTouch, int fortune) {
IBlockState state = world.getBlockState(pos);
Block block = state.getBlock();
if (block.isAir(state, world, pos) || state.getBlockHardness(world, pos) < 0 || block instanceof BlockLiquid) {
return BreakResult.NOT_BROKEN;
}
EntityPlayer fakePlayer = FakePlayer.getFakePlayer((WorldServer) world, pos).get();
List<ItemStack> allDrops = getDrops(world, pos, fakePlayer, silkTouch, fortune);
Map<Boolean, List<ItemStack>> groups = allDrops.stream().collect(Collectors.partitioningBy(filter));
if (allDrops.isEmpty() || !groups.get(true).isEmpty()) {
BlockEvent.BreakEvent breakEvent = new BlockEvent.BreakEvent(world, pos, state, fakePlayer);
MinecraftForge.EVENT_BUS.post(breakEvent);
if (!breakEvent.isCanceled()) {
world.setBlockToAir(pos);
return new BreakResult(true, groups);
}
}
return BreakResult.NOT_BROKEN;
}
private static List<ItemStack> getDrops(World world, BlockPos pos, EntityPlayer player, boolean silkTouch, int fortune) {
IBlockState state = world.getBlockState(pos);
Block block = state.getBlock();
if (silkTouch) {
Item item = Item.getItemFromBlock(block);
if (item == null) {
return Collections.emptyList();
} else {
return Lists.newArrayList(new ItemStack(item, 1, block.getMetaFromState(state)));
}
}
List<ItemStack> drops = block.getDrops(world, pos, state, fortune);
float dropChance = ForgeEventFactory.fireBlockHarvesting(drops, world, pos, state, fortune, 1.0F, false, player);
return drops.stream().filter(s -> world.rand.nextFloat() <= dropChance).collect(Collectors.toList());
}
public static String getBlockName(World w, BlockPos pos) {
if (w == null) {
return null;
}
IBlockState state = w.getBlockState(pos);
if (state.getBlock().isAir(state, w, pos)) {
return "";
} else {
ItemStack stack = state.getBlock().getItem(w, pos, state);
if (stack != null) {
return stack.getDisplayName();
} else {
return state.getBlock().getLocalizedName();
}
}
}
public static class BreakResult {
static final BreakResult NOT_BROKEN = new BreakResult(false, Collections.emptyMap());
private final boolean blockBroken;
private final Map<Boolean, List<ItemStack>> drops;
BreakResult(boolean blockBroken, Map<Boolean, List<ItemStack>> drops) {
this.blockBroken = blockBroken;
this.drops = drops;
}
public boolean isBlockBroken() {
return blockBroken;
}
List<ItemStack> getFilteredDrops(boolean passed) {
return drops.getOrDefault(passed, Collections.emptyList());
}
public void processDrops(World world, BlockPos pos, IItemHandler handler) {
for (ItemStack drop : getFilteredDrops(true)) {
ItemStack excess = handler.insertItem(0, drop, false);
if (excess != null) {
InventoryUtils.dropItems(world, pos, excess);
}
}
for (ItemStack drop : getFilteredDrops(false)) {
InventoryUtils.dropItems(world, pos, drop);
}
}
}
}
| true |
33e69123b8d9040e654c94bdb51879fa09631f26 | Java | JeeVeeVee/univ | /1steBachelor/OGPROG/Prog2-master/src/prog2/tracker/table/DoubleClickableTableRow.java | UTF-8 | 832 | 2.6875 | 3 | [] | no_license | package prog2.tracker.table;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.TableRow;
import javafx.scene.input.MouseEvent;
/**
* Table row waarop je kan dubbelklikken, bedoeld om in een table row cell factory gebruikt te
* worden.
*/
public class DoubleClickableTableRow<S> extends TableRow<S> implements EventHandler<MouseEvent> {
private EventHandler<ActionEvent> actionEventHandler;
public DoubleClickableTableRow(EventHandler<ActionEvent> actionEventHandler) {
this.actionEventHandler = actionEventHandler;
setOnMouseClicked(this);
}
@Override
public void handle(MouseEvent t) {
if (t.getClickCount() > 1) {
ActionEvent ae = new ActionEvent(this, null);
actionEventHandler.handle(ae);
}
}
}
| true |
66b7001fcf99a34749345e7bff84336e87784b90 | Java | cardSeller/cardSeller | /backoffice/src/main/java/com/card/seller/backoffice/service/GenerateService.java | UTF-8 | 1,407 | 2.0625 | 2 | [] | no_license | package com.card.seller.backoffice.service;
import com.card.seller.backoffice.constant.BoConstant;
import com.card.seller.domain.DateUtil;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.Date;
/**
* User: rojack.min
* Date: 14-3-5
* Time: 上午10:43
*/
@Service
public class GenerateService {
public ByteSource generateUserSalt() {
RandomNumberGenerator rng = new SecureRandomNumberGenerator();
ByteSource salt = rng.nextBytes();
return salt;
}
public String generatEncryptPassWord(String password, ByteSource salt) {
return new Sha256Hash(password, salt, BoConstant.HASH_INTERATIONS).toBase64();
}
// @Inject
// private OrdersDao ordersDao;
//
// @Transactional
// public String generateOrderNumber(Date date) {
// Long todayCount = ordersDao.countByDate(date);
// String dateStr = DateUtil.dateToString("yyyyMMdd", date);
// Long suffix = 1L;
// if (todayCount > 0) {
// suffix = todayCount + 1;
// }
// return "D" + dateStr + String.format("%04d", suffix);
// }
}
| true |
092ab16c8bb0e8fb1123cc3b64411379fdebd995 | Java | GoncaloBFM/DistributedImageServer | /project/src/sd/tp1/client/cloud/soap/AlbumWrapper.java | UTF-8 | 401 | 2.140625 | 2 | [] | no_license | package sd.tp1.client.cloud.soap;
import sd.tp1.Album;
import sd.tp1.client.cloud.soap.stubs.SharedAlbum;
/**
* Created by apontes on 3/25/16.
*/
class AlbumWrapper extends SharedAlbum implements Album {
AlbumWrapper(SharedAlbum album){
super();
super.name = album.getName();
}
AlbumWrapper(Album album){
super();
super.name = album.getName();
}
}
| true |
3963c90a2dcc31cc0cc7f4f8d7d633fe22a823b7 | Java | soyeon-gh/09_java_OOP_technology | /09_java_OOP_technology/src/step9_01/OOP_Theory/OOPEx10.java | UTF-8 | 1,750 | 4.0625 | 4 | [] | no_license | package step9_01.OOP_Theory;
/*
# 다형성
- 다형성이란 하나의 메소드가 서로 다른 클래스에서 다양하게 실행되는 것을 말한다.
- 다형성을 구현하기 위해서는 다형성을 구현할 메소드가 포함된 모든 클래스가 같은 부모 클래스를 가져야 한다.
- 부모 클래스와 자식 클래스에 같은 메소드가 있어야 하며 자식 클래스는 이 메소드를 반드시 override 시켜서 사용해야 한다.
- 부모 클래스 타입에 자식 클래스 타입을 대입시켜 다형성이 구현된 메소드를 실행한다.
*/
// 부모 클래스
class PolyShape {
void draw() {} // 자녀 클래스가 상속받아서 오버라이딩할 메서드를 정의
}
class PolyLine extends PolyShape {
void draw() { // 부모 클래스를 자신에 맞게 재정의 하여 사용
System.out.println("선을 그린다.");
}
}
class PolyCircle extends PolyShape {
void draw() { // 부모 클래스를 자신에 맞게 재정의 하여 사용
System.out.println("원을 그린다.");
}
}
class PolyRect extends PolyShape{
void draw() { // 부모 클래스를 자신에 맞게 재정의 하여 사용
System.out.println("사각형을 그린다.");
}
}
public class OOPEx10 {
public static void main(String[] args) {
PolyShape[] shapes = {
new PolyLine(),
new PolyRect(),
new PolyCircle()
};
shapes[0].draw(); // 자식클래스의 재정의 된 메서드가 호출
shapes[1].draw(); // 자식클래스의 재정의 된 메서드가 호출
shapes[2].draw(); // 자식클래스의 재정의 된 메서드가 호출
}
}
| true |
5c0482e26ebab42753d769037991c81dfe288c77 | Java | radovanbauer/eulerJava | /src/main/java/euler/Problem485.java | UTF-8 | 2,034 | 3.296875 | 3 | [] | no_license | package euler;
import java.util.ArrayDeque;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
public class Problem485 {
public static void main(String[] args) {
Stopwatch stopwatch = Stopwatch.createStarted();
System.out.println(new Problem485().solve());
System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
public long solve() {
int u = 100_000_000;
int k = 100_000;
Primes primes = new Primes(u);
ArrayDeque<Integer> divisorNumbers = new ArrayDeque<Integer>();
long sum = 0;
for (int n = 1; n <= u; n++) {
int added = primes.numberOfDivisors(n);
while (!divisorNumbers.isEmpty() && divisorNumbers.peekLast() < added) {
divisorNumbers.removeLast();
}
divisorNumbers.add(added);
if (n > k) {
int removed = primes.numberOfDivisors(n - k);
if (divisorNumbers.peekFirst() == removed) {
divisorNumbers.removeFirst();
}
}
if (n >= k) {
sum += divisorNumbers.peekFirst();
}
}
return sum;
}
private static class Primes {
private final int max;
private final boolean[] nonPrimes;
private final int[] smallestPrimeDivisor;
public Primes(int max) {
this.max = max;
nonPrimes = new boolean[max + 1];
smallestPrimeDivisor = new int[max + 1];
for (int i = 2; i <= max; i++) {
if (!nonPrimes[i]) {
smallestPrimeDivisor[i] = i;
long j = 1L * i * i;
while (j <= max) {
if (!nonPrimes[(int) j]) {
nonPrimes[(int) j] = true;
smallestPrimeDivisor[(int) j] = i;
}
j += i;
}
}
}
}
public int numberOfDivisors(int n) {
int res = 1;
while (n > 1) {
int prime = smallestPrimeDivisor[n];
int factor = 0;
while (n % prime == 0) {
n /= prime;
factor++;
}
res *= (factor + 1);
}
return res;
}
}
}
| true |
a8a26e0a087c0c2a2900e67c2c80506d7f42ccff | Java | tenbirds/OPENWORKS-3.0 | /src/main/java/zes/openworks/intra/poll/PollDomainVO.java | UTF-8 | 6,067 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2010 ZES Inc. All rights reserved.
* This software is the confidential and proprietary information of ZES Inc.
* You shall not disclose such Confidential Information and shall use it
* only in accordance with the terms of the license agreement you entered into
* with ZES Inc. (http://www.zesinc.co.kr/)
*/
package zes.openworks.intra.poll;
import java.util.List;
import zes.base.vo.PaggingVO;
/**
* 도메인 관리 VO
*
* @author : xanadu
* @version : 0.1, JDK 1.5 later, 2011. 3. 3.
* @since : OW 1.0
*/
public class PollDomainVO extends PaggingVO {
/** serialVersionUID */
private static final long serialVersionUID = -4766266534985367753L;
/** 도메인코드 */
private Integer domainCd;
/** 도메인명(FULL) */
private String domainNm;
/** 도메인 포트 */
private Integer portNo;
/** 도메인 그룹 IP */
private List<String> groupIpAddr;
/** 도메인 그룹 PORT */
private List<Integer> groupPortNo;
/** 도메인 설명 */
private String domainDesc;
/** 사용여부 */
private String useYn;
/** 등록자아이디 */
private String regId;
/** 등록자명 */
private String regNm;
/** 등록일 */
private String regDt;
/** 수정자 아이디 */
private String modId;
/** 수정자명 */
private String modNm;
/** 수정일시 */
private String modDt;
/**
* Integer domainCd을 반환
*
* @return Integer domainCd
*/
public Integer getDomainCd() {
return domainCd;
}
/**
* domainCd을 설정
*
* @param domainCd
* 을(를) Integer domainCd로 설정
*/
public void setDomainCd(Integer domainCd) {
this.domainCd = domainCd;
}
/**
* String domainNm을 반환
*
* @return String domainNm
*/
public String getDomainNm() {
return domainNm;
}
/**
* domainNm을 설정
*
* @param domainNm
* 을(를) String domainNm로 설정
*/
public void setDomainNm(String domainNm) {
this.domainNm = domainNm;
}
/**
* Integer portNo을 반환
*
* @return Integer portNo
*/
public Integer getPortNo() {
return portNo;
}
/**
* portNo을 설정
*
* @param portNo
* 을(를) Integer portNo로 설정
*/
public void setPortNo(Integer portNo) {
this.portNo = portNo;
}
/**
* List<String> groupIpAddr을 반환
*
* @return List<String> groupIpAddr
*/
public List<String> getGroupIpAddr() {
return groupIpAddr;
}
/**
* groupIpAddr을 설정
*
* @param groupIpAddr
* 을(를) List<String> groupIpAddr로 설정
*/
public void setGroupIpAddr(List<String> groupIpAddr) {
this.groupIpAddr = groupIpAddr;
}
/**
* List<Integer> groupPortNo을 반환
*
* @return List<Integer> groupPortNo
*/
public List<Integer> getGroupPortNo() {
return groupPortNo;
}
/**
* groupPortNo을 설정
*
* @param groupPortNo
* 을(를) List<Integer> groupPortNo로 설정
*/
public void setGroupPortNo(List<Integer> groupPortNo) {
this.groupPortNo = groupPortNo;
}
/**
* String domainDesc을 반환
*
* @return String domainDesc
*/
public String getDomainDesc() {
return domainDesc;
}
/**
* domainDesc을 설정
*
* @param domainDesc
* 을(를) String domainDesc로 설정
*/
public void setDomainDesc(String domainDesc) {
this.domainDesc = domainDesc;
}
/**
* String useYn을 반환
*
* @return String useYn
*/
public String getUseYn() {
return useYn;
}
/**
* useYn을 설정
*
* @param useYn
* 을(를) String useYn로 설정
*/
public void setUseYn(String useYn) {
this.useYn = useYn;
}
/**
* String regId을 반환
*
* @return String regId
*/
public String getRegId() {
return regId;
}
/**
* regId을 설정
*
* @param regId
* 을(를) String regId로 설정
*/
public void setRegId(String regId) {
this.regId = regId;
}
/**
* String regNm을 반환
*
* @return String regNm
*/
public String getRegNm() {
return regNm;
}
/**
* regNm을 설정
*
* @param regNm
* 을(를) String regNm로 설정
*/
public void setRegNm(String regNm) {
this.regNm = regNm;
}
/**
* String regDt을 반환
*
* @return String regDt
*/
public String getRegDt() {
return regDt;
}
/**
* regDt을 설정
*
* @param regDt
* 을(를) String regDt로 설정
*/
public void setRegDt(String regDt) {
this.regDt = regDt;
}
/**
* String modId을 반환
*
* @return String modId
*/
public String getModId() {
return modId;
}
/**
* modId을 설정
*
* @param modId
* 을(를) String modId로 설정
*/
public void setModId(String modId) {
this.modId = modId;
}
/**
* String modNm을 반환
*
* @return String modNm
*/
public String getModNm() {
return modNm;
}
/**
* modNm을 설정
*
* @param modNm
* 을(를) String modNm로 설정
*/
public void setModNm(String modNm) {
this.modNm = modNm;
}
/**
* String modDt을 반환
*
* @return String modDt
*/
public String getModDt() {
return modDt;
}
/**
* modDt을 설정
*
* @param modDt
* 을(를) String modDt로 설정
*/
public void setModDt(String modDt) {
this.modDt = modDt;
}
}
| true |
b41a9f944cf9a4d41073ec2aed6951ad2922d380 | Java | HenryP3/apirest | /repository/src/test/java/br/com/cddit/apirest/repository/common/DBCommandTransctionalExecutor.java | UTF-8 | 1,976 | 2.1875 | 2 | [] | no_license | package br.com.cddit.apirest.repository.common;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.junit.Ignore;
@Ignore
public class DBCommandTransctionalExecutor {
EntityManager em;
public DBCommandTransctionalExecutor(final EntityManager em) {
super();
this.em = em;
}
public <T> T executeCommand(final DBCommand<T> dbCommand) {
try {
em.getTransaction().begin();
final T toReturn = dbCommand.execute();
em.getTransaction().commit();
em.clear();
return toReturn;
} catch (final Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
throw e;
}
}
public <T> void executeCommandAndCheckViolations(final DBCommand<T> dbCommand,
final Map<String, String> constraintViolationsExpecteds) {
try {
em.getTransaction().begin();
dbCommand.execute();
em.getTransaction().commit();
em.clear();
fail("An error should have been thrown");
} catch (final Exception e) {
em.getTransaction().rollback();
assertThat(e, is(instanceOf(ConstraintViolationException.class)));
final ConstraintViolationException cve = (ConstraintViolationException) e;
final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations();
assertThat(constraintViolations.size(), is(equalTo(constraintViolationsExpecteds.size())));
constraintViolations.forEach(cv -> {
final String prop = cv.getPropertyPath().toString();
assertThat(constraintViolationsExpecteds, hasKey(prop));
assertThat(cv.getConstraintDescriptor().getMessageTemplate(),
is(equalTo(constraintViolationsExpecteds.get(prop))));
});
}
}
}
| true |
c8bc37fdeed85adbb3c63cf9b46e43b71bd05be3 | Java | freeroy/dw-frameworks-spring | /src/main/java/org/developerworld/frameworks/spring/orm/jpa/AbstractJpaGenericDaoImpl.java | UTF-8 | 2,825 | 2.3125 | 2 | [] | no_license | package org.developerworld.frameworks.spring.orm.jpa;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.developerworld.commons.dbutils.crud.GenericDao;
import org.developerworld.frameworks.spring.orm.jpa.support.DwJpaDaoSupport;
/**
* 针对JPA的持久层基础类
*
* @author Roy Huang
* @version 20130609
*
* @param <T>
* @param <PK>
*/
public abstract class AbstractJpaGenericDaoImpl<T, PK extends Serializable>
extends DwJpaDaoSupport implements GenericDao<T, PK> {
protected Class<T> entityClass;
public AbstractJpaGenericDaoImpl() {
Type type = getClass().getGenericSuperclass();
while(type!=null && !(type instanceof ParameterizedType))
type=type.getClass().getGenericSuperclass();
if (type!=null && type instanceof ParameterizedType) {
Type types[] = ((ParameterizedType) type).getActualTypeArguments();
if (types != null && types.length > 0 && types[0] instanceof Class)
entityClass = (Class<T>) types[0];
}
}
public Class<T> getEntityClass() {
return entityClass;
}
public String getEntityClassName() {
return getEntityClass().getName();
}
public void save(T entity) {
getDwJpaTemplate().persist(entity);
}
public void update(T entity) {
getDwJpaTemplate().merge(entity);
}
public void delete(T entity) {
getDwJpaTemplate().remove(entity);
}
public void delete(final PK id) {
delete(getDwJpaTemplate().getReference(entityClass, id));
}
public void delete(Collection<T> entitys) {
for (T entity : entitys)
delete(entity);
}
public void delete(PK[] ids) {
for (PK id : ids)
delete(id);
}
public long findCount() {
return getDwJpaTemplate().findLong(
"select count(*) from " + getEntityClassName());
}
public T findById(PK id) {
return findByPk(id);
}
public T findByPk(PK id) {
return getDwJpaTemplate().find(entityClass, id);
}
public List<T> findList() {
return getDwJpaTemplate().find("from " + getEntityClassName());
}
public List<T> findList(int pageNum, int pageSize) {
return getDwJpaTemplate().find("from " + getEntityClassName(),
(pageNum - 1) * pageSize, pageSize);
}
public List<T> findList(String order, int pageNum, int pageSize) {
String hql = "from " + getEntityClassName()
+ (StringUtils.isBlank(order) ? "" : " order by " + order);
return getDwJpaTemplate().find(hql, (pageNum - 1) * pageSize, pageSize);
}
public List<T> findList(String order) {
String hql = "from " + getEntityClassName()
+ (StringUtils.isBlank(order) ? "" : " order by " + order);
return getDwJpaTemplate().find(hql);
}
}
| true |
dbf05b5cbb9aa4147756eb23c2f7616cf50af6ab | Java | online-demo/netty-demo | /src/main/java/com/example/iodemo/c3/TimeServer.java | UTF-8 | 2,112 | 2.875 | 3 | [] | no_license | package com.example.iodemo.c3;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* @Author zhouguanya
* @Date 2018/9/7
* @Description netty时间服务器服务器端
*/
public class TimeServer {
public void bind(int port) {
//配置服务器端NIO线程组
//NioEventLoopGroup是个线程组,包含了一组NIO线程,处理网络事件,实际上就是Reactor线程组
try (EventLoopGroup bossLoopGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup()){
//netty用于启动NIO服务端的启动类,目的是降低NIO开发的复杂度
ServerBootstrap bootstrap = new ServerBootstrap();
//功能类似于NIO中的ServerSocketChannel
bootstrap.group(bossLoopGroup, workerGroup).channel(NioServerSocketChannel.class)
//配置NioServerSocketChannel的参数
.option(ChannelOption.SO_BACKLOG, 1024)
//绑定事件的处理类ChildChannelHandler
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new TimeServerHandler());
}
});
//绑定端口,同步等待绑定操作完成
ChannelFuture channelFuture = bootstrap.bind(port).sync();
//等待服务器监听端口关闭
channelFuture.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int port = 8888;
new TimeServer().bind(port);
}
}
| true |
dcdac0c23b52fe92948657d5929bed8abb2ff8b6 | Java | yazhenchua/AD_Kampung_Unite_Android | /app/src/main/java/com/example/ad_project_kampung_unite/entities/GroupPlan.java | UTF-8 | 4,306 | 2.078125 | 2 | [] | no_license | package com.example.ad_project_kampung_unite.entities;
import com.example.ad_project_kampung_unite.entities.enums.GroupPlanStatus;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.List;
public class GroupPlan implements Serializable {
private int id;
private String planName;
private String storeName;
private LocalDate shoppingDate;
private String pickupAddress;
private LocalDate pickupDate;
private GroupPlanStatus groupPlanStatus;
private CombinedPurchaseList combinedPurchaseList;
private List<AvailableTime> availableTimes;
private List<GroceryList> groceryLists;
private List<HitchRequest> groupPlan_hitchers;
public GroupPlan() {
}
public GroupPlan(String storeName, LocalDate shoppingDate, String pickupAddress, LocalDate pickupDate) {
this.storeName = storeName;
this.shoppingDate = shoppingDate;
this.pickupAddress = pickupAddress;
this.pickupDate = pickupDate;
}
public GroupPlan(int id, String planName, String storeName, LocalDate shoppingDate, String pickupAddress, LocalDate pickupDate, GroupPlanStatus groupPlanStatus, CombinedPurchaseList combinedPurchaseList, List<AvailableTime> availableTimes, List<GroceryList> groceryLists, List<HitchRequest> groupPlan_hitchers) {
this.id = id;
this.planName = planName;
this.storeName = storeName;
this.shoppingDate = shoppingDate;
this.pickupAddress = pickupAddress;
this.pickupDate = pickupDate;
this.groupPlanStatus = groupPlanStatus;
this.combinedPurchaseList = combinedPurchaseList;
this.availableTimes = availableTimes;
this.groceryLists = groceryLists;
this.groupPlan_hitchers = groupPlan_hitchers;
}
public String getPlanName() {
return planName;
}
public void setPlanName(String planName) {
this.planName = planName;
}
public int getId() {
return id;
}
public void setId(int id) {
id = id;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public LocalDate getShoppingDate() {
return shoppingDate;
}
public void setShoppingDate(LocalDate shoppingDate) {
this.shoppingDate = shoppingDate;
}
public String getPickupAddress() {
return pickupAddress;
}
public void setPickupAddress(String pickupAddress) {
this.pickupAddress = pickupAddress;
}
public LocalDate getPickupDate() {
return pickupDate;
}
public void setPickupDate(LocalDate pickupDate) {
this.pickupDate = pickupDate;
}
public GroupPlanStatus getGroupPlanStatus() {
return groupPlanStatus;
}
public void setGroupPlanStatus(GroupPlanStatus groupPlanStatus) {
this.groupPlanStatus = groupPlanStatus;
}
public CombinedPurchaseList getCombinedPurchaseList() {
return combinedPurchaseList;
}
public void setCombinedPurchaseList(CombinedPurchaseList combinedPurchaseList) {
this.combinedPurchaseList = combinedPurchaseList;
}
public List<AvailableTime> getAvailableTimes() {
return availableTimes;
}
public void setAvailableTimes(List<AvailableTime> availableTimes) {
this.availableTimes = availableTimes;
}
public List<GroceryList> getGroceryLists() {
return groceryLists;
}
public void setGroceryLists(List<GroceryList> groceryLists) {
this.groceryLists = groceryLists;
}
public List<HitchRequest> getGroupPlan_hitchers() {
return groupPlan_hitchers;
}
public void setGroupPlan_hitchers(List<HitchRequest> groupPlan_hitchers) {
this.groupPlan_hitchers = groupPlan_hitchers;
}
public GroupPlan(int id, String planName, String storeName, LocalDate shoppingDate, String pickupAddress, LocalDate pickupDate, GroupPlanStatus groupPlanStatus) {
this.id = id;
this.planName = planName;
this.storeName = storeName;
this.shoppingDate = shoppingDate;
this.pickupAddress = pickupAddress;
this.pickupDate = pickupDate;
this.groupPlanStatus = groupPlanStatus;
}
}
| true |
ab0807e0492681d6ebba323b6914bbff1a71f6d6 | Java | syafiqabdillah/TA_6_6 | /src/main/java/com/apap/farmasi/controller/PageController.java | UTF-8 | 4,118 | 2.296875 | 2 | [] | no_license | package com.apap.farmasi.controller;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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.client.RestTemplate;
import com.apap.farmasi.model.DetailMedicalSuppliesLabModel;
import com.apap.farmasi.model.MedicalSuppliesModel;
import com.apap.farmasi.model.PerencanaanModel;
import com.apap.farmasi.service.MedicalSuppliesService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
public class PageController {
@Autowired
MedicalSuppliesService medsupService;
@RequestMapping(value ="/", method = RequestMethod.GET)
public String home(Model model) throws IOException {
List<MedicalSuppliesModel> listMedicalSupplies = new ArrayList<>();
PerencanaanModel perencanaan = new PerencanaanModel();
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String formattedDate=dateFormat.format(date);
perencanaan.setTanggal(date);
if (minggu1Atau3()) {
System.out.println("ini minggu 1 atau 3");
}
if (minggu1Atau3()) {
//kalo minggu 1 atau 3, bebas
listMedicalSupplies = medsupService.getAll();
} else {
//kalo gak minggu 1 atau 3, cuma yang urgent
List<MedicalSuppliesModel> allMedsup = medsupService.getAll();
for (MedicalSuppliesModel medsup : allMedsup) {
//cuma masukin yang urgent
if (medsup.getJenisMedicalSupplies().getUrgent().getId() == 1) {
listMedicalSupplies.add(medsup);
} else {
System.out.println(medsup.getNama() + " tidak dimasukkan ke pilihan karena tidak urgent ");
}
}
}
List<DetailMedicalSuppliesLabModel> medsupLab = getDataFromLab();
model.addAttribute("medsupLab", medsupLab);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String authority = authentication.getAuthorities().iterator().next().getAuthority();
model.addAttribute("mingguKe", mingguKe());
model.addAttribute("authority", authority);
model.addAttribute("perencanaan", perencanaan);
model.addAttribute("listMedicalSupplies", listMedicalSupplies);
return "home";
}
int mingguKe() {
Calendar calendar = Calendar.getInstance();
return calendar.get(Calendar.WEEK_OF_MONTH);
}
boolean minggu1Atau3() {
Calendar calendar = Calendar.getInstance();
int minggu = calendar.get(Calendar.WEEK_OF_MONTH);
System.out.println("ini minggu ke-" + minggu);
return (minggu==1) || (minggu==3);
}
List<DetailMedicalSuppliesLabModel> getDataFromLab() throws IOException{
//rest template
RestTemplate restTemplate = new RestTemplate();
//membuat Object mapper
ObjectMapper mapper = new ObjectMapper();
//path
String path = "https://ta-apap-6-8.herokuapp.com/api/lab/kebutuhan/perencanaan";
//json
String jsonLab = restTemplate.getForObject(path, String.class);
JsonNode jsonNodeLab = mapper.readTree(jsonLab);
//mengambil list result
String result = jsonNodeLab.get("result").toString();
System.out.println("result = " + result);
//merubah string of map of Json menjad map of MedsupLab
List<DetailMedicalSuppliesLabModel> medsup = mapper.readValue(result, new TypeReference<ArrayList<DetailMedicalSuppliesLabModel>>(){});
//list
//test
for (DetailMedicalSuppliesLabModel med : medsup) {
System.out.println(med.getNama() + "-" + med.getJumlah());
}
return medsup;
}
@RequestMapping("/login")
public String login() {
return "login";
}
} | true |
fa3e19a737629f652309a80582ba3e8319407477 | Java | quteron/leetcode-problems | /easy/859.buddy-strings.java | UTF-8 | 802 | 3.125 | 3 | [] | no_license | public boolean buddyStrings(String a, String b) {
if (a.length() != b.length()) {
return false;
}
if (a.equals(b)) {
int maxFreq = 0;
int[] count = new int[26];
for (char ch : a.toCharArray()) {
count[ch - 'a']++;
maxFreq = Math.max(maxFreq, count[ch - 'a']);
}
return maxFreq > 1;
}
int first = -1, second = -1;
for (int i=0; i<a.length(); i++) {
if (a.charAt(i) != b.charAt(i)) {
if (first == -1) {
first = i;
} else if (second == -1) {
second = i;
} else {
return false;
}
}
}
return second != -1 && a.charAt(first) == b.charAt(second) && a.charAt(second) == b.charAt(first);
}
| true |
983ba7a32fc509439c55873e356bb8001275f3a8 | Java | sudhachinna/eclipse-workspace | /JavaTraining/src/in/vamsoft/training/employee/Listdemo.java | UTF-8 | 868 | 3.65625 | 4 | [] | no_license | package in.vamsoft.training.employee;
import java.util.*;
/*
* @this is the list sort program in collection.
* @using sort,reverse,fill,position.
*/
public class Listdemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(22);
list.add(10);
list.add(30);
list.add(40);
list.add(2, 88);
Collections.sort(list);
System.out.println("Sorting a list:" + list);
Collections.reverse(list);
System.out.println("Reversing Number:" + list);
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
Collections.fill(list, 1);
System.out.println("Fill the numbers:"+list);
Collections.sort(list);
int position = Collections.binarySearch(list, 30);
System.out.println("Position of number:"+position);
}
}
| true |
a85acca46fa54c80d0644fb070a6709ffcfe31e3 | Java | eyalkoren/apm-agent-java | /apm-agent-core/src/main/java/co/elastic/apm/bci/bytebuddy/ClassLoaderNameMatcher.java | UTF-8 | 1,397 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | /*-
* #%L
* Elastic APM Java agent
* %%
* Copyright (C) 2018 Elastic and contributors
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package co.elastic.apm.bci.bytebuddy;
import net.bytebuddy.matcher.ElementMatcher;
public class ClassLoaderNameMatcher extends ElementMatcher.Junction.AbstractBase<ClassLoader> {
private final String name;
private ClassLoaderNameMatcher(String name) {
this.name = name;
}
public static ElementMatcher.Junction.AbstractBase<ClassLoader> classLoaderWithName(String name) {
return new ClassLoaderNameMatcher(name);
}
public static ElementMatcher.Junction.AbstractBase<ClassLoader> isReflectionClassLoader() {
return new ClassLoaderNameMatcher("sun.reflect.DelegatingClassLoader");
}
@Override
public boolean matches(ClassLoader target) {
return target != null && name.equals(target.getClass().getName());
}
}
| true |
8753f3cc68098b20d0b640247c7669c38652cd46 | Java | dualapp/appowner | /AppOwnner/src/com/appowner/model/cls_Group.java | UTF-8 | 2,839 | 1.789063 | 2 | [] | no_license | package com.appowner.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "tb_group")
public class cls_Group implements Serializable
{
/**
* mukesh
*/
private static final long serialVersionUID = -723583058586873479L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column
private Integer int_GroupId;
public Integer getInt_GroupId() {
return int_GroupId;
}
public void setInt_GroupId(Integer int_GroupId) {
this.int_GroupId = int_GroupId;
}
@Column
private String str_GroupNm;
@Column
private String str_Groupaddress;
@Column
private String str_groupPrivate;
@Column
private String str_GroupDescription;
@Column
private char isCh_EmailAllow;
@Column
private int int_ApartmentID;
@Column
private Integer userId;
@Column
private Boolean bol_Smsallow;
@Column
private Boolean bol_Emailallow;
@Column
private int int_Nomember;
public int getInt_Nomember() {
return int_Nomember;
}
public void setInt_Nomember(int int_Nomember) {
this.int_Nomember = int_Nomember;
}
public Boolean getBol_Smsallow() {
return bol_Smsallow;
}
public Boolean getBol_Emailallow() {
return bol_Emailallow;
}
public void setBol_Smsallow(Boolean bol_Smsallow) {
this.bol_Smsallow = bol_Smsallow;
}
public void setBol_Emailallow(Boolean bol_Emailallow) {
this.bol_Emailallow = bol_Emailallow;
}
public String getStr_GroupNm() {
return str_GroupNm;
}
public void setStr_GroupNm(String str_GroupNm) {
this.str_GroupNm = str_GroupNm;
}
public String getStr_Groupaddress() {
return str_Groupaddress;
}
public void setStr_Groupaddress(String str_Groupaddress) {
this.str_Groupaddress = str_Groupaddress;
}
public String getStr_groupPrivate() {
return str_groupPrivate;
}
public void setStr_groupPrivate(String str_groupPrivate) {
this.str_groupPrivate = str_groupPrivate;
}
public char getIsCh_EmailAllow() {
return isCh_EmailAllow;
}
public void setIsCh_EmailAllow(char isCh_EmailAllow) {
this.isCh_EmailAllow = isCh_EmailAllow;
}
public String getStr_GroupDescription() {
return str_GroupDescription;
}
public void setStr_GroupDescription(String str_GroupDescription) {
this.str_GroupDescription = str_GroupDescription;
}
public int getInt_ApartmentID() {
return int_ApartmentID;
}
public void setInt_ApartmentID(int int_ApartmentID) {
this.int_ApartmentID = int_ApartmentID;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
}
| true |
a1704bd4a8a72b6c34e7ce2b7575acd5506ae3c7 | Java | eclipse-ee4j/metro-wsit | /wsit/ws-rx/wsmc-impl/src/main/java/com/sun/xml/ws/rx/mc/runtime/ResponseStorage.java | UTF-8 | 11,291 | 1.804688 | 2 | [
"BSD-3-Clause",
"EPL-2.0",
"LicenseRef-scancode-generic-export-compliance",
"GPL-2.0-only",
"Classpath-exception-2.0"
] | permissive | /*
* Copyright (c) 2010, 2022 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.rx.mc.runtime;
import com.sun.istack.NotNull;
import com.sun.istack.logging.Logger;
import com.sun.xml.ws.api.ha.HaInfo;
import com.sun.xml.ws.api.ha.HighAvailabilityProvider;
import com.sun.xml.ws.commons.ha.HaContext;
import com.sun.xml.ws.commons.ha.StickyKey;
import com.sun.xml.ws.rx.ha.HighlyAvailableMap;
import com.sun.xml.ws.rx.ha.HighlyAvailableMap.StickyReplicationManager;
import com.sun.xml.ws.rx.ha.ReplicationManager;
import com.sun.xml.ws.rx.mc.localization.LocalizationMessages;
import com.sun.xml.ws.rx.message.jaxws.JaxwsMessage;
import com.sun.xml.ws.rx.message.jaxws.JaxwsMessage.JaxwsMessageState;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import org.glassfish.ha.store.api.BackingStore;
import org.glassfish.ha.store.api.BackingStoreFactory;
final class ResponseStorage {
private static final Logger LOGGER = Logger.getLogger(ResponseStorage.class);
private static final class PendingMessageDataReplicationManager implements ReplicationManager<String, JaxwsMessage> {
private final BackingStore<StickyKey, JaxwsMessageState> messageStateStore;
private final String loggerProlog;
public PendingMessageDataReplicationManager(final String endpointUid) {
this.messageStateStore = HighAvailabilityProvider.INSTANCE.createBackingStore(
HighAvailabilityProvider.INSTANCE.getBackingStoreFactory(HighAvailabilityProvider.StoreType.IN_MEMORY),
endpointUid + "_MC_PENDING_MESSAGE_DATA_STORE",
StickyKey.class,
JaxwsMessageState.class);
this.loggerProlog = "[MC message data manager endpointUid: " + endpointUid + "]: ";
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Created pending message backing store");
}
}
@Override
public JaxwsMessage load(final String key) {
final JaxwsMessageState state = HighAvailabilityProvider.loadFrom(messageStateStore, new StickyKey(key), null);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Message state loaded from pending message backing store for key [" + key + "]: " + ((state == null) ? null : state.toString()));
}
final JaxwsMessage message = (state == null) ? null : state.toMessage();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Message state converted to a pending message: " + ((message == null) ? null : message.toString()));
}
return message;
}
@Override
public void save(final String key, final JaxwsMessage value, final boolean isNew) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Sending for replication pending message with a key [" + key + "]: " + value.toString() + ", isNew=" + isNew);
}
JaxwsMessageState state = value.getState();
HaInfo haInfo = HaContext.currentHaInfo();
if (haInfo != null) {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Existing HaInfo found, using it for pending message state replication: " + HaContext.asString(haInfo));
}
HaContext.udpateReplicaInstance(HighAvailabilityProvider.saveTo(messageStateStore, new StickyKey(key, haInfo.getKey()), state, isNew));
} else {
final StickyKey stickyKey = new StickyKey(key);
final String replicaId = HighAvailabilityProvider.saveTo(messageStateStore, stickyKey, state, isNew);
haInfo = new HaInfo(stickyKey.getHashKey(), replicaId, false);
HaContext.updateHaInfo(haInfo);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "No HaInfo found, created new after pending message state replication: " + HaContext.asString(haInfo));
}
}
}
@Override
public void remove(String key) {
HighAvailabilityProvider.removeFrom(messageStateStore, new StickyKey(key));
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Removed pending message from the backing store for key [" + key + "]");
}
}
@Override
public void close() {
HighAvailabilityProvider.close(messageStateStore);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Closed pending message backing store");
}
}
@Override
public void destroy() {
HighAvailabilityProvider.destroy(messageStateStore);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer(loggerProlog + "Destroyed pending message backing store");
}
}
}
//
private final ReentrantReadWriteLock storageLock = new ReentrantReadWriteLock();
//
private final HighlyAvailableMap<String, JaxwsMessage> pendingResponses;
private final HighlyAvailableMap<String, PendingResponseIdentifiers> pendingResponseIdentifiers;
private final String endpointUid;
//
public ResponseStorage(final String endpointUid) {
StickyReplicationManager<String, PendingResponseIdentifiers> responseIdentifiersManager = null;
PendingMessageDataReplicationManager responseManager = null;
if (HighAvailabilityProvider.INSTANCE.isHaEnvironmentConfigured()) {
final BackingStoreFactory bsf = HighAvailabilityProvider.INSTANCE.getBackingStoreFactory(HighAvailabilityProvider.StoreType.IN_MEMORY);
responseIdentifiersManager = new StickyReplicationManager<>(
endpointUid + "_MC_PENDING_MESSAGE_IDENTIFIERS_MAP_MANAGER",
HighAvailabilityProvider.INSTANCE.createBackingStore(
bsf,
endpointUid + "_MC_PENDING_MESSAGE_IDENTIFIERS_STORE",
StickyKey.class,
PendingResponseIdentifiers.class));
responseManager = new PendingMessageDataReplicationManager(endpointUid);
}
this.pendingResponseIdentifiers = HighlyAvailableMap.create(endpointUid + "_MC_PENDING_MESSAGE_IDENTIFIERS_MAP", responseIdentifiersManager);
this.pendingResponses = HighlyAvailableMap.create(endpointUid + "_MC_PENDING_MESSAGE_DATA_MAP", responseManager);
this.endpointUid = endpointUid;
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Response storage initialized");
}
}
void store(@NotNull JaxwsMessage response, @NotNull final String clientUID) {
try {
storageLock.writeLock().lock();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Storing new response for client UID: " + clientUID);
}
pendingResponses.put(response.getCorrelationId(), response);
PendingResponseIdentifiers clientResponses = pendingResponseIdentifiers.get(clientUID);
if (clientResponses == null) {
clientResponses = new PendingResponseIdentifiers();
}
if (!clientResponses.offer(response.getCorrelationId())) {
LOGGER.severe(LocalizationMessages.WSMC_0104_ERROR_STORING_RESPONSE(clientUID));
}
pendingResponseIdentifiers.put(clientUID, clientResponses);
} finally {
storageLock.writeLock().unlock();
}
}
public JaxwsMessage getPendingResponse(@NotNull final String clientUID) {
try {
storageLock.writeLock().lock();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Retrieving stored pending response for client UID: " + clientUID);
}
PendingResponseIdentifiers clientResponses = pendingResponseIdentifiers.get(clientUID);
if (clientResponses != null && !clientResponses.isEmpty()) {
String messageId = clientResponses.poll();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Found registered pending response with message id [" + messageId + "] for client UID: " + clientUID);
}
pendingResponseIdentifiers.put(clientUID, clientResponses);
final JaxwsMessage response = pendingResponses.remove(messageId);
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Retrieved and removed pending response message data for message id [" + messageId + "]: " + ((response == null) ? null : response.toString()));
}
if (response == null) {
LOGGER.warning("[WSMC-HA] endpoint UID [" + endpointUid + "]: No penidng response message data found for message id [" + messageId + "]");
}
return response;
}
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: No pedning responses found for client UID: " + clientUID);
}
return null;
} finally {
storageLock.writeLock().unlock();
}
}
public boolean hasPendingResponse(@NotNull String clientUID) {
try {
storageLock.readLock().lock();
PendingResponseIdentifiers clientResponses = pendingResponseIdentifiers.get(clientUID);
final boolean result = clientResponses != null && !clientResponses.isEmpty();
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Pending responses avaliable for client UID [" + clientUID + "]: " + result);
}
return result;
} finally {
storageLock.readLock().unlock();
}
}
void invalidateLocalCache() {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Invalidation local caches for the response storage");
}
pendingResponseIdentifiers.invalidateCache();
pendingResponses.invalidateCache();
}
void dispose() {
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.finer("[WSMC-HA] endpoint UID [" + endpointUid + "]: Disposing the response storage");
}
pendingResponseIdentifiers.close();
pendingResponseIdentifiers.destroy();
pendingResponses.close();
pendingResponses.destroy();
}
}
| true |
e8f2e13ea797a823f778732300625122dc1f9bb0 | Java | lvshuiyiqing/atComment | /cloned-randoop/src/randoop/experimental/AbstractSimplifier.java | UTF-8 | 7,095 | 2.984375 | 3 | [
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | package randoop.experimental;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import randoop.Check;
import randoop.ExecutableSequence;
import randoop.MultiVisitor;
import randoop.Sequence;
/**
* An abstract class encapsulating common fields and utility functions in
* simplifying the sequence.
* */
public abstract class AbstractSimplifier {
/**
* The sequence to simplify
* */
public final Sequence sequenceToSimplify;
/**
* The executable sequence keeps the runtime information of <code>sequenceToSimplify</code>
* */
public final ExecutableSequence eSeq;
/**
* The runtime execution visitor to reproduce the failure
* */
public final MultiVisitor visitor;
/**
* A list of removed indices in the <code>sequenceToSimplify</code> after performing
* the simplification task
* */
public final List<Integer> removed_indices;
public AbstractSimplifier(Sequence sequence, MultiVisitor visitor) {
assert sequence != null : "The input sequence should not be null.";
assert visitor != null : "The visitor can not be null.";
this.sequenceToSimplify = sequence;
this.visitor = visitor;
this.eSeq = this.execute_sequence(this.sequenceToSimplify, this.visitor);
//the sequence should not have non-executed sequence
assert this.eSeq.hasFailure() : "The input sequence should fail!";
assert !this.eSeq.hasNonExecutedStatements() :
"The sequence should not have non-executed statement.";
this.removed_indices = new LinkedList<Integer>();
}
abstract public ExecutableSequence simplfy_sequence();
/**
* Returns a list of removed indices from the original sequence after simplification
* */
protected List<Integer> getRemovedIndices() {
return this.removed_indices;
}
/**
* Executes a sequence with the given visitor, returns an executable sequence with runtime information
* */
protected ExecutableSequence execute_sequence(Sequence sequenceToSimplify, MultiVisitor visitor) {
ExecutableSequence eseq = new ExecutableSequence(sequenceToSimplify);
eseq.execute(visitor);
return eseq;
}
/**
* Returns a list of indices in the original sequence from a list of indices in the
* simplified sequence
* */
protected List<Integer> compute_indices_in_original_sequence(Sequence simplifiedSequence,
List<Integer> removed_indices, List<Integer> indices_in_simplified) {
List<Integer> indices_in_original_sequence = new LinkedList<Integer>();
for(Integer index_in_simplified : indices_in_simplified) {
Integer original_index = this.compute_index_in_original_sequence(simplifiedSequence,
removed_indices, index_in_simplified);
indices_in_original_sequence.add(original_index);
}
return indices_in_original_sequence;
}
/**
* Returns the index (of original sequence) in the simplified sequence
* For example, the original sequence is: [0, 1, 2, 3, 4, 5], and the removed indices are: [2, 5]
* So that, the simplified sequence has a length of 4. The index "3" in the simplified
* sequence is actually 4 in the original sequence.
* */
protected int compute_index_in_simplified_sequence(Sequence simplifiedSequence,
List<Integer> removed_indices, Integer indexInOrigSequence) {
assert indexInOrigSequence >= 0 && indexInOrigSequence < this.eSeq.sequence.size() :
"The index in orig sequence: " + indexInOrigSequence + " is not legal!";
assert removed_indices.size() + simplifiedSequence.size() == this.eSeq.sequence.size() :
"The sequence size is not correct, removed index num: " + removed_indices.size()
+ ", simplifiedSequence size: " + simplifiedSequence.size() + ", orig sequence size: "
+ this.eSeq.sequence.size();
assert !removed_indices.contains(indexInOrigSequence) : "The removed_indices can not contains queried" +
" index: " + indexInOrigSequence;
//the index for return in simplified sequence
int index_in_simplified = -1;
for(int i = 0; i < this.eSeq.sequence.size(); i++) {
if(removed_indices.contains(i)) {
continue;
}
index_in_simplified++;
if( i == indexInOrigSequence) {
break;
}
}
//check the correctness of result
assert index_in_simplified >= 0 && index_in_simplified < simplifiedSequence.size() :
"The index is illegal: " + index_in_simplified + ", the size of sequence: " + simplifiedSequence.size()
+ ", indexInOriginalSequence: " + indexInOrigSequence + ", the removed index: " + removed_indices;
return index_in_simplified;
}
/**
* Returns the index in the original sequence before simplification.
* For example, the original sequence is [0, 1, 2, 3, 4, 5]. The removed_indices is [2, 4]
* So, that an index 2 in the simplified sequence, is actually 3 in the original sequence.
* Invariants: the length of simplified sequence + the length of removed_indices == the length of original sequence
* */
protected int compute_index_in_original_sequence(Sequence simplifiedSequence,
List<Integer> removed_indices, Integer indexInSimplifiedSequence) {
assert indexInSimplifiedSequence < simplifiedSequence.size() : "The given index: " + indexInSimplifiedSequence
+ ", is not valid, the total length of simplified: " + simplifiedSequence.size();
assert simplifiedSequence.size() + removed_indices.size() == this.sequenceToSimplify.size() :
"Error in size, simpilified sequence size: " + simplifiedSequence.size() + ", removed index size: " + removed_indices.size()
+ ", original sequence size: " + this.sequenceToSimplify.size();
//sort it
Collections.sort(removed_indices);
//traverse the original un-simplified sequence
int countInSimplified = -1;
for(int i = 0; i < this.sequenceToSimplify.size(); i++) {
if(removed_indices.contains(i)) {
continue;
} else {
countInSimplified++;
if(countInSimplified == indexInSimplifiedSequence) {
return i;
}
}
}
System.out.println("total length of original: " + this.sequenceToSimplify.size());
System.out.println("removed_indices: " + removed_indices);
System.out.println("Count in simplified: " + countInSimplified);
System.out.println("indexInSimplifiedSequence: " + indexInSimplifiedSequence);
throw new Error("The execution should never be here. A bug in code, please report!");
}
/**
* Returns the failure index of the sequence before simplification
* */
protected int getFailureIndex() {
return eSeq.getFailureIndex();
}
/**
* Returns the failure checks of the sequence before simplification
* */
protected List<Check> getFailureChecks() {
List<Check> checklist = new LinkedList<Check>();
int failure_index = this.getFailureIndex();
if(failure_index != -1) {
checklist.addAll(this.eSeq.getFailures(failure_index));
}
return checklist;
}
/**
* Compares if the same failures occur
* */
protected boolean compareFailureChecks(List<Check> failure_in_original, List<Check> failure_in_simplified) {
return true;
}
}
| true |
180b2c848804d869f1d354b5784f4a0181bb9b84 | Java | neilcpaul/AIGridTanks | /Player/Player.java | UTF-8 | 1,932 | 3.203125 | 3 | [] | no_license | package Player;
import Core.GameLoader;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Neil
* Date: 12/11/12
* Time: 03:32
* To change this template use File | Settings | File Templates.
*/
public class Player {
private int playerNumber;
private String playerName;
private int playerColour;
private static ArrayList<Unit> playerUnits;
public Player(int playerNumber, String playerName)
{
this.playerNumber = playerNumber;
this.playerName = playerName;
playerUnits = new ArrayList<Unit>();
this.initUnits();
}
public void initUnits() {
for (int i = 0 ; i < GameLoader.getPlayerUnits() ; i++)
playerUnits.add(new Unit());
}
public ArrayList<Unit> getPlayerUnits()
{
return playerUnits;
}
public int getPlayerColour() {
return playerColour;
}
public void setPlayerColour(int playerColour) {
this.playerColour = playerColour;
}
public int getPlayerNumber() {
return playerNumber;
}
public String getPlayerName() {
return playerName;
}
public int getTotalHealth() {
int totalHealth = 0;
for (int i=0 ; i < playerUnits.size() ; i++)
{
totalHealth += playerUnits.get(i).getHealth();
}
return totalHealth;
}
public void unitDestroyed(Unit unit)
{
playerUnits.remove(unit);
}
public int getUnitsRemaining() {
return playerUnits.size();
}
public String toString()
{
String unitsList = "";
for (int i=0 ; i<getUnitsRemaining() ; i++)
{
unitsList = unitsList + (i+1) + " - " + playerUnits.get(i).toString();
}
return getPlayerNumber() + " " + getPlayerName() + "\nTotal Health: " + getTotalHealth() + "\nUnits Remaining: " + getUnitsRemaining() + "\n" + unitsList;
}
}
| true |
0c987f7f0a02e7747dd474fc9a460155ddd4b910 | Java | ramondcosta/twu-biblioteca-ramon-dias-costa | /src/com/twu/biblioteca/subMenus/CatalogMenu.java | UTF-8 | 210 | 1.609375 | 2 | [
"Apache-2.0"
] | permissive | package com.twu.biblioteca.subMenus;
import com.twu.biblioteca.Catalog;
import com.twu.biblioteca.SubMenu;
public class CatalogMenu {
public CatalogMenu(String description, Catalog catalog) {
}
}
| true |
6f35297bc2c70a54694f525195626e3eea5d7654 | Java | sergeysenja1992/NameCaseLib | /src/main/java/namecaselib/NCL.java | UTF-8 | 2,829 | 3.140625 | 3 | [
"MIT"
] | permissive | package namecaselib;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Класс, который содержит основные константы библиотеки:
* - индексы мужского и женского пола
* - индексы всех падежей
*/
public class NCL {
public enum Gender {
MAN, WOMAN
}
/*
* - <b>N</b> - ім’я
* - <b>S</b> - прізвище
* - <b>F</b> - по-батькові
*/
enum NamePart {
N, F, S
}
/**
* Именительный падеж
*
*/
public static final int IMENITLN = 0;
/**
* Родительный падеж
*
*/
public static final int RODITLN = 1;
/**
* Дательный падеж
*
*/
public static final int DATELN = 2;
/**
* Винительный падеж
*
*/
public static final int VINITELN = 3;
/**
* Творительный падеж
*
*/
public static final int TVORITELN = 4;
/**
* Предложный падеж
*
*/
public static final int PREDLOGN = 5;
/**
* Назвиний відмінок
*
*/
public static final int UaNazyvnyi = 0;
/**
* Родовий відмінок
*
*/
public static final int UaRodovyi = 1;
/**
* Давальний відмінок
*
*/
public static final int UaDavalnyi = 2;
/**
* Знахідний відмінок
*
*/
public static final int UaZnahidnyi = 3;
/**
* Орудний відмінок
*
*/
public static final int UaOrudnyi = 4;
/**
* Місцевий відмінок
*
*/
public static final int UaMiszevyi = 5;
/**
* Кличний відмінок
*
*/
public static final int UaKlychnyi = 6;
public static String substring(String str, int start, int length) {
if (start >= 0) {
return str.substring(start, start + length);
} else {
start = str.length() + start;
return str.substring(start, start + length);
}
}
public static boolean isNotEmpty(String str) {
return str != null && !str.isEmpty();
}
public static boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
public static <T> List<T> array(T... t) {
return new ArrayList<>(Arrays.asList(t));
}
public static <T> List<T> array_fill(int count, T value) {
List<T> list = new ArrayList<>();
for (int i = 0; i < count; i++) {
list.add(value);
}
return list;
}
} | true |
2a016fd22bf386337732db4f113052f3f0ce3abe | Java | TangGSen/SCuckoo-masterV2 | /appV1/src/main/java/com/ourcompany/activity/imui/SearchActivity.java | UTF-8 | 4,886 | 2.125 | 2 | [] | no_license | package com.ourcompany.activity.imui;
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.EditText;
import android.widget.TextView;
import com.mob.ums.User;
import com.ourcompany.R;
import com.ourcompany.app.MApplication;
import com.ourcompany.presenter.activity.SearchActPresenter;
import com.ourcompany.utils.Constant;
import com.ourcompany.utils.ToastUtils;
import com.ourcompany.view.activity.SearchActvityView;
import com.ourcompany.widget.recycleview.commadapter.OnItemOnclickLinstener;
import com.ourcompany.widget.recycleview.commadapter.RecycleCommonAdapter;
import com.ourcompany.widget.recycleview.commadapter.SViewHolder;
import com.ourcompany.widget.recycleview.commadapter.SimpleDecoration;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import company.com.commons.framework.view.impl.MvpActivity;
/**
* Author : 唐家森
* Version: 1.0
* On : 2018/2/4 21:26
* Des : 使用Rxjava 来友好搜索
*/
public class SearchActivity extends MvpActivity<SearchActvityView, SearchActPresenter> implements SearchActvityView {
@BindView(R.id.etSearch)
EditText etSearch;
@BindView(R.id.btCancle)
TextView btCancle;
@BindView(R.id.recycleview)
RecyclerView recycleview;
private List<User> mUsers = new ArrayList<>();
private RecycleCommonAdapter<User> recycleCommonAdapter;
@Override
public void showToastMsg(String string) {
ToastUtils.showSimpleToast(string);
}
@Override
public void loading() {
}
@Override
public void loaded() {
}
@Override
public void showSearchRes(ArrayList<User> users) {
if (users != null) {
mUsers.clear();
mUsers.addAll(users);
recycleCommonAdapter.notifyDataSetChanged();
}
}
@Override
public void showError(String message) {
showToastMsg(message);
}
@Override
protected int getLayoutId() {
return R.layout.acticvity_layout_search;
}
@Override
protected SearchActvityView bindView() {
return this;
}
@Override
protected SearchActPresenter bindPresenter() {
return new SearchActPresenter(MApplication.mContext);
}
@Override
protected void initView() {
super.initView();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MApplication.mContext);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycleview.setLayoutManager(linearLayoutManager);
recycleview.setHasFixedSize(true);
recycleview.addItemDecoration(new SimpleDecoration(MApplication.mContext, R.drawable.recycle_line_divider, 1));
recycleCommonAdapter = new RecycleCommonAdapter<User>(
MApplication.mContext, mUsers, R.layout.layout_search_user_item) {
@Override
public void bindItemData(SViewHolder holder, User itemData, int position) {
holder.setText(R.id.tvName, itemData.nickname.get());
}
};
recycleCommonAdapter.setOnItemClickLinstener(new OnItemOnclickLinstener() {
@Override
public void itemOnclickLinstener(int position) {
if (mUsers != null && mUsers.size() >= position) {
Constant.CURRENT_ITEM_USER = mUsers.get(position);
UserInfoActivity.gotoThis(SearchActivity.this,true,Constant.CURRENT_ITEM_USER.id.get());
}
}
});
recycleview.setAdapter(recycleCommonAdapter);
}
@Override
protected void initData(Bundle savedInstanceState) {
super.initData(savedInstanceState);
//先初始化RxJava
getPresenter().initPublishSubject();
etSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
//搜索结果
getPresenter().afterTextChanged(s.toString());
}
});
}
@OnClick({R.id.etSearch, R.id.btCancle})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.etSearch:
break;
case R.id.btCancle:
finish();
break;
}
}
@Override
protected void onDestroy() {
getPresenter().onDestroy();
super.onDestroy();
}
}
| true |
20e4df4cfb55f7d8d488a7abb8b98a38c97bde4e | Java | lcsuarezl/examples | /src/com/java/examples/access/library/Book.java | UTF-8 | 486 | 2.828125 | 3 | [] | no_license | package com.java.examples.access.library;
public class Book {
//public access
public String isbn;
//protected access
protected String author;
//default ~ package
int issues;
//private
private int pages;
public void printBook(){
System.out.println("printBook()");
}
protected void modifyTemplate(){
System.out.println("modifyTemplate()!");
}
void solved(){
System.out.println("solved()!");
}
private void count(){
System.out.println("count()!");
}
}
| true |
96f408a344b8450df8bba2ea8abda96d020dc931 | Java | zqq234/test | /XiaoYi.java | UTF-8 | 646 | 3.203125 | 3 | [] | no_license | import java.util.*;
public class XiaoYi{
public static int func(int m,int n){
while(n!=0){
int temp=m%n;
m=n;
n=temp;
}
return m;
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
while(sc.hasNextInt()){
int n=sc.nextInt();
int a=sc.nextInt();
for(int i=0;i<n;i++){
int b=sc.nextInt();
if(b<=a){
a+=b;
}else{
a+=func(a,b);
}
}
System.out.println(a);
}
}
} | true |
7f8117c8c1d128c7e88c2043e8660453247bebe2 | Java | thedarkclouds/arithmetic | /src/main/java/Linked/criclLinked/CLLNodeApi.java | UTF-8 | 380 | 2.421875 | 2 | [] | no_license | package Linked.criclLinked;
public class CLLNodeApi {
public int length(CLLNode headNode){
int length=0;
CLLNode currentNode=headNode;
while (currentNode!=null){
length++;
currentNode=currentNode.getNext();
if (currentNode==headNode){
break;
}
}
return length;
}
}
| true |
e1aebafaca9c208126bc293fd50dce5758066f24 | Java | jonathany23/JavaCodeChallenge | /src/test/java/org/jonathany23/challenge/arrays/CharacterRepogramingTest.java | UTF-8 | 539 | 2.328125 | 2 | [] | no_license | package org.jonathany23.challenge.arrays;
import org.junit.Test;
import static org.junit.Assert.*;
public class CharacterRepogramingTest {
@Test
public void chracter_reprograming_1() {
assertEquals(2, CharacterRepograming.getMaxDeletions("URDR"));
}
@Test
public void chracter_reprograming_2() {
assertEquals(0, CharacterRepograming.getMaxDeletions("RRR"));
}
@Test
public void chracter_reprograming_3() {
assertEquals(4, CharacterRepograming.getMaxDeletions("RUDRL"));
}
} | true |
dbd733f15538bcc6a5066621ed65c978fed58f6c | Java | lxxhack/myCode | /src/main/java/BowlingGame.java | UTF-8 | 760 | 2.75 | 3 | [] | no_license | public class BowlingGame{
public int getBowlingScore(String frame){
int cell=10;
int[] score=new int[cell*2+2];
int total=0;
int j=0;
int i;
for (i=0;i<frame.length();i++){
char c=frame.charAt(i);
switch(c)
{
case 'X':score[j++]=10;
if (j<cell*2)
score[j++]=0;
break;
case '/':score[j++]=10-score[j-2];
break;
case '-':score[j++]=0;
break;
case '|':
break;
default:score[j++]=c-'0';
}
}
for (i=0;i<cell*2-2;i+=2)
{
if(score[i]==10)
{
if (score[i+2]==10)
total+=20+score[i+4];
else
total+=10+score[i+2]+score[i+3];
}
else if(score[i]+score[i+1]==10)
{
total+=10+score[i+2];
}
else
{
total+=score[i]+score[i+1];
}
}
total+=score[i]+score[i+1]+score[i+2]+score[i+3];
return total;
}
}
| true |
912b825e2506ad0f9c111f22704096ba205d3a58 | Java | luke21608/SpringBootREST | /src/main/java/com/demo/mapper/demo/DemoMapper.java | UTF-8 | 191 | 1.804688 | 2 | [] | no_license | package com.demo.mapper.demo;
import org.apache.ibatis.annotations.Param;
import com.demo.bean.User;
public interface DemoMapper {
public User queryById(@Param(value="id") String id);
}
| true |
fde16bab9c8479fa3380f720e7b48fd8ebbb6dde | Java | EsupPortail/esup-publisher | /src/main/java/org/esupportail/publisher/web/rest/dto/RedactorDTO.java | UTF-8 | 2,926 | 2 | 2 | [
"LGPL-2.0-or-later",
"CDDL-1.1",
"EPL-1.0",
"CC0-1.0",
"GPL-2.0-only",
"BSD-3-Clause",
"Classpath-exception-2.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LGPL-2.1-only",
"MPL-2.0",
"LGPL-2.1-or-later",
"JSON",
"EPL-2.0",
"CDDL-1.0",
"MIT"
] | permissive | /**
* Copyright (C) 2014 Esup Portail http://www.esup-portail.org
* @Author (C) 2012 Julien Gribonvald <julien.gribonvald@recia.fr>
*
* 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.esupportail.publisher.web.rest.dto;
import java.io.Serializable;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.esupportail.publisher.domain.util.CstPropertiesLength;
/**
*
* @author GIP RECIA - Julien Gribonvald
* 13 oct. 2014
*/
@NoArgsConstructor
@ToString(callSuper=true)
public class RedactorDTO extends AbstractIdDTO<Long> implements IAbstractDTO<Long>, Serializable {
/** This field corresponds to the database column name. */
@Getter
@Setter
@NotNull
@Size(min=1,max= CstPropertiesLength.NAME)
private String name;
/** This field corresponds to the database column display_name. */
@Getter
@Setter
@NotNull
@Size(min=1, max=CstPropertiesLength.DISPLAYNAME)
private String displayName;
/** This field corresponds to the database column description. */
@Getter
@Setter
@NotNull
@Size(min=5, max=CstPropertiesLength.DESCRIPTION)
private String description;
/** This field corresponds to the database column name. */
@Getter
@Setter
@Min(1)
@Max(2)
private int nbLevelsOfClassification;
@Getter
@Setter
private boolean optionalPublishTime = false;
@Getter
@Setter
@Min(1)
@Max(999)
private int nbDaysMaxDuration;
/**
* @param modelId
* @param name
* @param displayName
* @param description
* @param nbLevelsOfClassification
*/
public RedactorDTO(@NotNull final Long modelId, @NotNull final String name, @NotNull final String displayName,
@NotNull final String description, @NotNull final int nbLevelsOfClassification, final boolean optionalPublishTime,
final int nbDaysMaxDuration) {
super(modelId);
this.name = name;
this.displayName = displayName;
this.description = description;
this.nbLevelsOfClassification = nbLevelsOfClassification;
this.optionalPublishTime = optionalPublishTime;
this.nbDaysMaxDuration = nbDaysMaxDuration;
}
}
| true |
662a1abfc2ca2f847641f7ce5decb3fd80eb2881 | Java | andresmarino87/Italo | /app/src/main/java/pedidos/ValPed.java | UTF-8 | 1,658 | 2.75 | 3 | [] | no_license | package pedidos;
public class ValPed {
private String continuar;
private String solicitar_compromiso;
private String compromiso_obligatorio;
private String estado_pedido;
private String motivo;
private String complemento_observacion;
private String mensaje_de_error;
public ValPed(){
continuar="";
solicitar_compromiso="";
compromiso_obligatorio="";
estado_pedido="";
motivo="";
complemento_observacion="";
mensaje_de_error="";
}
//Getters
public String getContinuar(){
return continuar;
}
public String getSolicitarCompromiso(){
return solicitar_compromiso;
}
public String getCompromisoObligatorio(){
return compromiso_obligatorio;
}
public String getEstdoPedido(){
return estado_pedido;
}
public String getMotivo(){
return motivo;
}
public String getComplementoObs(){
return complemento_observacion;
}
public String getMensajeError(){
return mensaje_de_error;
}
//Setters
public void setContinuar(String continuar){
this.continuar=continuar;
}
public void setSolicitarCompromiso(String solicitar_compromiso){
this.solicitar_compromiso=solicitar_compromiso;
}
public void setCompromisoObligatorio(String compromiso_obligatorio){
this.compromiso_obligatorio=compromiso_obligatorio;
}
public void setEstdoPedido(String estado_pedido){
this.estado_pedido=estado_pedido;
}
public void setMotivo(String motivo){
this.motivo=motivo;
}
public void setComplementoObs(String complemento_observacion){
this.complemento_observacion=complemento_observacion;
}
public void setMensajeError(String mensaje_de_error){
this.mensaje_de_error=mensaje_de_error;
}
}
| true |