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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a825e8cee4738b3e59e6a36a71c2623f6258f03a | Java | 3870009/Senla | /src/eu/senla/task2/Rainbow.java | UTF-8 | 10,015 | 3.671875 | 4 | [] | no_license | package eu.senla.task2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Rainbow {
private final static String COLOR_1 = "красный";
private final static String COLOR_2 = "оранжевый";
private final static String COLOR_3 = "желтый";
private final static String COLOR_4 = "зеленый";
private final static String COLOR_5 = "голубой";
private final static String COLOR_6 = "синий";
private final static String COLOR_7 = "фиолетовый";
private final static String MIXCOLOR_1 = "красно-";
private final static String MIXCOLOR_2 = "оранжево-";
private final static String MIXCOLOR_3 = "желто-";
private final static String MIXCOLOR_4 = "зелено-";
private final static String MIXCOLOR_6 = "сине-";
private final static String MIXCOLOR_7 = "фиолетово-";
void userInput() throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Введите номер цвета (0- для выхода из программы): ");
int userColor = Integer.parseInt(reader.readLine());
if(userColor == 0) break;
else {
if(userColor < 0 || userColor >= 100)
System.out.println("Неверный ввод. Диапазон ввода для простых цветов 1-7, для сложных цветов 10-77. Пожалуйста, повторите ввод.");
if(userColor >= 10 && userColor < 100){
int userColor1 = userColor/10; //нахождение числа из разряда десятков
int userColor2 = userColor%10; //нахождение числа из разряда единиц
showNumToColor(userColor1,userColor2);//использование метода с 2 параметрами
}
if(userColor > 0 && userColor < 10)
showNumToColor(userColor);//использование метода с 1 параметром
}
}
}
void showNumToColor(int userColor) {
switch (userColor) {
case 1:
System.out.println("Выбранный цвет - " + COLOR_1);
break;
case 2:
System.out.println("Выбранный цвет - " + COLOR_2);
break;
case 3:
System.out.println("Выбранный цвет - " + COLOR_3);
break;
case 4:
System.out.println("Выбранный цвет - " + COLOR_4);
break;
case 5:
System.out.println("Выбранный цвет - " + COLOR_5);
break;
case 6:
System.out.println("Выбранный цвет - " + COLOR_6);
break;
case 7:
System.out.println("Выбранный цвет - " + COLOR_7);
break;
default:
System.out.println("Неверный ввод. Диапазон ввода для простых цветов 1-7");
}
}
void showNumToColor(int userColor1, int userColor2) {
int userColorMix = Integer.parseInt(String.valueOf(userColor1) + String.valueOf(userColor2)); //склейка двух цифр в число
switch (userColorMix) {
case 01:
showNumToColor(1);
break;
case 10:
showNumToColor(1);
break;
case 11:
showNumToColor(1);
break;
case 12:
System.out.println("Выбранный цвет - " + MIXCOLOR_1 + COLOR_2);
break;
case 13:
System.out.println("Выбранный цвет - " + MIXCOLOR_1 + COLOR_3);
break;
case 14:
System.out.println("Выбранный цвет - " + MIXCOLOR_1 + COLOR_4);
break;
case 15:
System.out.println("Выбранный цвет - " + MIXCOLOR_1 + COLOR_5);
break;
case 16:
System.out.println("Выбранный цвет - " + MIXCOLOR_1 + COLOR_6);
break;
case 17:
System.out.println("Выбранный цвет - " + MIXCOLOR_1 + COLOR_7);
break;
case 02:
showNumToColor(2);
break;
case 20:
showNumToColor(2);
break;
case 22:
showNumToColor(2);
break;
case 21:
showNumToColor(1,2);
break;
case 23:
System.out.println("Выбранный цвет - " +MIXCOLOR_2 + COLOR_3);
break;
case 24:
System.out.println("Выбранный цвет - " + MIXCOLOR_2 + COLOR_4);
break;
case 25:
System.out.println("Выбранный цвет - " + MIXCOLOR_2 + COLOR_5);
break;
case 26:
System.out.println("Выбранный цвет - " + MIXCOLOR_2 + COLOR_6);
break;
case 27:
System.out.println("Выбранный цвет - " + MIXCOLOR_2 + COLOR_7);
break;
case 03:
showNumToColor(3);
break;
case 30:
showNumToColor(3);
break;
case 33:
showNumToColor(3);
break;
case 31:
showNumToColor(1,3);
break;
case 32:
showNumToColor(2,3);
break;
case 34:
System.out.println("Выбранный цвет - " + MIXCOLOR_3 + COLOR_4);
break;
case 35:
System.out.println("Выбранный цвет - " + MIXCOLOR_3 + COLOR_5);
break;
case 36:
System.out.println("Выбранный цвет - " + MIXCOLOR_3 + COLOR_6);
break;
case 37:
System.out.println("Выбранный цвет - " + MIXCOLOR_3 + COLOR_7);
break;
case 04:
showNumToColor(4);
break;
case 40:
showNumToColor(4);
break;
case 44:
showNumToColor(4);
break;
case 41:
showNumToColor(1,4);
break;
case 42:
showNumToColor(2,4);
break;
case 43:
showNumToColor(3,4);
break;
case 45:
System.out.println("Выбранный цвет - " + MIXCOLOR_4 + COLOR_5);
break;
case 46:
System.out.println("Выбранный цвет - " + MIXCOLOR_4 + COLOR_6);
break;
case 47:
System.out.println("Выбранный цвет - " + MIXCOLOR_4 + COLOR_7);
break;
case 05:
showNumToColor(5);
break;
case 50:
showNumToColor(5);
break;
case 55:
showNumToColor(5);
break;
case 51:
showNumToColor(1,5);
break;
case 52:
showNumToColor(2,5);
break;
case 53:
showNumToColor(3,5);
break;
case 54:
showNumToColor(4,5);
break;
case 56:
System.out.println("Выбранный цвет - " + MIXCOLOR_6 + COLOR_5);
break;
case 57:
System.out.println("Выбранный цвет - " + MIXCOLOR_7 + COLOR_5);
break;
case 06:
showNumToColor(6);
break;
case 60:
showNumToColor(6);
break;
case 66:
showNumToColor(6);
break;
case 61:
showNumToColor(1,6);
break;
case 62:
showNumToColor(2,6);
break;
case 63:
showNumToColor(3,6);
break;
case 64:
showNumToColor(4,6);
break;
case 65:
showNumToColor(5,6);
break;
case 67:
System.out.println("Выбранный цвет - " + MIXCOLOR_6 + COLOR_7);
break;
case 07:
showNumToColor(7);
break;
case 70:
showNumToColor(7);
break;
case 77:
showNumToColor(7);
break;
case 71:
showNumToColor(1,7);
break;
case 72:
showNumToColor(2,7);
break;
case 73:
showNumToColor(3,7);
break;
case 74:
showNumToColor(4,7);
break;
case 75:
showNumToColor(5,7);
break;
case 76:
showNumToColor(6,7);
break;
default:
System.out.println("Неверный ввод. Диапазон ввода для сложных цветов 10-77");
}
}
} | true |
6e3a671371be5994a7d16eedc3947a0cd495a720 | Java | QRXqrx/leetcode | /src/main/java/edu/postgraduate/programExercise/exception/myexceptions/NegativeParameterException.java | UTF-8 | 331 | 2.09375 | 2 | [] | no_license | package edu.postgraduate.programExercise.exception.myexceptions;
public class NegativeParameterException extends RuntimeException{
static final long serialVersionUID = -7034897745766939L;
public NegativeParameterException() {
}
public NegativeParameterException(String message) {
super(message);
}
}
| true |
194010f68f023a94e1971cc345c6ce8a8f4b58e0 | Java | opelayoa/Project | /app/src/main/java/com/tiendas3b/almacen/services/GeofenceTransitionsIntentService.java | UTF-8 | 14,356 | 1.773438 | 2 | [] | no_license | package com.tiendas3b.almacen.services;
import android.app.ActivityManager;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import com.tiendas3b.almacen.R;
import com.tiendas3b.almacen.activities.MainActivity;
import com.tiendas3b.almacen.geofencing.GeofenceErrorMessages;
import com.tiendas3b.almacen.util.FileUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
@SuppressWarnings("MissingPermission")
public class GeofenceTransitionsIntentService extends IntentService /*implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener*/ {
// public static final String FUSED_PRIVIDER = "fused";
protected static final String TAG = "GeofenceTransitionsIS";
// public static final int MILLISECONDS_PER_SECOND = 1000;
// public static final int UPDATE_INTERVAL_IN_SECONDS = 3;
// public static final long UPDATE_INTERVAL_IN_MILLISECONDS = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
// public static final int FAST_CEILING_IN_SECONDS = 1;
// public static final long FAST_INTERVAL_CEILING_IN_MILLISECONDS = MILLISECONDS_PER_SECOND * FAST_CEILING_IN_SECONDS;
// private static final float DISPLACEMAENT = 2.0f;
// private Context mContext;
// private IDatabaseManager db;
// protected GoogleApiClient mGoogleApiClient;
//// private LocationManager mLocationManager;
// private LocationRequest mLocationRequest;
// private boolean bfusedProvider = false;
// private LocationListener fusedListener;
// private Location mLastLocation;
// private Location mLocation;
// private boolean sendNow = false;
// private static GeofenceTransitionsIntentService instance = null;
//
// public static GeofenceTransitionsIntentService getInstance() {
// return instance;
// }
// public synchronized void setSendNow(boolean sendNow) {
// this.sendNow = sendNow;
// }
public GeofenceTransitionsIntentService() {
super(TAG);
}
@Override
public void onCreate() {
super.onCreate();
// mContext = getApplicationContext();
// mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Location l = new Location("");
// mLastLocation = db.
// buildGoogleApiClient();
// mGoogleApiClient.connect();
// fusedListener = new com.google.android.gms.location.LocationListener() {
// @Override
// public synchronized void onLocationChanged(Location location) {
// Log.w("FusedLocationListener", "onLocationChanged" + location.getTime());
// FileUtil.writeFile(TAG + ": onLocationChanged");
// if (LocationUtil.isBetterLocation(location, mLocation)) {
// mLocation = location;
// if (sendNow) {
// LocationService.startActionBestLocation(mContext, mLocation);
// }
// }
// }
// };
}
private static SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss:SSS", Locale.getDefault());
/**
* Handles incoming intents.
*
* @param intent sent by Location Services. This Intent is provided to Location
* Services (inside a PendingIntent) when addGeofences() is called.
*/
@Override
protected void onHandleIntent(Intent intent) {
FileUtil.writeFile(TAG + ": onHandleIntent");
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
if (geofencingEvent.hasError()) {
String errorMessage = GeofenceErrorMessages.getErrorString(this, geofencingEvent.getErrorCode());
FileUtil.writeFile(TAG + ": " + errorMessage);
//Log.e(TAG, errorMessage);
return;
}
int geofenceTransition = geofencingEvent.getGeofenceTransition();
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
String date = df.format(new Date());
FileUtil.writeFile(TAG + " : Exit " + date);
// sendNotification("Exit");
// List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
// String geofenceTransitionDetails = getGeofenceTransitionDetails(this, geofenceTransition, triggeringGeofences);
findBestLocation();
// sendNotification(geofenceTransitionDetails);
// Log.i(TAG, geofenceTransitionDetails);
} else {
FileUtil.writeFile(TAG + ": NO Exit");
//Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition));
}
FileUtil.writeFile(TAG + ": End");
}
private void findBestLocation() {
if (isMyServiceRunning(LocationService.class)) {
FileUtil.writeFile("isMyServiceRunning");
} else {
FileUtil.writeFile("!isMyServiceRunning");
Intent i = new Intent(this, LocationService.class);
startService(i);
// requestLocationFused(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, DISPLACEMAENT);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
// private boolean servicesConnected() {
// GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
// int result = googleAPI.isGooglePlayServicesAvailable(this);
// if (result != ConnectionResult.SUCCESS) {
//// if(googleAPI.isUserResolvableError(result)) {
//// googleAPI.getErrorDialog(this, result,
//// PLAY_SERVICES_RESOLUTION_REQUEST).show();
//// }
// FileUtil.writeFile(TAG + ": result != ConnectionResult.SUCCESS");
// return false;
// }
//
// return true;
// }
//
// public synchronized void requestLocationFused(int priority, float displacement) {
// FileUtil.writeFile(TAG + ": requestLocationFused");
// if (mGoogleApiClient == null) {
// FileUtil.writeFile(TAG + ": mGoogleApiClient == null");
// buildGoogleApiClient();
// mGoogleApiClient.connect();
// } else if (mGoogleApiClient.isConnected()) {
// FileUtil.writeFile(TAG + ": mGoogleApiClient.isConnected");
// if (!bfusedProvider) {
// FileUtil.writeFile(TAG + ": !bfusedProvider");
// startUpdates(priority, displacement);
// }
// } else if (mGoogleApiClient.isConnecting()) {
// Log.d(TAG, "mLocationClient.isConnecting");
// } else {
// mGoogleApiClient.connect();
// }
// }
//
// public void startUpdates(int priority, float displacement) {
// FileUtil.writeFile(TAG + ": startUpdates");
// if (servicesConnected()) {
//// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
// mLocationRequest = LocationRequest.create();
// mLocationRequest.setPriority(priority);
// mLocationRequest.setSmallestDisplacement(displacement);
// mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// mLocationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
//// if(checkLocationPermission()){
// LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, fusedListener);
// bfusedProvider = true;
//// writeFile("requestFusedUpdates!");
//// }
//
// }
// }
//
// public void stopUpdates() {
// FileUtil.writeFile(TAG + ": stopUpdates");
// if (servicesConnected()) {
// if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
//// writeFile("\n" + sdf.format(new Date()) + "removeFusedUpdates!");
// LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, fusedListener);
// }
// bfusedProvider = false;
// }
// }
//
// protected synchronized void buildGoogleApiClient() {
// mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
// }
//
// @Override
// public void onDestroy() {
// FileUtil.writeFile(TAG + ": onDestroy");
// super.onDestroy();
// stopUpdates();
// mGoogleApiClient.disconnect();
// mGoogleApiClient = null;
// }
//
// @Override
// public void onConnected(Bundle connectionHint) {
// FileUtil.writeFile(TAG + ": onConnected");
// Log.i(TAG, "Connected to GoogleApiClient");
// startUpdates(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, DISPLACEMAENT);
//// if (PermissionUtil.permissionGranted(this, Manifest.permission.ACCESS_FINE_LOCATION) /*|| PermissionUtil.permissionGranted(this, Manifest.permission.ACCESS_COARSE_LOCATION)*/) {
//// mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
//// } else {
//// PermissionUtil.showDialog(activity, PermissionUtil.REQUEST_FINE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
//// }
// }
//
// @Override
// public void onConnectionFailed(ConnectionResult result) {
// // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// // onConnectionFailed.
// Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
// }
//
// @Override
// public void onConnectionSuspended(int cause) {
// // The connection to Google Play services was lost for some reason.
// Log.i(TAG, "Connection suspended");
//
// // onConnected() will be called again automatically when the service reconnects
// }
// /**
// * Gets transition details and returns them as a formatted string.
// *
// * @param context The app context.
// * @param geofenceTransition The ID of the geofence transition.
// * @param triggeringGeofences The geofence(s) triggered.
// * @return The transition details formatted as String.
// */
// private String getGeofenceTransitionDetails(Context context, int geofenceTransition, List<Geofence> triggeringGeofences) {
//
// String geofenceTransitionString = getTransitionString(geofenceTransition);
//
// // Get the Ids of each geofence that was triggered.
// ArrayList triggeringGeofencesIdsList = new ArrayList();
// for (Geofence geofence : triggeringGeofences) {
// triggeringGeofencesIdsList.add(geofence.getRequestId());
// }
// String triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList);
//
// return geofenceTransitionString + ": " + triggeringGeofencesIdsString;
// }
/**
* Posts a notification in the notification bar when a transition is detected.
* If the user clicks the notification, control goes to the MainActivity.
*/
private void sendNotification(String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setSmallIcon(R.drawable.ic_date_24dp)
// In a real app, you may want to use a library like Volley
// to decode the Bitmap.
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_date_24dp)).setColor(Color.RED).setContentTitle(notificationDetails).setContentText(getString(R.string.geofence_transition_notification_text)).setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
// /**
// * Maps geofence transition types to their human-readable equivalents.
// *
// * @param transitionType A transition type constant defined in Geofence
// * @return A String indicating the type of transition
// */
// private String getTransitionString(int transitionType) {
// switch (transitionType) {
// case Geofence.GEOFENCE_TRANSITION_ENTER:
// return getString(R.string.geofence_transition_entered);
// case Geofence.GEOFENCE_TRANSITION_EXIT:
// return getString(R.string.geofence_transition_exited);
// default:
// return getString(R.string.unknown_geofence_transition);
// }
// }
} | true |
ae4b17d31b68477f1cb01458648c30e3593e3add | Java | Team3176/2021_Robot_Code | /Akriveia/src/main/java/frc/robot/commands/teleop/DrumVelocityUp.java | UTF-8 | 1,661 | 2.359375 | 2 | [] | no_license | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.teleop;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.Drum;
import frc.robot.constants.DrumConstants;
import java.util.UUID;
public class DrumVelocityUp extends CommandBase {
/** Creates a new DrumVelocitySpeed2. */
Drum m_Drum = Drum.getInstance();
int tempSetting;
String procTag;
public DrumVelocityUp() {
// Use addRequirements() here to declare subsystem dependencies.
addRequirements(m_Drum);
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
// System.out.println("DrumVelocitySpeed.initialized executed. ########################################################");
tempSetting = m_Drum.getLastSetting();
procTag = UUID.randomUUID().toString();
System.out.println("______DRUM VELOCITY UP INITIALIZED______");
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
if (tempSetting + 1 < DrumConstants.SPEEDS.length) {
m_Drum.pidVelCtrl_setRpmLevel(tempSetting + 1, procTag);
//m_Drum.pidVelCtrl_step4LevelsToDesiredSpeed(tempSetting + 1, 1, procTag);
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return (procTag == m_Drum.getProcTag()) ? true : false;
}
}
| true |
8be4f179eca4756cb23156bf6eb4a4fde8f34121 | Java | londonb/CodeReviewWeek4Java | /src/test/java/AppTest.java | UTF-8 | 1,580 | 2.453125 | 2 | [
"MIT"
] | permissive | import org.junit.*;
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.fluentlenium.adapter.FluentTest;
import org.junit.ClassRule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import static org.assertj.core.api.Assertions.assertThat;
public class AppTest extends FluentTest {
public WebDriver webDriver = new HtmlUnitDriver();
public WebDriver getDefaultDriver() {
return webDriver;
}
@ClassRule
public static ServerRule server = new ServerRule();
@Test
public void rootTest() {
goTo("http://localhost:4567/");
assertThat(pageSource()).contains("Welcome to the Concert Database");
}
@Test
public void bandIsCreated() {
goTo("http://localhost:4567/bands");
fill("#band_name").with("Go Go Boogie");
submit("#addBand");
assertThat(pageSource()).contains("Go Go Boogie");
}
@Test
public void venueIsCreated() {
goTo("http://localhost:4567/venues");
fill("#venueName").with("40 Watt");
submit("#addVenue");
assertThat(pageSource()).contains("40 Watt");
}
@Test
public void addVenueToBand() {
Venue newVenue = new Venue("Fox Teater");
newVenue.save();
Band newBand = new Band("Go Go Boogie");
newBand.save();
String bandPath = String.format("http://localhost:4567/bands/%d", newBand.getId());
goTo(bandPath);
assertThat(pageSource()).contains("Fox Teater");
assertThat(pageSource()).contains("Go Go Boogie");
}
}
| true |
57ea1d228f15ed257820942f067dc0a25124ace7 | Java | MiguelLiraLuis/WeTranslate | /src/utils/NodeData.java | UTF-8 | 699 | 2.796875 | 3 | [] | no_license | package utils;
import java.io.Serializable;
public class NodeData implements Comparable<NodeData>, Serializable {
private String addr;
private String port;
private String location;
private int requestsTaken;
public NodeData(String addr, String port) {
this.addr = addr;
this.port = port;
this.location = addr + ":" + port;
this.requestsTaken = 0;
}
public String getAddr() {
return addr;
}
public String getPort() {
return port;
}
public String getLocation() {
return location;
}
public void increaseRequestsTaken() {
this.requestsTaken++;
}
@Override
public int compareTo(NodeData nd) {
return Integer.compare(this.requestsTaken, nd.requestsTaken);
}
}
| true |
0195b925980d0ee35e7ac11f460406230f6655c1 | Java | adikarah/Virtualize-Backened | /src/test/java/com/hu/Virtualize/controllers/admin/ProductControllerTest.java | UTF-8 | 4,523 | 2 | 2 | [] | no_license | package com.hu.Virtualize.controllers.admin;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hu.Virtualize.commands.admin.ProductCommand;
import com.hu.Virtualize.entities.AdminEntity;
import com.hu.Virtualize.services.admin.ProductCreateServiceImpl;
import com.hu.Virtualize.services.admin.ShopServiceImpl;
import com.hu.Virtualize.services.admin.service.ProductCreateService;
import com.hu.Virtualize.services.admin.service.ShopService;
import com.hu.Virtualize.services.user.ProductServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired
private ObjectMapper objectMapper;
@Autowired
private MockMvc mockMvc;
@MockBean
private ProductCreateServiceImpl productCreateService;
@MockBean
private ShopServiceImpl shopService;
private ProductCommand productCommand;
private AdminEntity adminEntity;
@BeforeEach
void setUp() {
productCommand = new ProductCommand(1L,1L,1L,"abc",200,"Peter","ncjdn","CLOTHE","size",null);
adminEntity = new AdminEntity(1L,"User","u@gmail.com","123",null);
}
@Test
void insertShop() throws Exception{
when(productCreateService.insertProduct(productCommand)).thenReturn(adminEntity);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/admin/product/create")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(productCommand)))
.andExpect(status().isOk())
.andReturn();
AdminEntity adminEntity1 = objectMapper.readValue(mvcResult.getResponse().getContentAsString(),AdminEntity.class);
assertEquals(adminEntity1.getAdminId(), adminEntity.getAdminId());
}
@Test
void updateProduct() throws Exception{
when(productCreateService.updateProduct(any())).thenReturn(adminEntity);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.put("/admin/product/update")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(productCommand)))
.andExpect(status().isOk())
.andReturn();
AdminEntity adminEntity1 = objectMapper.readValue(mvcResult.getResponse().getContentAsString(),AdminEntity.class);
assertEquals(adminEntity1.getAdminId(), adminEntity.getAdminId());
}
@Test
void deleteProduct() throws Exception{
when(productCreateService.deleteProduct(productCommand)).thenReturn(adminEntity);
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.delete("/admin/product/delete")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(productCommand)))
.andExpect(status().isOk())
.andReturn();
AdminEntity adminEntity1 = objectMapper.readValue(mvcResult.getResponse().getContentAsString(),AdminEntity.class);
assertEquals(adminEntity1.getAdminId(), adminEntity.getAdminId());
}
@Test
void getAllProductType() throws Exception{
when(productCreateService.getAllProductType()).thenReturn(Arrays.asList("abc","efg"));
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/admin/product/types"))
.andExpect(status().isOk())
.andReturn();
List<String> products = objectMapper.readValue(mvcResult.getResponse().getContentAsString(), List.class);
assertEquals(products.size(), 2);
}
} | true |
ee6d6e2c654fdfc26b0bab2e9e3b6bf711307196 | Java | amilosh/Person | /src/main/java/by/it/milosh/controllers/PersonController.java | UTF-8 | 1,281 | 2.203125 | 2 | [] | no_license | package by.it.milosh.controllers;
import by.it.milosh.service.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import by.it.milosh.entity.Person;
import java.util.List;
@RestController
@RequestMapping("/person")
public class PersonController {
private PersonService personService;
@Autowired
public PersonController(PersonService personService) {
this.personService = personService;
}
@RequestMapping(value = "/list")
public List<Person> getAllPersons() {
return personService.getAllPersons();
}
@RequestMapping(value = "/list/{id}")
public Person findOne(@PathVariable Long id) {
return personService.findOne(id);
}
@RequestMapping(value = "/add")
public Person addPerson(@RequestBody Person person) {
return personService.addT(person);
}
@RequestMapping(value = "/delete/{id}")
public String deleteStringPerson(@PathVariable Long id) {
return personService.deleteStringT(id);
}
}
| true |
7ba24e7444284bf05f1c7a16caabca94df94951c | Java | yerasylalibek/MidterProjectJavaEE | /midterm/src/main/java/kz/edu/iitu/servlet/InsertServlet.java | UTF-8 | 1,747 | 2.421875 | 2 | [] | no_license | package kz.edu.iitu.servlet;
import kz.edu.iitu.dao.TicketDaoImpl;
import kz.edu.iitu.dao.UserDaoImpl;
import kz.edu.iitu.model.Ticket;
import kz.edu.iitu.model.User;
import javax.servlet.RequestDispatcher;
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.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet(name = "/insert")
public class InsertServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Insert Ticket");
int id = Integer.parseInt(request.getParameter("id"));
String froma = request.getParameter("froma");
String tob = request.getParameter("tob");
int price = Integer.parseInt(request.getParameter("price"));
TicketDaoImpl ticketDao = new TicketDaoImpl();
Ticket ticket = new Ticket();
ticket.setId(id);
ticket.setFrom(froma);
ticket.setTo(tob);
ticket.setPrice(price);
int res = ticketDao.insert(ticket);
if(res != 0){
request.setAttribute("success", "Ticket Added!");
System.out.println("Sending to tickets.jsp)");
request.getRequestDispatcher("tickets.jsp").forward(request, response);
}else{
request.setAttribute("wrong", "Something wrong! PLease try again!");
System.out.println("Something wrong! PLease try again)");
request.getRequestDispatcher("tickets.jsp").forward(request, response);
}
}
}
| true |
69e756f57177325c591ea291c8da85a7f2b54a2f | Java | Michael-Raafat/SIC-Assembler | /Assembler/src/assembler/pass/parsers/ISecondPassParser.java | UTF-8 | 619 | 2.6875 | 3 | [] | no_license | package assembler.pass.parsers;
import java.util.List;
import assembler.instruction.Instruction;
/**
* Interface of the second pass parser.
* @author Amr
*
*/
public interface ISecondPassParser {
/**
* Performs the second pass on the list of instructions.
* @param sourceProgram
* The list of instructions.
* @param outPath
* The output path for the listing file and object code.
* @return
* True if it contained no errors, false otherwise.
* @param endIndex
* The index of the end instruction.
*/
boolean secondPass(String outPath, List<Instruction> sourceProgram,
Integer endIndex);
}
| true |
b2570371a0fa65ac6b8d93857d953010cae44f5e | Java | wufan52/fuckyun | /src/cn/hbkcn/fuckyun/Main.java | UTF-8 | 2,373 | 2.53125 | 3 | [] | no_license | package cn.hbkcn.fuckyun;
import fuckyun.listener.DownListener;
import fuckyun.listener.UpListener;
import fuckyun.main.FuckYun;
import fuckyun.network.Http;
import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
/**
* 测试
*/
public class Main {
private static String url = "http://39.108.149.133/test/fuckyun.php";
private static String id = "1";
private static String table = User.class.getSimpleName();
public static void main(String[] args) {
FuckYun fuckYun = new FuckYun(id, url, table);
UpListener upListener = (code, msg) -> System.out.println(code + ": " + msg);
DownListener<User> downListener = System.out::println;
// LinkedList<File> files = new LinkedList<>();
// files.add(new File("C:\\Users\\hbk\\Desktop\\ssr.txt"));
// files.add(new File("C:\\Users\\hbk\\Desktop\\宝塔.txt"));
// fuckYun.uploadFile(files, upListener);
LinkedList<File> files = new LinkedList<>();
files.add(new File("C:\\Users\\hbk\\Desktop\\ssr.txt"));
files.add(new File("C:\\Users\\hbk\\Pictures\\视频项目\\Windows7.png"));
files.add(new File("D:\\students.json"));
fuckYun.uploadFile(files, upListener);
//
// Where where = new Where();
// // username LIKE 0004%
// where.add("username", "0004%", Where.Type.LIKE);
//
// // LIMIT 5
// Limit limit = new Limit(5);
//
// // 查询
// fuckYun.query(where, limit, User.class, (DownListener<User>) result -> {
// int code = result.getCode();
// String message = result.getMessage();
// System.out.println(code + ": " + message);
// ArrayList<User> data = result.getData();
// for (User user : data) {
// System.out.println(user.getUsername() + user.getPassword());
// }
// });
// 删除对象
// fuckYun.delete(where, listener);
// 删除所有数据
// fuckYun.deleteAllData(listener);
// 删除表
// fuckYun.deleteTable(listener);
//
// 更新
// fuckYun.update(user, where, listener);
// 创建表
// fuckYun.createTable(User.class, listener);
// 保存
// fuckYun.save(user, listener);
// 保存
// user.save(table, listener);
}
}
| true |
3ffc1519e2828ee237d6f79ec01a61012293c425 | Java | manufarfaro/Twitter4Pirates | /src/main/java/ar/edu/unlam/t4p/acciones/UnfollowServlet.java | UTF-8 | 2,025 | 2.15625 | 2 | [] | no_license | package ar.edu.unlam.t4p.acciones;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 ar.edu.unlam.t4p.model.User;
import ar.edu.unlam.t4p.servicios.ServiceLocator;
import ar.edu.unlam.t4p.servicios.UserService;
/**
* Servlet implementation class UnfollowServlet
*/
@WebServlet("/unfollow.do")
public class UnfollowServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UnfollowServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserService userService = ServiceLocator.getInstance().getUserService();
User usuario = (User)request.getSession().getAttribute(SessionConstants.USER);
String datoUsuario = request.getParameter("datoUsuario");
User nuevoUsuario = userService.findByUsername(datoUsuario);
String idUser = String.valueOf(nuevoUsuario.getId());
userService.removeFollowing(nuevoUsuario, usuario);
userService.removeFollower(nuevoUsuario, usuario);
request.setAttribute("usuarioPerfil", nuevoUsuario);
String dispatcherPage = "others.do?profile=".concat(idUser);
RequestDispatcher ruta = request.getRequestDispatcher(dispatcherPage);
ruta.forward(request, response);
}
}
| true |
b5a66b8dff4ca91b1cef01351739a05214fb1dd8 | Java | wangde/Securityguards | /app/src/main/java/com/hlju/wangde/securityguards/service/LocationService.java | UTF-8 | 3,208 | 2.015625 | 2 | [] | no_license | package com.hlju.wangde.securityguards.service;
import android.Manifest;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import com.hlju.wangde.securityguards.utils.PrefUtils;
import java.util.List;
public class LocationService extends Service {
private LocationManager mLM;
private MyListener mListener;
@Override
public void onCreate() {
super.onCreate();
mLM = (LocationManager) getSystemService(LOCATION_SERVICE);
List<String> allProviders = mLM.getAllProviders();
System.out.println(allProviders);
mListener = new MyListener();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(true);//允许花费流量
String bestProvider = mLM.getBestProvider(criteria, true);//获取当前最合适的位置提供者
mLM.requestLocationUpdates(bestProvider, 0, 0, mListener);
}
public LocationService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
class MyListener implements LocationListener {
//位置发生变化
@Override
public void onLocationChanged(Location location) {
String j = "j:" + location.getLongitude();//经度
String w = "w:" + location.getLatitude();//纬度
String accuracy = "accuracy:" + location.getAccuracy();//精确度
// String altitude ="altitude"+location.getAltitude();//海拔
String result = j + "\n" + w + "\n" + accuracy;
String phone = PrefUtils.getString("safe_phone", "", getApplicationContext());
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(phone, null, result, null, null);
stopSelf();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
System.out.println("onStatusChanged");
}
@Override
public void onProviderEnabled(String provider) {
System.out.println("onProviderEnabled");
}
@Override
public void onProviderDisabled(String provider) {
System.out.println("onProviderDisabled");
}
}
@Override
public void onDestroy() {
super.onDestroy();
mLM.removeUpdates(mListener);
mListener = null;
}
}
| true |
9e783c7baf741ce66c1e7f9da15fb22bcb4a55a2 | Java | trauvmfpt/ass-jws-client | /src/main/java/t1708e/asm/diduduadi/entity/User.java | UTF-8 | 3,492 | 2.109375 | 2 | [] | no_license | package t1708e.asm.diduduadi.entity;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int age;
private int gender;
private String address;
private String password;
@Column(unique = true)
private String email;
@Column(unique = true)
private String username;
@Column(unique = true)
private String token;
private String salt;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Post> postSet;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Comment> commentSet;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Rating> ratingSet;
@ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, fetch = FetchType.EAGER)
@JoinTable(name = "role_user",
joinColumns = @JoinColumn(name = "userId"),
inverseJoinColumns = @JoinColumn(name = "roleId"))
private Set<Role> roleSet;
public Set<Role> getRoleSet() {
return roleSet;
}
public void setRoleSet(Set<Role> roleSet) {
this.roleSet = roleSet;
}
private int status;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Set<Post> getPostSet() {
return postSet;
}
public void setPostSet(Set<Post> postSet) {
this.postSet = postSet;
}
public Set<Comment> getCommentSet() {
return commentSet;
}
public void setCommentSet(Set<Comment> commentSet) {
this.commentSet = commentSet;
}
public Set<Rating> getRatingSet() {
return ratingSet;
}
public void setRatingSet(Set<Rating> ratingSet) {
this.ratingSet = ratingSet;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public void addRole(Role role) {
if (this.roleSet == null) {
this.roleSet = new HashSet<>();
}
this.roleSet.add(role);
}
}
| true |
2cfb210a6231d050037a4f38174e88966a80e4aa | Java | yffd/jecap-admin-sys | /src/main/java/com/yffd/jecap/admin/sys/domain/role/entity/SysRole.java | UTF-8 | 1,346 | 2.203125 | 2 | [] | no_license | package com.yffd.jecap.admin.sys.domain.role.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.yffd.jecap.admin.base.entity.IBaseEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import java.time.LocalDateTime;
/**
* <p>
* 系统-角色表
* </p>
*
* @author ZhangST
* @since 2020-09-28
*/
@Data
@Accessors(chain = true)
@NoArgsConstructor
public class SysRole implements IBaseEntity {
private static final long serialVersionUID = 1L;
/**
* 主键
*/
@TableId(type = IdType.AUTO)
private String roleId;
/**
* 角色名称
*/
private String roleName;
/**
* 角色编号
*/
private String roleCode;
/**
* 角色状态,1=启用、0=禁用
*/
private String roleStatus;
/**
* 创建时间
*/
private LocalDateTime createTime;
public SysRole(String roleName, String roleCode) {
this.roleName = roleName;
this.roleCode = roleCode;
}
public SysRole initValue() {
if (StringUtils.isBlank(this.roleStatus)) this.roleStatus = "1";
if (null == this.createTime) this.createTime = LocalDateTime.now();
return this;
}
}
| true |
ac3b89adf67430f627deb2207e644acc582d5921 | Java | jmagicdev/jmagic | /cards/src/main/java/org/rnd/jmagic/cards/SignaltheClans.java | UTF-8 | 2,135 | 3.09375 | 3 | [] | no_license | package org.rnd.jmagic.cards;
import static org.rnd.jmagic.Convenience.*;
import org.rnd.jmagic.engine.*;
import org.rnd.jmagic.engine.generators.*;
@Name("Signal the Clans")
@Types({Type.INSTANT})
@ManaCost("RG")
@ColorIdentity({Color.RED, Color.GREEN})
public final class SignaltheClans extends Card
{
public SignaltheClans(GameState state)
{
super(state);
// Search your library for three creature cards and reveal them.
EventFactory search = new EventFactory(EventType.SEARCH, "Search your library for three creature cards and reveal them.");
search.parameters.put(EventType.Parameter.CAUSE, This.instance());
search.parameters.put(EventType.Parameter.PLAYER, You.instance());
search.parameters.put(EventType.Parameter.NUMBER, numberGenerator(3));
search.parameters.put(EventType.Parameter.CARD, LibraryOf.instance(You.instance()));
search.parameters.put(EventType.Parameter.TYPE, Identity.instance(HasType.instance(Type.CREATURE)));
this.addEffect(search);
// If you reveal three cards with different names, choose one of them at
// random and put that card into your hand.
SetGenerator revealedCards = Intersect.instance(EffectResult.instance(search), Cards.instance());
SetGenerator threeNames = Intersect.instance(numberGenerator(3), Count.instance(NameOf.instance(revealedCards)));
EventFactory random = new EventFactory(RANDOM, "Choose one of them at random");
random.parameters.put(EventType.Parameter.OBJECT, revealedCards);
SetGenerator chosen = EffectResult.instance(random);
EventFactory toHand = putIntoHand(chosen, You.instance(), "and put that card into your hand");
// The three names condition is sufficient, since if you search for less
// than three cards, there will be less than three names (and you can't
// search for more)
EventFactory effect = ifThen(threeNames, sequence(random, toHand), "If you reveal three cards with different names, choose one of them at random and put that card into your hand.");
this.addEffect(effect);
// Shuffle the rest into your library.
this.addEffect(shuffleLibrary(You.instance(), "Shuffle the rest into your library."));
}
}
| true |
07708cde380070794074f099fa0c9e0fa874ca9f | Java | jackz314/KeepFit | /app/src/main/java/com/jackz314/keepfit/models/User.java | UTF-8 | 4,318 | 2.5625 | 3 | [] | no_license | package com.jackz314.keepfit.models;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.PropertyName;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.ExecutionException;
public class User implements Serializable {
private static final String TAG = "User";
private String uid;
private String biography;
private String email;
private String name;
private String profilePic;
private Date birthday;
private int height; // cm
private int weight; // kg
private boolean sex; // true for men, false for women
public User() {
name = "";
}
public User(DocumentSnapshot doc) {
if (!doc.exists()) return;
uid = doc.getId();
biography = doc.getString("biography");
email = doc.getString("email");
name = doc.getString("name");
profilePic = doc.getString("profile_pic");
birthday = doc.getDate("birthday");
Long height = doc.getLong("height");
if (height == null) height = 0L;
this.height = height.intValue();
Long weight = doc.getLong("weight");
if (weight == null) weight = 0L;
this.weight = weight.intValue();
Boolean sex = doc.getBoolean("sex");
if (sex == null) sex = true;
this.sex = sex;
}
public User(String uid, String biography, String email, String name, String profilePic, Date birthday, int height, int weight, boolean sex) {
this.uid = uid;
this.biography = biography;
this.email = email;
this.name = name;
this.profilePic = profilePic;
this.birthday = birthday;
this.height = height;
this.weight = weight;
this.sex = sex;
}
public static User populateFromUid(String uid) {
try {
return new User(Tasks.await(FirebaseFirestore.getInstance().collection("users").document(uid).get()));
} catch (ExecutionException | InterruptedException e) {
Log.e(TAG, "populateFromUid: error getting user from uid", e);
}
return null;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getBiography() {
return biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@PropertyName("profile_pic")
public String getProfilePic() {
return profilePic;
}
@PropertyName("profile_pic")
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public boolean getSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
@NotNull
@Override
public String toString() {
return "User{" +
"uid='" + uid + '\'' +
", biography='" + biography + '\'' +
", email='" + email + '\'' +
", name='" + name + '\'' +
", profile_pic='" + profilePic + '\'' +
", birthday=" + birthday +
", height=" + height +
", weight=" + weight +
", sex=" + sex +
'}';
}
@NonNull
public User copy() {
return new User(uid, biography, email, name, profilePic, birthday, height, weight, sex);
}
}
| true |
cd5ad8f0a58f45694ee6ec2537f5b21b9c1e1f78 | Java | LuiJ/data-structures-and-algorithms | /src/main/java/root/tree/BinaryTree.java | UTF-8 | 1,256 | 3.390625 | 3 | [] | no_license | package root.tree;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
public class BinaryTree<V extends Comparable<V>>
{
@Getter
private Node<V> root;
public void addNode(V value)
{
if (root == null)
{
root = new Node<>(value);
}
else
{
root.addChildNode(value);
}
}
@RequiredArgsConstructor
@Getter
public static class Node<V extends Comparable<V>>
{
private final V value;
private Node<V> left;
private Node<V> right;
private void addChildNode(V childNodeValue)
{
if (childNodeValue.compareTo(this.value) > 0)
{
if (right == null)
{
right = new Node<>(childNodeValue);
}
else
{
right.addChildNode(childNodeValue);
}
}
else
{
if (left == null)
{
left = new Node<>(childNodeValue);
}
else
{
left.addChildNode(childNodeValue);
}
}
}
}
}
| true |
cbd8907b3689d9e6d88d2ef94457acb45e649c21 | Java | Draaft4/Ferreteria | /SistemaAdiscom/src/DAO/UsuarioBD.java | UTF-8 | 1,126 | 2.828125 | 3 | [] | no_license | package DAO;
import ConexionBD.BaseDeDatos;
import Modelo.Usuario;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class UsuarioBD {
public ArrayList<Usuario> ListUsuario() {
ArrayList<Usuario> usuario = new ArrayList();
try {
Connection cnx = BaseDeDatos.getConnection();
Statement st = cnx.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM fr_usuarios");
while (rs.next()) {
int idUsr = rs.getInt("idusr");
String password = rs.getString("contraseña");
int nivelAcceso = rs.getInt("nivelacceso");
String user = rs.getString("usuario");
Usuario cl = new Usuario(idUsr, password, nivelAcceso, user);
usuario.add(cl);
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
System.out.println("Error en listado");
}
return usuario;
}
}
| true |
854080abca0f904954ef85c020c5faf4e9ba0dd0 | Java | CJX413/tcsms-springcloud3_22 | /business-server/src/main/java/com/tcsms/business/Entity/RoleApply.java | UTF-8 | 1,495 | 2.34375 | 2 | [] | no_license | package com.tcsms.business.Entity;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Objects;
@Entity
@Data
@Table(name = "role_apply")
@EntityListeners(AuditingEntityListener.class)//自动更新时间戳
public class RoleApply {
@Id
@Column(name = "username")
private String username;
@Basic
@Column(name = "role")
private String role;
@Basic
@Column(name = "createTime")
@CreatedDate
@LastModifiedDate
private Timestamp createTime;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RoleApply roleApply = (RoleApply) o;
return Objects.equals(username, roleApply.username) &&
Objects.equals(role, roleApply.role) &&
Objects.equals(createTime, roleApply.createTime);
}
@Override
public int hashCode() {
return Objects.hash(username, role, createTime);
}
@Override
public String toString() {
return "{" +
"\"username\":" + "\"" + username + "\"" + "," +
"\"role\":" + "\"" + role + "\"" + "," +
"\"createTime\":" + "\"" + createTime + "\"" +
"}";
}
}
| true |
75f552f288ee656fad41801676eb44426fcee437 | Java | zhaoxichen/cloud-alibaba-security | /micro-cloud/service-sys/src/main/java/com/galen/micro/sys/controller/MenuController.java | UTF-8 | 4,785 | 2.3125 | 2 | [] | no_license | package com.galen.micro.sys.controller;
import com.galen.model.AplResponse;
import com.galen.model.ResponseUtils;
import com.galen.micro.sys.annotation.SysLog;
import com.galen.micro.sys.model.MenuFilter;
import com.galen.micro.sys.service.MenuService;
import com.galen.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(value = "权限controller", tags = {"权限菜单操作接口"})
@RestController
@RequestMapping("menu")
public class MenuController {
@Autowired
private MenuService menuService;
@SysLog("增加权限菜单")
@ApiOperation("增加权限菜单(把资源加入权限管理)")
@PostMapping("create")
public AplResponse createSysMenu(Integer menuType, Long parentId, String title, String titleEn, String iconPic, String path, String component,
String elementId, String requestUrl, Integer sortOrder) {
if (null == menuType) {
return ResponseUtils.FAIL("请传入菜单类型:1:左侧主菜单;2:页面中的按钮;3:页面中标签");
}
if (null == parentId) {
parentId = 0L;
}
if (StringUtil.isEmpty(title)) {
if (1 == menuType) {
return ResponseUtils.FAIL("请传入菜单名称");
}
}
if (StringUtil.isEmpty(titleEn)) {
if (1 == menuType) {
return ResponseUtils.FAIL("请传入菜单英文名称");
}
}
if (StringUtil.isEmpty(elementId)) {
if (2 == menuType) {
return ResponseUtils.FAIL("请传入元素id");
}
}
if (StringUtil.isEmpty(requestUrl)) {
requestUrl = "/";
}
if (null == sortOrder) {
sortOrder = 1;
}
return menuService.createSysMenu(menuType, parentId, title, titleEn, iconPic, path, component, elementId, requestUrl, sortOrder);
}
@SysLog("更新权限菜单")
@ApiOperation("更新权限菜单")
@PostMapping("modify")
public AplResponse modifySysMenu(Long id, String title, String titleEn, String iconPic, String path, String component,
String elementId, String requestUrl, Integer sortOrder) {
if (null == id) {
return ResponseUtils.FAIL("请传入权限菜单id");
}
return menuService.modifySysMenu(id, title, titleEn, iconPic, path, component, elementId, requestUrl, sortOrder);
}
@ApiOperation("添加角色拥有xxx权限")
@PostMapping("add/to")
public AplResponse addToSysMenu(Long roleId, Long menuId) {
if (null == roleId || null == menuId) {
return ResponseUtils.build(401, "错误");
}
return menuService.addToSysMenu(roleId, menuId);
}
@ApiOperation(value = "查看系统权限资源管理", notes = "权限资源管理页面查看权限资源原始数据")
@GetMapping("list/all/get")
public AplResponse getAllSysMenuList(MenuFilter filter) {
return menuService.getAllSysMenuList(filter);
}
@ApiOperation(value = "查看系统权限资源", notes = "如果传入roleId,则顺便核查此角色是否拥有该权限,对应的权限对象中的onChoose=true为拥有")
@GetMapping("list/get")
public AplResponse getSysMenuList(Long roleId) {
if (null == roleId) {
return menuService.getSysMenuList();
}
return menuService.getSysMenuList(roleId);
}
@ApiOperation("仅查看xx角色的权限资源列表")
@GetMapping("list/role/get")
public AplResponse getRoleSysMenuList(Long roleId) {
if (null == roleId) {
return ResponseUtils.build(401, "错误");
}
return menuService.getRoleSysMenuList(roleId);
}
@ApiOperation("移除xx角色的一个权限资源")
@PostMapping("/role/remove")
public AplResponse removeRoleSysMenu(Long roleId, Long menuId) {
if (null == roleId || null == menuId) {
return ResponseUtils.build(401, "错误");
}
return menuService.removeRoleSysMenu(roleId, menuId);
}
@ApiOperation("移除一个权限资源")
@PostMapping("/remove")
public AplResponse removeSysMenu(Long menuId) {
if (null == menuId) {
return ResponseUtils.build(401, "错误");
}
return menuService.removeSysMenu(menuId);
}
}
| true |
f443a2510f732788988fd221be2676e22d988090 | Java | keithwilsonqa/Selenium | /BetAmerica/src/main/java/BetAmericaTests/Utilities.java | UTF-8 | 1,261 | 3.125 | 3 | [] | no_license | package BetAmericaTests;
import java.util.Random;
/**
* Created by keith.wilson on 6/9/17.
*/
public class Utilities {
public String getRandomUsername() {
Random rand = new Random();
int randomNumber = rand.nextInt((99999999 - 10000000) + 1) + 10000000;
return "wilson" + Integer.toString(randomNumber);
}
public String getRandomPhoneNumber() {
Random rand = new Random();
int firstDigit = rand.nextInt((9 - 1) + 1) + 1;
int randomNumber = rand.nextInt((999999999 - 100000000) + 1) + 100000000;
return firstDigit + Integer.toString(randomNumber);
}
public String getRandomDOB() {
Random rand = new Random();
int m = rand.nextInt((12 - 1) + 1) + 1;
String month;
if (m < 10) {
month = "0" + Integer.toString(m);
} else {
month = Integer.toString(m);
}
String day;
int d = rand.nextInt((29 - 1) + 1) + 1;
if (d < 10) {
day = "0" + Integer.toString(d);
} else {
day = Integer.toString(d);
}
int y = rand.nextInt((1990 - 1930) + 1) + 1930;
String year = Integer.toString(y);
return month + "/" + day + "/" + year;
}
}
| true |
ee0ec3a1eab863a48195455fbf41b81579462b07 | Java | Driw/timesheet | /src/main/java/br/com/driw/timesheet/config/RestMcvConfig.java | UTF-8 | 667 | 1.96875 | 2 | [] | no_license | package br.com.driw.timesheet.config;
import br.com.driw.timesheet.Constants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
@Configuration
public class RestMcvConfig {
@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {
return new RepositoryRestConfigurer() {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.setBasePath(Constants.API_PATH);
}
};
}
}
| true |
4066665a990f8e409e1a04eb2e712e87f95e7420 | Java | xuelianhan/basic-algos | /src/main/java/org/ict/algorithm/leetcode/heap/FindKPairsWithSmallestSums.java | UTF-8 | 5,710 | 3.71875 | 4 | [] | no_license | package org.ict.algorithm.leetcode.heap;
import java.util.*;
import java.util.stream.Collectors;
/**
* You are given two integer arrays nums1 and nums2 sorted in ascending order and an integer k.
* Define a pair (u, v) which consists of one element from the first array and one element from the second array.
* Return the k pairs (u1, v1), (u2, v2), ..., (uk, vk) with the smallest sums.
*
* Example 1:
* Input: nums1 = [1,7,11], nums2 = [2,4,6], k = 3
* Output: [[1,2],[1,4],[1,6]]
* Explanation:
* The first 3 pairs are returned from the sequence: [1,2],[1,4],[1,6],[7,2],[7,4],[11,2],[7,6],[11,4],[11,6]
*
* Example 2:
* Input: nums1 = [1,1,2], nums2 = [1,2,3], k = 2
* Output: [[1,1],[1,1]]
* Explanation:
* The first 2 pairs are returned from the sequence: [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
*
* Example 3:
* Input: nums1 = [1,2], nums2 = [3], k = 3
* Output: [[1,3],[2,3]]
* Explanation:
* All possible pairs are returned from the sequence: [1,3],[2,3]
*
* Constraints:
* 1 <= nums1.length, nums2.length <= 10^5
* -10^9 <= nums1[i], nums2[i] <= 10^9
* nums1 and nums2 both are sorted in ascending order.
* 1 <= k <= 10^4
*
* @author sniper
* @date 24 Jun 2023
* LC373, Medium, High Frequency, Top-150
* Amazon, Google, Microsoft
*/
public class FindKPairsWithSmallestSums {
/**
* Understanding the following solution
* Time Cost 38ms
* @param nums1
* @param nums2
* @param k
* @return
*/
public List<List<Integer>> kSmallestPairsV2(int[] nums1, int[] nums2, int k) {
int n = nums1.length;
int m = nums2.length;
List<List<Integer>> res = new ArrayList<>();
PriorityQueue<SumPair> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.sum));
minHeap.offer(new SumPair(0, 0, nums1[0] + nums2[0]));
while (!minHeap.isEmpty() && k > 0) {
SumPair pair = minHeap.poll();
int i = pair.i;
int j = pair.j;
res.add(Arrays.asList(nums1[i], nums2[j]));
k -= 1;
if (i == j) {
if ((i + 1) < n) {
minHeap.offer(new SumPair(i + 1, j, nums1[i + 1] + nums2[j]));
}
if ((j + 1) < m) {
minHeap.offer(new SumPair(i, j + 1, nums1[i] + nums2[j + 1]));
}
if ((i + 1) < n && (j + 1) < m) {
minHeap.offer(new SumPair(i + 1, j + 1, nums1[i + 1] + nums2[j + 1]));
}
} else if (i > j) {
if ((i + 1) < n) {
minHeap.offer(new SumPair(i + 1, j, nums1[i + 1] + nums2[j]));
}
} else {
if ((j + 1) < m) {
minHeap.offer(new SumPair(i, j + 1, nums1[i] + nums2[j + 1]));
}
}
}
return res;
}
/**
* Understanding the following solution
* Time Cost 40ms
* @param nums1
* @param nums2
* @param k
* @return
*/
public List<List<Integer>> kSmallestPairsV1(int[] nums1, int[] nums2, int k) {
PriorityQueue<SumPair> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.sum));
for (int i = 0; i < Math.min(k, nums1.length); i++) {
minHeap.offer(new SumPair(i, 0, nums1[i] + nums2[0]));
}
List<List<Integer>> res = new ArrayList<>();
while (!minHeap.isEmpty() && res.size() < k) {
SumPair pair = minHeap.poll();
int i = pair.i;
int j = pair.j;
res.add(Arrays.asList(nums1[i], nums2[j]));
if (j + 1 < nums2.length) {
minHeap.offer(new SumPair(i, j + 1, nums1[i] + nums2[j + 1]));
}
}
return res;
}
/**
* Understanding the following solution
* @param nums1
* @param nums2
* @param k
* @return
*/
public List<List<Integer>> kSmallestPairs(int[] nums1, int[] nums2, int k) {
PriorityQueue<SumPair> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a.sum));
for (int i = 0; i < k && i < nums1.length; i++) {
minHeap.offer(new SumPair(i, 0, nums1[i] + nums2[0]));
}
List<List<Integer>> res = new ArrayList<>();
while (!minHeap.isEmpty() && res.size() < k) {
int i = minHeap.peek().i;
int j = minHeap.poll().j;
res.add(Arrays.asList(nums1[i], nums2[j]));
if (j + 1 < nums2.length) {
minHeap.offer(new SumPair(i, j + 1, nums1[i] + nums2[j + 1]));
}
}
return res;
}
private static class SumPair {
private int i;
private int j;
private int sum;
public SumPair(int i, int j, int sum) {
this.i = i;
this.j = j;
this.sum = sum;
}
}
/**
* Time Limit Exceeded
* @param nums1
* @param nums2
* @param k
* @return
*/
public List<List<Integer>> kSmallestPairsOutOfTime(int[] nums1, int[] nums2, int k) {
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> b[0] + b[1] - a[0] - a[1]);
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
maxHeap.offer(new int[] {nums1[i], nums2[j]});
if (maxHeap.size() > k) {
maxHeap.poll();
}
}
}
List<List<Integer>> res = new ArrayList<>();
for (int[] item : maxHeap) {
res.add(Arrays.stream(item).boxed().collect(Collectors.toList()));
}
return res;
}
}
| true |
af1175fd4db0e08c0304a9b68818c957387cf8c0 | Java | Melnik-Dmitry/Figures | /figuresFX/src/com/melnik/projectExceptions/InvalidParametrsException.java | UTF-8 | 203 | 2.234375 | 2 | [] | no_license | package com.melnik.projectExceptions;
public class InvalidParametrsException extends Exception {
public InvalidParametrsException() {
super("The specified parameter is incorrect");
}
}
| true |
d4eff9e7c2406adef19497c8c7a800638599e825 | Java | DoraQi/StoodyHelpa | /src/main/java/events/StudyTimeEvent/StudyTimeRecord.java | UTF-8 | 3,597 | 2.90625 | 3 | [] | no_license | package events.StudyTimeEvent;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.bson.Document;
import exceptions.InvalidDocumentException;
import persistence.DBReader;
import persistence.DBWriter;
import persistence.SaveOption;
import persistence.Writable;
/**
* Represents an abstraction for a time instance that is mapped to
* a user ID.
*/
public class StudyTimeRecord implements Writable {
public static final String COLLECTION_NAME = "study_times";
public static final String STUDY_TIME_KEY = "study_time";
public static final String EPOCH_KEY = "epoch";
private static final DBReader reader = new DBReader(COLLECTION_NAME);
private static final DBWriter writer = new DBWriter(COLLECTION_NAME);
private Instant start;
private long studyTime;
private String memberID;
/**
* Loads a study sesssion of a user with a given ID from the database
* @param memberID id of the member whose study session needs to be returned
* @return a StudyTimeSession which contatains the time when user started studying
* @throws InvalidDocumentException thrown to signify that a study session for given user doesn't exist
*/
public static StudyTimeRecord getStudySession(String memberID) throws InvalidDocumentException {
Document doc = reader.loadObject(memberID);
long epoch = doc.getLong(EPOCH_KEY);
long studyTime = doc.getLong(STUDY_TIME_KEY);
StudyTimeRecord session = new StudyTimeRecord(memberID, epoch,studyTime);
return session;
}
@Override
/**
*
* @return a document that contains information about current session
*/
public Document toDoc() {
Document doc = new Document();
doc.put(ACCESS_KEY, memberID);
doc.put(EPOCH_KEY, start.getEpochSecond());
doc.put(STUDY_TIME_KEY, studyTime);
return doc;
}
/**
* Constructs a new StudyTimeSession and saves it to database
* @param memberID the String that contains id of the user to whom this study seesion belongs too
*/
public StudyTimeRecord(String memberID) {
this.memberID = memberID;
this.studyTime = 0;
}
/**
* Constructs a new StudySession
* @param memberID id of the member to whom this session belongs to
* @param epoch an Epoch that points to a specific time
*/
public StudyTimeRecord(String memberID, long epoch, long studyTime) {
this.start = Instant.ofEpochSecond(epoch);
this.memberID = memberID;
this.studyTime = studyTime;
}
/**
* Saves this session to the database
*/
public void trackSession() {
this.start = Instant.now();
DBWriter writer = new DBWriter(COLLECTION_NAME);
writer.saveObject(this, SaveOption.DEFAULT);
}
/**
* Returns the time elapsed between the start of this session and the current time
* @return time elapsed since between start of the session and the current moment
*/
public long finishSession() {
Instant finish = Instant.now();
long timeElapsed = this.start.until(finish, ChronoUnit.SECONDS);
this.studyTime = this.studyTime + timeElapsed;
writer.saveObject(this, SaveOption.DEFAULT);
return timeElapsed;
}
public static void subtractStudyTime(String idAsString, long time) throws InvalidDocumentException {
StudyTimeRecord session = getStudySession(idAsString);
session.studyTime -= time;
writer.saveObject(session, SaveOption.DEFAULT);
}
}
| true |
075abcb108ca05f3cf499dbf3f498f89ec25a95b | Java | ecspresso/open.kattis.com | /1.2/BatterUp/BatterUp.java | UTF-8 | 749 | 3.171875 | 3 | [] | no_license | package batterup;
import java.util.Scanner;
public class BatterUp {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
String atbatsString = inputScanner.nextLine();
int atbats = Integer.parseInt(atbatsString);
String[] basesPerAtbats = inputScanner.nextLine().split(" ");
int walks = 0;
double totalBases = 0;
for(int hit = 0; hit < atbats; hit++) {
if(Double.parseDouble(basesPerAtbats[hit]) == -1) {
walks++;
} else {
totalBases = totalBases + Double.parseDouble(basesPerAtbats[hit]);
}
}
System.out.println(totalBases/(atbats-walks));
}
} | true |
8863ecd1f13059974fe6d4591b84f967337f576f | Java | BlackPreacher/android_md5_sha1_cracker | /app/src/main/java/com/development/black_preacher/md5_sha1_cracker/MainActivity.java | UTF-8 | 4,138 | 2.296875 | 2 | [] | no_license | package com.development.black_preacher.md5_sha1_cracker;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
Log.d(TAG, "Key: " + key + " Value: " + value);
}
}
// [END handle_data_extras]
Button subscribeButton = (Button) findViewById(R.id.subscribeButton);
subscribeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// [START subscribe_topics]
FirebaseMessaging.getInstance().subscribeToTopic("news");
Log.i(TAG, "Subscribed to news topic");
// [END subscribe_topics]
}
});
Button logTokenButton = (Button) findViewById(R.id.logTokenButton);
logTokenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "InstanceID token: " + FirebaseInstanceId.getInstance().getToken());
}
});
}
public void calculate_plain(View v) {
//String linkip = "http://[2a02:908:dc41:200:b1b7:6ec9:7164:e96e]";
String linkip = "http://blackpreacher.bplaced.net/";
String hash = "";
EditText ed_hash = (EditText)findViewById(R.id.hash_edit);
TextView result_view = (TextView) findViewById(R.id.result_view);
hash = ed_hash.getText().toString();
String result = "";
try {
HashMap<String,String> tmp = new HashMap<>();
tmp.put("url",linkip+"/tools/solve_plain.php");
tmp.put("hash",hash);
result = new NetworkOperations().execute(tmp).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
final JSONArray jArray_ein;
try {
jArray_ein = new JSONArray(result);
final int laenge_ein = jArray_ein.length();
Log.i("Main",Integer.toString(laenge_ein));
if(laenge_ein > 0) {
for (int i = 0; i < laenge_ein; i++) {
JSONObject data;
data = jArray_ein.getJSONObject(i);
String plain = data.getString("plain");
result_view.setText("The password you searched is: " + plain);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(result_view.getWindowToken(),0);
}
} else {
result_view.setText("Sorry, I cant crack this password");
}
} catch (JSONException e) {
if(result.equals("no_connection")){
result_view.setText("Sorry, but I need connection to the Server");
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(result_view.getWindowToken(),0);
} else {
e.printStackTrace();
}
}
}
}
| true |
6bafc0bf8c0adc0756f053048831f846d5f6766b | Java | msdgwzhy6/FengHuangNews | /FengHuangNew/app/src/main/java/momo/com/week10_project/fragment/NewsItemFragment.java | UTF-8 | 18,811 | 1.898438 | 2 | [] | no_license | package momo.com.week10_project.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import java.util.ArrayList;
import java.util.List;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import momo.com.week10_project.R;
import momo.com.week10_project.adapter.AbstractBaseAdapter;
import momo.com.week10_project.entity.NewsTopEntity;
import momo.com.week10_project.news_interface.NewsInterface;
import momo.com.week10_project.ui.NewsTopContent_Activity;
import momo.com.week10_project.utils.Constant;
import momo.com.week10_project.utils.ManagerApi;
import momo.com.week10_project.utils.TimeUtils;
import momo.com.week10_project.widget.BannerView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* 新闻--头条fragment,有顶置的专题 单图(含不置顶的专题) 多图 新闻轮播 视频
*/
public class NewsItemFragment extends Fragment implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener {
//当前时间的月日
private String currentData;
//标识:初次进入default,上拉加载更多up,下拉刷新down
private String action = "default";
//标识:是否初次进入,针对刷新头
private boolean flag = true;
//标识:是否加载更多
private boolean isAddMore = false;
private PtrClassicFrameLayout refresh;
private ListView lv;
//新闻轮播View
private BannerView<NewsTopEntity.ItemEntity> bannerView;
private AbstractBaseAdapter<NewsTopEntity.ItemEntity> adapter;
//所有的itemlist
private List<NewsTopEntity.ItemEntity> totalList;
//放置顶专题的itemlist
private List<NewsTopEntity.ItemEntity> topList;
//只放普通新闻的itemlist
private List<NewsTopEntity.ItemEntity> itemList;
//放新闻轮播的itemlist
private List<NewsTopEntity.ItemEntity> bannerList;
@Override
public void onCreate(@Nullable Bundle bundle) {
super.onCreate(bundle);
initData();
}
//初始化数据源及adapter
private void initData() {
totalList = new ArrayList<>();
itemList = new ArrayList<>();
topList = new ArrayList<>();
bannerList = new ArrayList<>();
adapter = new AbstractBaseAdapter<NewsTopEntity.ItemEntity>(getActivity(), totalList,
R.layout.news_content_layout1, R.layout.news_content_layout2,
R.layout.news_content_layout3, R.layout.news_content_layout4) {
@Override
public void bindData(int position, ViewHolder holder) {
NewsTopEntity.ItemEntity itemEntity = totalList.get(position);
int type = totalList.get(position).getViewType();
switch (type) {
//单图布局或不置顶的专题
case 0: {
//图片
ImageView iv = (ImageView) holder.findViewById(R.id.news_lv1_iv);
Glide.with(getActivity()).load(itemEntity.getThumbnail()).into(iv);
//标题
TextView tv_title = (TextView) holder.findViewById(R.id.news_lv1_title);
tv_title.setText(itemEntity.getTitle());
//来源与时间
TextView tv_source = (TextView) holder.findViewById(R.id.news_lv1_source);
if (itemEntity.getSource()!=null) {
tv_source.setText(itemEntity.getSource() + " " + getUpdateTime(itemEntity.getUpdateTime()));
}else{
//不置顶的专题
itemEntity.setSource(Constant.Top_TITLE);
tv_source.setText(itemEntity.getSource());
}
}
break;
//多图布局
case 1: {
//标题
TextView tv_title = (TextView) holder.findViewById(R.id.news_lv2_title);
tv_title.setText(itemEntity.getTitle());
//图片
List<String> imagesUrl = itemEntity.getStyle().getImages();
ImageView iv1 = (ImageView) holder.findViewById(R.id.news_lv2_iv1);
ImageView iv2 = (ImageView) holder.findViewById(R.id.news_lv2_iv2);
ImageView iv3 = (ImageView) holder.findViewById(R.id.news_lv2_iv3);
Glide.with(getActivity()).load(imagesUrl.get(0)).into(iv1);
Glide.with(getActivity()).load(imagesUrl.get(1)).into(iv2);
Glide.with(getActivity()).load(imagesUrl.get(2)).into(iv3);
//来源与时间
TextView tv_source = (TextView) holder.findViewById(R.id.news_lv2_source);
tv_source.setText(itemEntity.getSource() + " " + getUpdateTime(itemEntity.getUpdateTime()));
}
break;
//专题布局(置顶)
case 2: {
//图片
ImageView iv = (ImageView) holder.findViewById(R.id.news_lv3_iv);
Glide.with(getActivity()).load(itemEntity.getThumbnail()).into(iv);
//标题
TextView tv_title = (TextView) holder.findViewById(R.id.news_lv3_title);
tv_title.setText(itemEntity.getTitle());
//评论数
TextView tv_comments = (TextView) holder.findViewById(R.id.news_lv3_comments);
tv_comments.setText(itemEntity.getCommentsall());
}
break;
//视频布局
case 3: {
//标题
TextView tv_title = (TextView) holder.findViewById(R.id.news_lv4_title);
tv_title.setText(itemEntity.getTitle());
//图片
ImageView iv = (ImageView) holder.findViewById(R.id.news_lv4_iv_thumb);
Glide.with(getActivity()).load(itemEntity.getThumbnail()).into(iv);
//视频时长
TextView tv_videoTime = (TextView) holder.findViewById(R.id.news_lv4_tv_videotime);
tv_videoTime.setText(TimeUtils.getVideoTime(itemEntity.getPhvideo().getLength()));
//来源
TextView tv_source = (TextView) holder.findViewById(R.id.news_lv4_source);
tv_source.setText(itemEntity.getPhvideo().getChannelName());
//评论数
TextView tv_comments = (TextView) holder.findViewById(R.id.news_lv4_comments);
tv_comments.setText(itemEntity.getCommentsall());
}
}
}
@Override
public int getItemViewType(int position) {
int tmpType = totalList.get(position).getViewType();
return tmpType;
}
};
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_item, container, false);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//初始化控件
setupViews(view);
}
private void setupViews(View view) {
lv = (ListView) view.findViewById(R.id.newstop_lv);
lv.setAdapter(adapter);
//还是首次加载数据,viewpager切换回来,广告保留(若用原来的bannerView切换不流畅,不知道为什么?所以在ondestoryView将bannerView=null)
if(bannerList.size()>0&& action.equals("default")){
bannerView = new BannerView<NewsTopEntity.ItemEntity>(getActivity(),bannerList) {
@Override
public void bindData(Banner banner, List<NewsTopEntity.ItemEntity> list) {
List<String> imgUrls = new ArrayList<String>();
List<String> titles = new ArrayList<String>();
for (NewsTopEntity.ItemEntity i : list) {
imgUrls.add(i.getThumbnail());
titles.add(i.getTitle());
}
//设置banner的图片集合及标题集合
banner.setImages(imgUrls);
banner.setBannerTitles(titles);
//banner配置完成,开始轮播
banner.start();
}
};
lv.addHeaderView(bannerView,null,false);
}
//listview item点击事件
lv.setOnItemClickListener(this);
//listview 滚动监听
lv.setOnScrollListener(this);
refresh = (PtrClassicFrameLayout) view.findViewById(R.id.news_refresh);
refresh.setLastUpdateTimeRelateObject(this);
//初次进来,自动刷新
if(flag ==true) {
//在刷新头控件加载完成后 ,自动刷新。
refresh.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int width = refresh.getWidth();
if (width > 0) {
refresh.autoRefresh(true);
//api>=16
refresh.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
}
//刷新头的监听
refresh.setPtrHandler(new PtrDefaultHandler() {
@Override
public void onRefreshBegin(PtrFrameLayout frame) {
//判断是首次还是人为的下拉刷新
action = flag == true ? "default" : "down";
flag = false;
//获取数据
getNewsData();
}
//解决刷新控件与listview的滑动冲突
@Override
public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
return super.checkCanDoRefresh(frame, lv, header);
}
});
}
private void getNewsData() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ManagerApi.BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
NewsInterface newsInterface = retrofit.create(NewsInterface.class);
Call<List<NewsTopEntity>> call = newsInterface.getTopEntity(action);
call.enqueue(new Callback<List<NewsTopEntity>>() {
@Override
public void onResponse(Call<List<NewsTopEntity>> call, Response<List<NewsTopEntity>> response) {
//非首次自动加载数据,移除广告
if(bannerView!=null&& !action.equals("default")){
lv.removeHeaderView(bannerView);
bannerView =null;
}
List<NewsTopEntity> entity = response.body();
for (int i = 0; i < entity.size(); i++) {
switch (entity.get(i).getType()) {
//普通新闻
case "list": {
//人为下拉刷新
if (action.equals("down")) {
itemList.clear();
//去掉专题
if(totalList.size()>0) {
if (totalList.get(0).getViewType() == 2) {
totalList.remove(0);
}
}
}
for (int j = 0; j < entity.get(i).getItem().size(); j++) {
//单图
if (entity.get(i).getItem().get(j).getStyle() == null && entity.get(i).getItem().get(j).getPhvideo() == null) {
entity.get(i).getItem().get(j).setViewType(0);
}
//多图
else if (entity.get(i).getItem().get(j).getStyle() != null) {
entity.get(i).getItem().get(j).setViewType(1);
}
//视频
else {
entity.get(i).getItem().get(j).setViewType(3);
}
}
//下拉刷新,最新数据放到最前面。首先,这里先把之前的数据放到itemlist。最后(在for循环体外面),把itemlist 加到totallist
if (action.equals("down")) {
itemList.addAll(entity.get(i).getItem());
itemList.addAll(totalList);
} else {
//上拉加载更多(在for循环体外面),直接加到totallist
itemList.addAll(entity.get(i).getItem());
}
}
break;
//轮播新闻
case "focus": {
bannerList.addAll(entity.get(i).getItem());
bannerView = new BannerView<NewsTopEntity.ItemEntity>(getActivity(),bannerList) {
@Override
public void bindData(Banner banner, List<NewsTopEntity.ItemEntity> list) {
List<String> imgUrls = new ArrayList<String>();
List<String> titles = new ArrayList<String>();
for (NewsTopEntity.ItemEntity i : list){
imgUrls.add(i.getThumbnail());
titles.add(i.getTitle());
}
//设置banner的图片集合及标题集合
banner.setImages(imgUrls);
banner.setBannerTitles(titles);
//banner配置完成,开始轮播
banner.start();
}
};
lv.addHeaderView(bannerView,null,false);
}
break;
//专题新闻
case "top": {
for (int j = 0; j < entity.get(i).getItem().size(); j++) {
entity.get(i).getItem().get(j).setViewType(2);
}
topList.addAll(entity.get(i).getItem());
}
break;
}
}
//获取当前时间
currentData = null;
currentData = TimeUtils.getCurrentTime();
totalList.clear();
if (action.equals("default")) {
totalList.addAll(topList);
}
totalList.addAll(itemList);
adapter.notifyDataSetChanged();
refresh.refreshComplete();
}
@Override
public void onFailure(Call<List<NewsTopEntity>> call, Throwable t) {
refresh.refreshComplete();
}
});
}
//listview item的点击事件
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// String itemId = totalList.get(position-lv.getHeaderViewsCount()).getId();
// String commentsUrl = totalList.get(position-lv.getHeaderViewsCount()).getCommentsUrl();
// int viewType = totalList.get(position-lv.getHeaderViewsCount()).getViewType();
// String title = totalList.get(position-lv.getHeaderViewsCount()).getTitle();
String webUrl = totalList.get(position-lv.getHeaderViewsCount()).getLink().getWeburl();
Intent intent = new Intent(getActivity(),NewsTopContent_Activity.class);
// intent.putExtra(Constant.ITEM_ID,itemId);
// intent.putExtra(Constant.ITEM_COMMENTSURL,commentsUrl);
// intent.putExtra(Constant.ITEM_VIEWTYPE,viewType);
// intent.putExtra(Constant.ITEM_TITLE,title);
intent.putExtra(Constant.ITEM_WEBURL,webUrl);
startActivity(intent);
}
private String getUpdateTime(String sourceTime) {
if (sourceTime == null) {
return null;
}
if (sourceTime.contains(currentData)) {
//返回时分
return sourceTime.substring(12, 16);
} else {
//返回月日
return sourceTime.substring(5, 10);
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (isAddMore && scrollState == SCROLL_STATE_IDLE) {
action = "up";
getNewsData();
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount == totalItemCount) {
isAddMore = true;
} else {
isAddMore = false;
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
if(bannerView!=null) {
lv.removeHeaderView(bannerView);
bannerView = null;
}
}
}
| true |
886076e82bba7ed9bf93997ba80f96f97ee18768 | Java | chirag1998/POC | /Customer/src/main/java/com/xoriant/bank/service/BankServiceImpl.java | UTF-8 | 1,706 | 2.15625 | 2 | [] | no_license | package com.xoriant.bank.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xoriant.bank.dao.BankDao;
import com.xoriant.bank.model.Account;
import com.xoriant.bank.model.Transactions;
import com.xoriant.bank.model.Userdetails;
@Service
public class BankServiceImpl implements BankService {
@Autowired
private BankDao bankDao;
@Override
public float GetBalance(int accountnumber) {
// TODO Auto-generated method stub
if(accountnumber<0)
{
return 0;
}
else {
return bankDao.GetBalance(accountnumber);
}
}
@Override
public List<Account> getaccount(int customerid)
{
if(customerid<0)
{
return null;
}
else {
return bankDao.getaccount(customerid);
}
}
@Override
public Userdetails addUserdetails(Userdetails userdetails,String emailid)
{
if(userdetails==null && emailid.equals(""))
{
return null;
}
else {
return bankDao.addUserdetails(userdetails, emailid);
}
}
@Override
public List<Transactions> getministatement(int accountnumber)
{
if(accountnumber<0)
{
return null;
}
else {
return bankDao.getministatement(accountnumber);
}
}
@Override
public String changepassword(String username,String newpassword)
{
if(username.equalsIgnoreCase("") || newpassword.equalsIgnoreCase(""))
{
return "Invalid Details";
}
else {
return bankDao.changepassword(username, newpassword);
}
}
@Override
public List<Transactions> customreport (String start,String end)
{
if(start.equalsIgnoreCase("") && end.equalsIgnoreCase(""))
{
return null;
}
{
return bankDao.customreport(start, end);
}
}
}
| true |
9f3ee8cf91599ca1edff1402ab4c86651d81aa26 | Java | EmilHernvall/tregmine | /bungee/Hub Plugin/src/info/tregmine/hub/listeners/BoostListener.java | UTF-8 | 1,939 | 2.59375 | 3 | [
"BSD-4-Clause"
] | permissive | package info.tregmine.hub.listeners;
import java.util.ArrayList;
import info.tregmine.hub.Hub;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;
public class BoostListener implements Listener
{
private Hub plugin;
public BoostListener(Hub instance)
{
this.plugin = instance;
}
private ArrayList<Player> boosters = new ArrayList<Player>();
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
Location playerLoc = player.getLocation();
Material check = playerLoc.getWorld().getBlockAt(playerLoc).getRelative(0, -2, 0).getType();
Material plate = playerLoc.getWorld().getBlockAt(playerLoc).getType();
if (check != Material.EMERALD_BLOCK){
return;
}
if (plate != Material.GOLD_PLATE &&
plate != Material.IRON_PLATE &&
plate != Material.STONE_PLATE &&
plate != Material.WOOD_PLATE){
return;
}
//Launch the player
player.setVelocity(player.getLocation().getDirection().multiply(4));
player.setVelocity(new Vector(player.getVelocity().getX(), 1.5D, player.getVelocity().getZ()));
boosters.add(player);
}
@EventHandler
public void onPlayerDamage(EntityDamageEvent e) {
if (e.getEntity() instanceof Player) {
Player p = (Player) e.getEntity();
if (e.getCause() == DamageCause.FALL && boosters.contains(p)) {
e.setDamage(0.0);
boosters.remove(p);
}
}
}
@EventHandler
public void onPortalCreate(BlockPhysicsEvent e) {
if(e.getBlock().getType() == Material.PORTAL){
e.setCancelled(true);
}
}
} | true |
e86ea66e0456ab210dc9708122afa98f7e61bd14 | Java | BenRaguckas/Y2_SoftwareDev2_Lab_7 | /src/Building.java | UTF-8 | 2,553 | 3.453125 | 3 | [] | no_license | class Building implements Walls, Roof{
private int walls;
private String roof;
public Building(){
this.roof = ROOF_DEFAULT;
this.walls = WALLS_DEFAULT;
}
public Building(int walls, String roof){
this.walls = walls;
this.roof = roof;
}
@Override
public String getRoof() {
return roof;
}
@Override
public void setRoof(String roof) {
this.roof = roof;
}
@Override
public int getWalls() {
return walls;
}
@Override
public void setWalls(int walls) {
this.walls = walls;
}
@Override
public String toString() {
return "Building " +
"walls = " + walls +
", roof = '" + roof + "'.";
}
}
class House extends Building implements Rooms {
private int rooms;
public House(){
super();
this.rooms = ROOMS_DEFAULT;
}
public House(int walls, String roof, int rooms){
super(walls, roof);
this.rooms = rooms;
}
@Override
public int getRooms() {
return rooms;
}
@Override
public void setRooms(int rooms) {
this.rooms = rooms;
}
@Override
public String toString() {
return super.toString() + " Type = House, " + "rooms = " + rooms + ".";
}
}
class ApartmentBlock extends Building implements Units {
private int units;
public ApartmentBlock(){
super();
this.units = UNITS_DEFAULT;
}
public ApartmentBlock(int walls, String roof, int units) {
super(walls, roof);
this.units = units;
}
@Override
public int getUnits() {
return units;
}
@Override
public void setUnits(int units) {
this.units = units;
}
@Override
public String toString() {
return super.toString() + " Type = Apartment Block, " + "Units = " + units + ".";
}
}
class OfficeBlock extends Building implements Cubicles {
int cubicles;
public OfficeBlock(){
super();
this.cubicles = CUBICLES_DEFAULT;
}
public OfficeBlock(int walls, String roof, int cubicles) {
super(walls, roof);
this.cubicles = cubicles;
}
@Override
public int getCubicles() {
return cubicles;
}
@Override
public void setCubicles(int cubicles) {
this.cubicles = cubicles;
}
@Override
public String toString() {
return super.toString() + " Type = Office Block, " + "Cubicles = " + cubicles + ".";
}
} | true |
a1598d88c865323d2fc1aca2b29026d6b17448f1 | Java | Spaicat/IUT-S4-Cryptage | /TD_TP/Crypto_nite/src/crypto/algorithmes/generateurdecles/GenerateurDeClesCesar.java | UTF-8 | 1,061 | 2.78125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package crypto.algorithmes.generateurdecles;
import crypto.donnees.cles.CleInteger;
import crypto.donnees.cles.Cles;
import java.util.Random;
/**
*
* @author Antonia, Thibault
*/
public class GenerateurDeClesCesar {
//Attribut
private Cles cles;
/**
*
* @return null car il n'y a pas de clé publique dans ces algo
*/
public Cles genererClePublique(){
return null;
}
/**
* Genere la cle privée
* @return un attribut de type Cles (liste de clés privées)
*/
public Cles genererClePrivee(){
if (this.cles == null) {
Random random = new Random();
int nbAleatoire = random.nextInt(25);
this.cles = new Cles();
this.cles.addCle("cleCesar", new CleInteger(nbAleatoire));
}
return this.cles;
}
}
| true |
1fd5d8a8a1a6296c0f3f4d9401430a7a65ca4854 | Java | PanzariuAdi/Proiect-IP | /Baza de date/src/test/java/DatabaseTest/AsistentTest.java | UTF-8 | 3,890 | 2.640625 | 3 | [] | no_license | package DatabaseTest;
import DAOClasses.DAO;
import DAOClasses.Database;
import DAOClasses.Asistent;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
class AsistentTest {
private Database db = Database.getInstance();
private DAO p = new Asistent();
private List<String> actual = new ArrayList<>();
private List<String> expected = new ArrayList<>();
@Test
@DisplayName("Should insert an asistent document into the DB")
void asistentInsert() throws Exception {
db.connectToDatabase();
//TEST FOR DATA INSERTION
p.insertIntoDB("1990505000000", "neuro", "test");
expected.add("neuro");
expected.add("test");
for (Map.Entry<String, Object> entry : p.getDocumentByID("1990505000000").entrySet()) {
actual.add(entry.getValue().toString());
}
Assertions.assertLinesMatch(expected, actual);
actual.clear();
expected.clear();
}
@Test
@DisplayName("Should update a document")
void asistentUpdate() throws Exception {
db.connectToDatabase();
//TEST FOR DATA UPDATE
p.updateInDB("1990505000000", "sectie", "junior");
expected.add("junior");
expected.add("test");
for (Map.Entry<String, Object> entry : p.getDocumentByID("1990505000000").entrySet()) {
actual.add(entry.getValue().toString());
}
Assertions.assertLinesMatch(expected, actual);
actual.clear();
expected.clear();
}
@Test
@DisplayName("Should remove a document")
void asistentRemove() throws Exception {
db.connectToDatabase();
//TEST FOR DATA REMOVAL
p.removeFromDB("1990505000000");
for (Map.Entry<String, Object> entry : p.getDocumentByID("1990505000000").entrySet()) {
actual.add(entry.getValue().toString());
}
Assertions.assertLinesMatch(new ArrayList<String>(), actual);
actual.clear();
expected.clear();
}
@Test
@DisplayName("Should get a document by field")
void asistentGetDocByField() throws Exception {
db.connectToDatabase();
for (Map<String, Object> map : p.getDocumentByField("sectie", "junior")) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
actual.add(entry.getValue().toString());
}
}
expected.add("junior");
expected.add("test");
Assertions.assertLinesMatch(expected, actual);
actual.clear();
expected.clear();
}
@Test
@DisplayName("Should get a document by ID")
void asistentGetDocByID() throws Exception {
db.connectToDatabase();
for (Map.Entry<String, Object> entry : p.getDocumentByID("1990505000000").entrySet()) {
actual.add(entry.getValue().toString());
}
expected.add("junior");
expected.add("test");
Assertions.assertLinesMatch(expected, actual);
actual.clear();
expected.clear();
}
@Test
@DisplayName("Should get a collection")
void asistentGetCollection() throws Exception {
db.connectToDatabase();
for (Map<String, Object> map : p.getCollection()) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
actual.add(entry.getValue().toString());
}
}
expected.add("junior");
expected.add("test");
expected.add("neurologie");
expected.add(" test");
Assertions.assertLinesMatch(expected, actual);
actual.clear();
expected.clear();
}
} | true |
129003d5587c96b1bcebd8da8e93212e72a988ea | Java | edwarddes/OATimer | /src/com/desparddesign/orienteering/codechecking/sportident/commands/GetTime.java | UTF-8 | 383 | 2.046875 | 2 | [] | no_license | package com.desparddesign.orienteering.codechecking.sportident.commands;
import com.desparddesign.orienteering.codechecking.sportident.SICommandPacket;
public class GetTime extends SICommand
{
public GetTime()
{
}
public SICommandPacket rawPacket()
{
SICommandPacket packet = new SICommandPacket();
packet.setCommand(0xF7);
packet.setLength(0);
return packet;
}
}
| true |
8a449accb387562164ffc43cc5382db6391c4132 | Java | agrandea/Dead_Meme | /Main Clicker Concept/TestUpper.java | UTF-8 | 1,061 | 2.984375 | 3 | [] | no_license | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//test to see how HarabmeResearchers or any other passive click can add buttons
//to a seperate JFrame
public class TestUpper extends JFrame
{
private final long serialVersionUID = 1L;
protected JFrame MainJF;
protected JPanel MainJP;
public TestUpper()
{
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
createAndShowGUI();
}
});
}
private void createAndShowGUI() {
/*
MainJF = new JFrame();
MainJF.setExtendedState(JFrame.MAXIMIZED_BOTH);
MainJF.setUndecorated(true);
MainJF.setVisible(true);
MainJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
*/
MainJP = new JPanel();
setSize(1600,1000);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(MainJP);
setVisible(true);
}
}
| true |
20e6229d390bd6c25921d4ff1c741f0ee65227f3 | Java | Techmomentous/GTTracker | /src/com/gt/dbtools/LocationDB.java | UTF-8 | 19,628 | 2.5625 | 3 | [] | no_license | package com.gt.dbtools;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.gt.db.DBConfig;
import com.gt.db.DBProvider;
import com.gt.logs.LogUtility;
import com.gt.pojo.LocationData;
public class LocationDB {
private static final String LOG_TAG = "LocationDB";
private DBProvider provider;
private Connection connection;
private Statement statement;
int AutoID = 0;
private MembersDB membersDB;
public LocationDB() {
provider = new DBProvider();
}
/**
* Add new Location of given member id and return the auto-generated keys
*
* @param locationData
* @param memberid
* @return
*/
public int addNewLocation(LocationData locationData) {
try {
String query = "INSERT INTO "
+ DBConfig.getLocationTable()
+ " (`memberid`,`latitude`,`longitude`,`place`,`extrainfo`,`username`,`distance`,`date`,`direction`,`accuracy`,`phoneumber`,`speed`,`locationmethod`) VALUES( "
+ locationData.getMemberid() + " , '" + locationData.getLatitude() + "' , '"
+ locationData.getLongitude() + "' , '" + locationData.getPlace() + "' , '"
+ locationData.getExtrainfo() + "' , '" + locationData.getUsername() + "' , '"
+ locationData.getDistance() + "' , '" + locationData.getDate() + "' , '"
+ locationData.getDirection() + "' , '" + locationData.getAccuaracy() + "' , '"
+ locationData.getPhonenumber() + "' , '" + locationData.getSpeed() + "' , '"
+ locationData.getLocationMethod() + "');";
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
PreparedStatement statement = connection.prepareStatement(query,
Statement.RETURN_GENERATED_KEYS);
int affectedRows = statement.executeUpdate();
if (affectedRows > 0) {
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
AutoID = resultSet.getInt(1);
LogUtility.LogInfo("Location Added of Member " + locationData.getMemberid(),
LOG_TAG);
}
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Adding Location of : " + locationData.getMemberid()
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Adding Location of : " + locationData.getMemberid()
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError(
"Error While Adding Location of : " + locationData.getMemberid()
+ " Error : " + e, LOG_TAG);
}
}
return AutoID;
}
/**
* Update location data of given user name
*
* @param locationData
* @param username
* @return
*/
public boolean updateLocationByUsername(LocationData locationData, String username) {
try {
String query = "UPDATE " + DBConfig.getLocationTable() + " SET `LATITUDE` = '"
+ locationData.getLatitude() + " ',`LONGITUDE` = '"
+ locationData.getLongitude() + "' , `PLACE` = '" + locationData.getPlace()
+ "' ,`EXTRAINFO` = '" + locationData.getExtrainfo() + "', `DISTANCE` = '"
+ locationData.getDistance() + "' , `DATE` = '" + locationData.getDate()
+ "' , `DIRECTION` = '" + locationData.getDirection() + "',`ACCURACY` = '"
+ locationData.getAccuaracy() + "' , `PHONEUMBER` = '"
+ locationData.getPhonenumber() + "',`SPEED` = '" + locationData.getSpeed()
+ "', `LOCATIONMETHOD` = '" + locationData.getLocationMethod()
+ "' WHERE `USERNAME` = '" + username + "';";
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
statement = connection.createStatement();
// Execute the query and get the result set
int rowCount = statement.executeUpdate(query);
if (rowCount > 0) {
return true;
}
}
catch (NullPointerException e) {
LogUtility.LogError(
"Error While Updating Location Data of : " + locationData.getUsername()
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError(
"Error While Update Location Data of : " + locationData.getUsername()
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError(
"Error While Update Location Data of : " + locationData.getUsername()
+ " Error : " + e, LOG_TAG);
}
}
return false;
}
/**
* Update the location data of given memberid
*
* @param locationData
* @param memberid
* @return
*/
public synchronized boolean updateLocationByMemberID(LocationData locationData, int memberid) {
try {
String query = "UPDATE " + DBConfig.getLocationTable() + " SET `LATITUDE` = '"
+ locationData.getLatitude() + " ',`LONGITUDE` = '"
+ locationData.getLongitude() + "' , `PLACE` = '" + locationData.getPlace()
+ "' ,`EXTRAINFO` = '" + locationData.getExtrainfo() + "', `DISTANCE` = '"
+ locationData.getDistance() + "' , `DATE` = '" + locationData.getDate()
+ "' , `DIRECTION` = '" + locationData.getDirection() + "',`ACCURACY` = '"
+ locationData.getAccuaracy() + "' , `SPEED` = '" + locationData.getSpeed()
+ "', `LOCATIONMETHOD` = '" + locationData.getLocationMethod()
+ "' WHERE `MEMBERID` = '" + memberid + "';";
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
statement = connection.createStatement();
// Execute the query and get the result set
int rowCount = statement.executeUpdate(query);
if (rowCount > 0) {
return true;
}
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Adding Location of : " + locationData.getUsername()
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Adding Location of : " + locationData.getUsername()
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Adding Location of : " + e, LOG_TAG);
}
}
return false;
}
/**
* Retrieve the location data of given member id
*
* @param memberid
*/
public LocationData getLocationByMemberID(int memberid) {
LocationData location = null;
try {
location = new LocationData();
String query = "SELECT * FROM " + DBConfig.getLocationTable() + " WHERE MEMBERID= "
+ memberid;
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
statement = connection.createStatement();
// Execute the query and get the result set
ResultSet resultSet = statement.executeQuery(query);
// Check the result row count if greater than 0 means lecture
// details are found. Set the success flag to true.
// Check if resultset has a row
if (resultSet.next()) {
location.setIdlocation(resultSet.getInt(1));
location.setMemberid(resultSet.getInt(2));
location.setLongitude(resultSet.getString(3));
location.setLatitude(resultSet.getString(4));
location.setPlace(resultSet.getString(5));
location.setExtrainfo(resultSet.getString(6));
location.setUsername(resultSet.getString(7));
location.setDistance(resultSet.getString(8));
location.setDate(resultSet.getString(9));
location.setDirection(resultSet.getString(10));
location.setAccuaracy(resultSet.getString(11));
location.setPhonenumber(resultSet.getString(12));
location.setSpeed(resultSet.getString(13));
location.setLocationMethod(resultSet.getString(14));
LogUtility.LogInfo("Got Location : " + location, LOG_TAG);
}
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Getting Location of member id :" + memberid
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Getting Location of member id :" + memberid
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting Location of member id :" + memberid
+ " Error : " + e, LOG_TAG);
}
}
return location;
}
/**
* Retrieve the location data of given member id and returnt the location
* json
*
* @param memberid
*/
public JsonObject getLocationJSONByMemberID(int memberid) {
JsonObject locationJson = null;
try {
String query = "SELECT * FROM " + DBConfig.getLocationTable() + " WHERE MEMBERID= "
+ memberid;
if (provider == null) {
provider = new DBProvider();
}
membersDB = new MembersDB();
// Initialize the connection and statement
if (connection == null) {
connection = provider.getConnection();
}
statement = connection.createStatement();
// Execute the query and get the result set
ResultSet resultSet = statement.executeQuery(query);
// Check the result row count if greater than 0 means lecture
// details are found. Set the success flag to true.
// Check if resultset has a row
if (resultSet.next()) {
locationJson = new JsonObject();
locationJson.addProperty("locationid", resultSet.getInt(1));
locationJson.addProperty("memberid", resultSet.getInt(2));
locationJson.addProperty("latitude", resultSet.getString(3));
locationJson.addProperty("longitude", resultSet.getString(4));
locationJson.addProperty("place", resultSet.getString(5));
locationJson.addProperty("extrainfo", resultSet.getString(6));
locationJson.addProperty("username", resultSet.getString(7));
locationJson.addProperty("distance", resultSet.getString(8));
locationJson.addProperty("date", resultSet.getString(9));
locationJson.addProperty("direction", resultSet.getString(10));
locationJson.addProperty("accuarcy", resultSet.getString(11));
locationJson.addProperty("phone", resultSet.getString(12));
locationJson.addProperty("speed", resultSet.getString(13));
locationJson.addProperty("locationMethod", resultSet.getString(14));
// Get the member picture
String picture = membersDB.getMemberPicByID(memberid);
locationJson.addProperty("markerpic", picture);
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting Location of member id :" + memberid
+ " Error : " + e, LOG_TAG);
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Getting Location of member id :" + memberid
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Getting Location of member id :" + memberid
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting All Member: Error : " + e.getMessage(),
LOG_TAG);
}
}
return locationJson;
}
/**
* Retrieve the location data of all members json
*
* @param memberid
*/
public JsonArray getAllMembersLocationJSON() {
JsonArray locationArrayJson = null;
try {
String query = "SELECT * FROM " + DBConfig.getLocationTable() + ";";
if (provider == null) {
provider = new DBProvider();
}
membersDB = new MembersDB();
// Initialize the connection and statement
if (connection == null) {
connection = provider.getConnection();
}
statement = connection.createStatement();
// Execute the query and get the result set
ResultSet resultSet = statement.executeQuery(query);
// Check the result row count if greater than 0 means lecture
// details are found. Set the success flag to true.
// Check if resultset has a row
locationArrayJson = new JsonArray();
while (resultSet.next()) {
JsonObject locationJson = new JsonObject();
locationJson.addProperty("locationid", resultSet.getInt(1));
int memberid = resultSet.getInt(2);
locationJson.addProperty("memberid", memberid);
locationJson.addProperty("latitude", resultSet.getString(3));
locationJson.addProperty("longitude", resultSet.getString(4));
locationJson.addProperty("place", resultSet.getString(5));
locationJson.addProperty("extrainfo", resultSet.getString(6));
locationJson.addProperty("username", resultSet.getString(7));
locationJson.addProperty("distance", resultSet.getString(8));
locationJson.addProperty("date", resultSet.getString(9));
locationJson.addProperty("direction", resultSet.getString(10));
locationJson.addProperty("accuarcy", resultSet.getString(11));
locationJson.addProperty("phone", resultSet.getString(12));
locationJson.addProperty("speed", resultSet.getString(13));
locationJson.addProperty("locationMethod", resultSet.getString(14));
// Get the member picture
String picture = membersDB.getMemberPicByID(memberid);
locationJson.addProperty("markerpic", picture);
locationArrayJson.add(locationJson);
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting All Members Location :" + " Error : " + e,
LOG_TAG);
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Getting All Members Location :" + " Error : " + e,
LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Getting All Members Location :" + " Error : " + e,
LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting All Members Location :" + " Error : " + e,
LOG_TAG);
}
}
return locationArrayJson;
}
/**
* Retrieve the location data of given user name
*
* @param username
* @return
*/
public LocationData getLocationByUserName(String username) {
LocationData location = null;
try {
location = new LocationData();
String query = "SELECT * FROM " + DBConfig.getLocationTable() + " WHERE USERNAME= "
+ username;
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
statement = connection.createStatement();
// Execute the query and get the result set
ResultSet resultSet = statement.executeQuery(query);
// Check the result row count if greater than 0 means lecture
// details are found. Set the success flag to true.
// Check if resultset has a row
if (resultSet.next()) {
location.setIdlocation(resultSet.getInt(1));
location.setMemberid(resultSet.getInt(2));
location.setLongitude(resultSet.getString(3));
location.setLatitude(resultSet.getString(4));
location.setPlace(resultSet.getString(5));
location.setExtrainfo(resultSet.getString(6));
location.setUsername(resultSet.getString(7));
location.setDistance(resultSet.getString(8));
location.setDate(resultSet.getString(9));
location.setDirection(resultSet.getString(10));
location.setAccuaracy(resultSet.getString(11));
location.setPhonenumber(resultSet.getString(12));
location.setSpeed(resultSet.getString(13));
location.setLocationMethod(resultSet.getString(14));
LogUtility.LogInfo("Got Location : " + location, LOG_TAG);
}
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Getting Location By user name :" + username
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Getting Location By user name :" + username
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting Location By user name :" + username
+ " Error : " + e, LOG_TAG);
}
}
return location;
}
/**
* Retrieve the latitude and Longitude location data of given user name
*
* @param username
* @return
*/
public LocationData getLatLong(String username) {
LocationData location = null;
try {
location = new LocationData();
String query = "SELECT LATITUDE, LONGITUDE FROM " + DBConfig.getLocationTable()
+ " WHERE USERNAME= '" + username + "';";
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
statement = connection.createStatement();
// Execute the query and get the result set
ResultSet resultSet = statement.executeQuery(query);
// Check the result row count if greater than 0 means lecture
// details are found. Set the success flag to true.
// Check if resultset has a row
if (resultSet.next()) {
location.setLongitude(resultSet.getString(1));
location.setLatitude(resultSet.getString(2));
LogUtility.LogInfo("Got Location : " + location, LOG_TAG);
}
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Getting latitude longitude By user name :" + username
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Getting latitude longitude By user name :" + username
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting latitude longitude By user name :"
+ username + " Error : " + e, LOG_TAG);
}
}
return location;
}
/**
* Retrieve the latitude and Longitude location data of given memberid
*
* @param username
* @return
*/
public LocationData getLatLongMemberID(int memberid) {
LocationData location = null;
try {
location = new LocationData();
String query = "SELECT LATITUDE, LONGITUDE FROM " + DBConfig.getLocationTable()
+ " WHERE IDMEMBERS= " + memberid;
if (provider == null) {
provider = new DBProvider();
}
// Initialize the connection and statement
connection = provider.getConnection();
statement = connection.createStatement();
// Execute the query and get the result set
ResultSet resultSet = statement.executeQuery(query);
// Check the result row count if greater than 0 means lecture
// details are found. Set the success flag to true.
// Check if resultset has a row
if (resultSet.next()) {
location.setLongitude(resultSet.getString(1));
location.setLatitude(resultSet.getString(2));
LogUtility.LogInfo("Got Location : " + location, LOG_TAG);
}
}
catch (NullPointerException e) {
LogUtility.LogError("Error While Getting latitude longitude By memberid :" + memberid
+ " Error : " + e, LOG_TAG);
}
catch (Exception e) {
LogUtility.LogError("Error While Getting latitude longitude By memberid :" + memberid
+ " Error : " + e, LOG_TAG);
}
finally {
try {
if (connection != null || !connection.isClosed()) {
connection.close();
}
}
catch (SQLException e) {
LogUtility.LogError("Error While Getting latitude longitude By memberid :"
+ memberid + " Error : " + e, LOG_TAG);
}
finally {
}
}
return location;
}
}
| true |
551bd3c73c83d2821bf02b416c47183364c4e8fa | Java | annabeljump/SDP2016 | /cw-one/src/test/testSubInstruction.java | UTF-8 | 540 | 2.421875 | 2 | [] | no_license | package src.test;
import org.junit.Before;
import org.junit.Test;
import src.SubInstruction;
/**
* Tests for DivInstruction.
* @author Annabel Jump
*/
public class testSubInstruction {
@Before
public void setup() {
SubInstruction testee = new SubInstruction("L1", 0, 3, 4);
}
@Test
public void testFields() {
SubInstruction testee = new SubInstruction("L1", 0, 3, 4);
assert(testee.getOp1() == 3);
assert(testee.getOp2() == 4);
assert(testee.getLabel().equals("L1"));
}
}
| true |
c22cfda2b51c14329e61ab49e77acd96401b0b26 | Java | gustavopinto/Brasfoot | /src/classes/Clube.java | UTF-8 | 10,328 | 2.53125 | 3 | [] | no_license | package classes;
import static classes.Brasfoot.baseDadosClubes;
import static classes.Brasfoot.updateBaseDados;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.ImageIcon;
public class Clube extends BaseClube{
//<editor-fold desc="Variaveis">
private final Color FOREGROUND;
private final int id,relevancia;
private Estatistica stats = new Estatistica();
private final ImageIcon background,emblema,emblemaMini;
private double dinheiro,gastos,over,forcaAtaque,forcaDefesa;
private ArrayList<Jogador> elenco,reservas = new ArrayList(),titulares = new ArrayList();
//</editor-fold>
public Clube(String nome, ArrayList<Jogador> elenco, short relevancia,
double dinheiro, String emblema, String emblemaPequeno,
String background, Color foreground, int id ) {
super(nome);
this.elenco = elenco;
this.relevancia = relevancia;
this.dinheiro = dinheiro;
initGastos();
this.id = id;
calcOver();
this.FOREGROUND = foreground;
this.emblema = getEmblema(emblema);
this.emblemaMini = getEmblemaMini(emblemaPequeno);
this.background = getBackground(background);
}
//<editor-fold desc=" Métodos internos">
private ImageIcon getBackground(String arq) {
ImageIcon background;
try {
background = new ImageIcon(getClass().getResource("../img/"+arq));
return background;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private ImageIcon getEmblema(String arq) {
ImageIcon img;
try {
img = new ImageIcon(getClass().getResource("../emblemas/"+arq));
return img;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private ImageIcon getEmblemaMini(String arq) {
ImageIcon img;
try {
img = new ImageIcon(getClass().getResource("../emblemas/"+arq));
return img;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void calcOver() {
double forca = 0, ataque = 0, defesa = 0;
int qtdAtq = 0, qtdDef = 0;
for (int i = 0; i < this.elenco.size(); i++) {
forca += this.elenco.get(i).getOver();
if (this.getElenco().get(i).getPosicao().equals("Atacante")) {
qtdAtq++;
ataque += (double)(this.elenco.get(i).getAtaque()*10 + this.elenco.get(i).getMeio()*0.5)/10;
}
if (this.getElenco().get(i).getPosicao().equals("Meio-Campo")) {
qtdAtq++;
ataque += (double)(this.elenco.get(i).getAtaque()*0.5 + this.elenco.get(i).getMeio()*10)/10;
}
if (this.getElenco().get(i).getPosicao().equals("Defensor")) {
qtdDef++;
defesa += (double)(this.getElenco().get(i).getDefesa()*10 + this.getElenco().get(i).getMeio())/10;
}
if (this.getElenco().get(i).getPosicao().equals("Goleiro")) {
qtdDef++;
defesa += (double)(this.elenco.get(i).getGoleiro());
}
}
this.forcaAtaque = ataque/qtdAtq;
this.forcaDefesa = defesa/qtdDef;
this.over = forca/this.elenco.size();
}
private void initGastos() {
this.gastos = 0;
for (int i = 0; i < getElenco().size(); i++) {
this.gastos += this.elenco.get(i).getSalario();
}
this.dinheiro -= this.gastos;
}
private boolean jaExiste(Jogador jogador) {
for (int i = 0; i < this.elenco.size(); i++) {
if (this.elenco.get(i).getNome().equals(jogador.getNome())) {
return true;
}
}
return false;
}
//</editor-fold>
//<editor-fold desc=" Getters ">
public double getForcaAtaque() {
return forcaAtaque;
}
public double getForcaDefesa() {
return forcaDefesa;
}
public ArrayList<Jogador> getReservas() {
return reservas;
}
public ArrayList<Jogador> getTitulares() {
return titulares;
}
public double getDinheiro() {
return dinheiro;
}
public double getOver() {
return over;
}
public ArrayList<Jogador> getElenco() {
return elenco;
}
public int getRelevancia() {
return relevancia;
}
public double getGastos() {
return gastos;
}
public ImageIcon getEmblema() {
return emblema;
}
public ImageIcon getEmblemaMini() {
return emblemaMini;
}
public ImageIcon getBackground() {
return background;
}
public Color getFOREGROUND() {
return FOREGROUND;
}
public int getId() {
return id;
}
public Estatistica getStats() {
return stats;
}
//</editor-fold>
//Metodos Publicos//
public void rescindirContrato(Jogador jogador) {
for (int i = 0; i < this.elenco.size(); i++) {
if(jogador.equals(this.elenco.get(i).getNome())) {
jogador.receberRecisaoContratual();
this.elenco.remove(i);
}
}
}
public void rescindirContrato(int jogador) {
this.elenco.get(jogador).receberRecisaoContratual();
this.elenco.remove(jogador);
}
public String analisarProposta(double oferta, Jogador jogador) {
double taxa = this.over - jogador.getOver();
double contraProposta = 0 ;
if(taxa > 10 && jogador.getValor()*0.9 < oferta) {
return "true";
}else if((taxa < 10 || taxa < 0) && jogador.getValor()*1.3 < oferta){
return "true";
}else {
if (taxa > 10) {
contraProposta = jogador.getValor();
} else {
contraProposta = jogador.getValor()*1.3;
}
return " não aceita menos que " + ((int)contraProposta+1) + " Mi \npelo " +jogador.getNome();
}
}
public String negociarComClube (Clube clube, Jogador jogador, double oferta) {
if (!this.jaExiste(jogador)) {
String resposta = clube.analisarProposta(oferta, jogador);
if(resposta.equals("true")) {
if (jogador.analisarProposta(clube)) {
if (this.dinheiro > oferta && (this.dinheiro-oferta) > jogador.getSalario()) {
this.gastos += oferta;
this.dinheiro -= oferta;
jogador.trocarDeClube(this);
this.elenco.add(jogador);
clube.getElenco().remove(jogador);
updateBaseDados(clube);
updateBaseDados(this);
return clube.getNome() + " aceitou sua proposta por " + jogador.getNome();
} else {
return "Você não dinheiro suficiente para realizar essa transferência!";
}
}else {
return jogador.getNome() + " não quer jogar pelo seu clube!";
}
}
return "O " + clube.getNome() + resposta;
} else {
return "Você já contratou esse jogador!";
}
}
public Clube venderJogador(Jogador jogador) {
Random gerador = new Random();
int index = 0;
do {
index = gerador.nextInt(baseDadosClubes().size());
} while (baseDadosClubes().get(index).getId() == this.id);
Clube clube = baseDadosClubes().get(index);
clube.getElenco().add(jogador);
this.getElenco().remove(jogador);
jogador.trocarDeClube(clube);
updateBaseDados(clube);
clube.dinheiro -= jogador.getValor()*1.3;
this.dinheiro += jogador.getValor()*1.3;
return clube;
}
public String contratarJogadorSemClube(Jogador jogador) {
if (!this.jaExiste(jogador)) {
if (this.dinheiro > jogador.getSalario()) {
if (jogador.analisarProposta(this)) {
jogador.trocarDeClube(this);
this.elenco.add(jogador);
this.gastos += jogador.getSalario();
this.dinheiro -= jogador.getSalario();
updateBaseDados(this);
return jogador.getNome() + " aceitou sua proposta" ;
} else {
return jogador.getNome() + " não jogar pelo seu clube";
}
} else {
return "Você não dinheiro suficiente para contratar esse jogador!";
}
} else {
return "Você já contratou esse jogador!";
}
}
public boolean adicionarTitular(Jogador jogador) {
if (this.titulares.size() < 11) {
this.titulares.add(jogador);
return true;
}
return false;
}
public boolean removerTitular(Jogador jogador) {
for (int i = 0; i < this.titulares.size(); i++) {
if (this.titulares.get(i).equals(jogador)) {
this.titulares.remove(jogador);
return true;
}
}
return false;
}
public boolean adicionarReserva(Jogador jogador) {
if (this.reservas.size() < 7) {
this.reservas.add(jogador);
return true;
}
return false;
}
public boolean removerReserva(Jogador jogador) {
for (int i = 0; i < this.reservas.size(); i++) {
if (this.reservas.get(i).equals(jogador)) {
this.reservas.remove(jogador);
return true;
}
}
return false;
}
}
| true |
1d3ce14a9fa871c24acf5871487a0857c533cb8c | Java | yefan95/leetcode-solutions | /src/main/java/de/yefan/leetcode/backtrack/Num60.java | UTF-8 | 2,787 | 3.765625 | 4 | [] | no_license | package de.yefan.leetcode.backtrack;
import java.util.ArrayList;
import java.util.List;
/**
* Permutation Sequence
* https://leetcode.com/problems/permutation-sequence/description/
*/
public class Num60 {
public String getPermutation(int n, int k) {
boolean[] used = new boolean[n];
return helper(n, k, used);
}
private String helper(int n, int k, boolean[] used) {
// termination
if (n == 0) {
return "";
}
// recursion
int sum = 1;
for (int i = n; i >= 1; i--) {
sum *= i;
}
int section = sum / n;
int index = 0;
// point to next available number
while (used[index] == true) {
index++;
}
while (k > section) {
k -= section;
// next available number
index++;
while (used[index] == true) {
index++;
}
}
used[index] = true;
return String.valueOf(index + 1) + helper(n - 1, k, used);
}
public String getPermutation1(int n, int k) {
int pos = 0;
List<Integer> numbers = new ArrayList<>();
int[] factorial = new int[n + 1];
StringBuilder sb = new StringBuilder();
int sum = 1;
factorial[0] = 1;
for (int i = 1; i <= n; i++) {
sum *= i;
factorial[i] = sum;
}
// factorial[] = {1, 1, 2, 6, 24, ... n!}
// create a list of numbers to get indices
for (int i = 1; i <= n; i++) {
numbers.add(i);
}
// numbers = {1, 2, 3, 4}
k--;
for (int i = 1; i <= n; i++) {
int index = k / factorial[n - i];
sb.append(String.valueOf(numbers.get(index)));
numbers.remove(index);
k -= index * factorial[n - i];
}
return String.valueOf(sb);
}
public String getPermutation2(int n, int k) {
// recursive
// how do you make the problem smaller?
List<Integer> list = new ArrayList<>();
// 1,1,2,6
int[] factorials = new int[n];
factorials[0] = 1;
for (int i = 1; i < n; i++) {
factorials[i] = factorials[i - 1] * i;
}
for (int i = 1; i <= n; i++) {
list.add(i);
}
return helper(list, k, factorials);
}
private String helper(List<Integer> list, int k, int[] factorials) {
if (list.size() == 0) {
return "";
}
int num = (k - 1) / factorials[list.size() - 1];
String str = "" + list.get(num);
k -= num * factorials[list.size() - 1];
list.remove(num);
return str + helper(list, k, factorials);
}
}
| true |
d9307f2c7f85f5fc6c19483339b9bff59a62702b | Java | kumar835/firstrepo | /SalessTool2019/src/com/faith/test/Main.java | UTF-8 | 389 | 2.234375 | 2 | [] | no_license | package com.faith.test;
public class Main {
public static void main(String[] args){
SalesData objSalesData=new SalesData();
ThirdOne obj=new ThirdOne();
System.out.println("Hello UST Guys ! GOT REPOSITORY");
displayGreetings();
objSalesData.display();
obj.print();
}
private static void displayGreetings(){
System.out.println("Welcome to ooty");
}
}
| true |
78548da42e30307c211207670a0a75fac64d4a55 | Java | junges521/src_awe | /src/main/java/com/bytedance/android/live/core/rxutils/h.java | UTF-8 | 7,931 | 1.632813 | 2 | [] | no_license | package com.bytedance.android.live.core.rxutils;
import com.meituan.robust.ChangeQuickRedirect;
import com.meituan.robust.PatchProxy;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;
public class h implements Function<Observable<Throwable>, ObservableSource<?>> {
/* renamed from: a reason: collision with root package name */
public static ChangeQuickRedirect f8100a;
/* renamed from: b reason: collision with root package name */
public final int f8101b;
/* renamed from: c reason: collision with root package name */
public final long f8102c;
/* renamed from: d reason: collision with root package name */
public int f8103d;
public /* synthetic */ Object apply(Object obj) throws Exception {
Observable observable = (Observable) obj;
if (!PatchProxy.isSupport(new Object[]{observable}, this, f8100a, false, 626, new Class[]{Observable.class}, ObservableSource.class)) {
return observable.flatMap(new Function<Throwable, ObservableSource<?>>() {
/* renamed from: a reason: collision with root package name */
public static ChangeQuickRedirect f8104a;
/* JADX WARNING: Code restructure failed: missing block: B:15:0x0090, code lost:
if (r0 == false) goto L_0x0092;
*/
/* Code decompiled incorrectly, please refer to instructions dump. */
public final /* synthetic */ java.lang.Object apply(java.lang.Object r19) throws java.lang.Exception {
/*
r18 = this;
r7 = r18
r8 = r19
java.lang.Throwable r8 = (java.lang.Throwable) r8
r9 = 1
java.lang.Object[] r0 = new java.lang.Object[r9]
r10 = 0
r0[r10] = r8
com.meituan.robust.ChangeQuickRedirect r2 = f8104a
java.lang.Class[] r5 = new java.lang.Class[r9]
java.lang.Class<java.lang.Throwable> r1 = java.lang.Throwable.class
r5[r10] = r1
java.lang.Class<io.reactivex.ObservableSource> r6 = io.reactivex.ObservableSource.class
r3 = 0
r4 = 628(0x274, float:8.8E-43)
r1 = r18
boolean r0 = com.meituan.robust.PatchProxy.isSupport(r0, r1, r2, r3, r4, r5, r6)
if (r0 == 0) goto L_0x003b
java.lang.Object[] r0 = new java.lang.Object[r9]
r0[r10] = r8
com.meituan.robust.ChangeQuickRedirect r2 = f8104a
r3 = 0
r4 = 628(0x274, float:8.8E-43)
java.lang.Class[] r5 = new java.lang.Class[r9]
java.lang.Class<java.lang.Throwable> r1 = java.lang.Throwable.class
r5[r10] = r1
java.lang.Class<io.reactivex.ObservableSource> r6 = io.reactivex.ObservableSource.class
r1 = r18
java.lang.Object r0 = com.meituan.robust.PatchProxy.accessDispatch(r0, r1, r2, r3, r4, r5, r6)
io.reactivex.ObservableSource r0 = (io.reactivex.ObservableSource) r0
return r0
L_0x003b:
boolean r0 = r8 instanceof com.bytedance.android.live.base.model.d.a
if (r0 == 0) goto L_0x0092
com.bytedance.android.live.core.rxutils.h r0 = com.bytedance.android.live.core.rxutils.h.this
r1 = r8
com.bytedance.android.live.base.model.d.a r1 = (com.bytedance.android.live.base.model.d.a) r1
java.lang.Object[] r11 = new java.lang.Object[r9]
r11[r10] = r1
com.meituan.robust.ChangeQuickRedirect r13 = com.bytedance.android.live.core.rxutils.h.f8100a
r14 = 0
r15 = 627(0x273, float:8.79E-43)
java.lang.Class[] r2 = new java.lang.Class[r9]
java.lang.Class<com.bytedance.android.live.base.model.d.a> r3 = com.bytedance.android.live.base.model.d.a.class
r2[r10] = r3
java.lang.Class r17 = java.lang.Boolean.TYPE
r12 = r0
r16 = r2
boolean r2 = com.meituan.robust.PatchProxy.isSupport(r11, r12, r13, r14, r15, r16, r17)
if (r2 == 0) goto L_0x007d
java.lang.Object[] r11 = new java.lang.Object[r9]
r11[r10] = r1
com.meituan.robust.ChangeQuickRedirect r13 = com.bytedance.android.live.core.rxutils.h.f8100a
r14 = 0
r15 = 627(0x273, float:8.79E-43)
java.lang.Class[] r1 = new java.lang.Class[r9]
java.lang.Class<com.bytedance.android.live.base.model.d.a> r2 = com.bytedance.android.live.base.model.d.a.class
r1[r10] = r2
java.lang.Class r17 = java.lang.Boolean.TYPE
r12 = r0
r16 = r1
java.lang.Object r0 = com.meituan.robust.PatchProxy.accessDispatch(r11, r12, r13, r14, r15, r16, r17)
java.lang.Boolean r0 = (java.lang.Boolean) r0
boolean r0 = r0.booleanValue()
goto L_0x0090
L_0x007d:
int r0 = r1.getStatusCode()
r2 = 500(0x1f4, float:7.0E-43)
if (r0 < r2) goto L_0x008f
int r0 = r1.getStatusCode()
r1 = 599(0x257, float:8.4E-43)
if (r0 > r1) goto L_0x008f
r0 = 1
goto L_0x0090
L_0x008f:
r0 = 0
L_0x0090:
if (r0 != 0) goto L_0x00aa
L_0x0092:
com.bytedance.android.live.core.rxutils.h r0 = com.bytedance.android.live.core.rxutils.h.this
int r1 = r0.f8103d
int r1 = r1 + r9
r0.f8103d = r1
com.bytedance.android.live.core.rxutils.h r0 = com.bytedance.android.live.core.rxutils.h.this
int r0 = r0.f8101b
if (r1 > r0) goto L_0x00aa
com.bytedance.android.live.core.rxutils.h r0 = com.bytedance.android.live.core.rxutils.h.this
long r0 = r0.f8102c
java.util.concurrent.TimeUnit r2 = java.util.concurrent.TimeUnit.MILLISECONDS
io.reactivex.Observable r0 = io.reactivex.Observable.timer(r0, r2)
return r0
L_0x00aa:
io.reactivex.Observable r0 = io.reactivex.Observable.error((java.lang.Throwable) r8)
return r0
*/
throw new UnsupportedOperationException("Method not decompiled: com.bytedance.android.live.core.rxutils.h.AnonymousClass1.apply(java.lang.Object):java.lang.Object");
}
});
}
return (ObservableSource) PatchProxy.accessDispatch(new Object[]{observable}, this, f8100a, false, 626, new Class[]{Observable.class}, ObservableSource.class);
}
public h(int i, long j) {
this.f8101b = i <= 0 ? 1 : i;
this.f8102c = j <= 0 ? 500 : j;
}
}
| true |
090540d77a48b7fba5cd1e43118214b21b86c04c | Java | shadow2016yy/spring-first | /src/test/java/com/ryan/www/drool/Test1.java | UTF-8 | 1,536 | 2.1875 | 2 | [] | no_license | package com.ryan.www.drool;
import com.ryan.www.dto.User;
import org.assertj.core.util.Lists;
import org.junit.runner.RunWith;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* Created by Ryan on 2019/2/20.
*/
public class Test1 {
public static void main(String[] args) throws Exception {
KieServices ks = KieServices.Factory.get();
KieContainer kc = ks.getKieClasspathContainer();
execute( kc );
}
public static void execute( KieContainer kc ) throws Exception{
KieSession ksession = kc.newKieSession("point-rulesKS");
List<User> orderList = getInitData();
for (int i = 0; i < orderList.size(); i++) {
User o = orderList.get(i);
ksession.insert(o);
ksession.fireAllRules();
System.out.println(o);
}
ksession.dispose();
}
private static List<User> getInitData() {
List<User> list= Lists.newArrayList();
User user= User.builder()
.amout(100)
.build();
list.add(user);
User user1= User.builder()
.amout(600)
.build();
list.add(user1);
User user2= User.builder()
.amout(1600)
.build();
list.add(user2);
return list;
}
}
| true |
87430744e0e023647f888c8573b9f7b251b0d925 | Java | MessaoudAbdelatif/LADE | /web/src/main/java/com/lade/app/controller/VoieController.java | UTF-8 | 2,709 | 2.265625 | 2 | [] | no_license | package com.lade.app.controller;
import com.lade.app.dto.contract.VoieMapperImpl;
import com.lade.app.dto.impl.VoieDto;
import entities.Cotation;
import entities.Voie;
import javax.validation.Valid;
import metier.contract.SecteurMetier;
import metier.contract.VoieMetier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class VoieController {
private VoieMetier voieMetier;
private VoieMapperImpl voieMapper;
private SecteurMetier secteurMetier;
@Autowired
public VoieController(VoieMetier voieMetier, VoieMapperImpl voieMapper,
SecteurMetier secteurMetier) {
this.voieMetier = voieMetier;
this.voieMapper = voieMapper;
this.secteurMetier = secteurMetier;
}
//--------------------- Consulter une Voie ---------------------------------
@GetMapping("/viewVoie/{id}")
public String afficherUneVoie(Model model, @PathVariable("id") Long id) {
try {
Voie voieSelected = voieMetier.consulterUneVoie(id);
model.addAttribute("voieSelected", voieSelected);
} catch (Exception e) {
model.addAttribute("exception", e);
}
return "views/viewVoie";
}
//___________________________________________________________________________
//--------------------- Création d'Une Voie -------------------------
@ModelAttribute("newVoie")
public VoieDto voieDto() {
return new VoieDto();
}
@GetMapping("/creationVoie/{secteurID}")
public String creationVoie(Model model, @PathVariable("secteurID") String secteurID) {
model.addAttribute("secteurID", secteurID);
model.addAttribute("SecteurParent", secteurMetier.consulterUnSecteur(Long.valueOf(secteurID)));
model.addAttribute("cotationList", Cotation.getCotations());
return "views/creationVoie";
}
@PostMapping("/ajouterVoie/{secteurID}")
public String ajouterVoie(Model model,
@Valid @ModelAttribute("newVoie") VoieDto voieDto, BindingResult newVoieErrors,
@ModelAttribute("secteurID") String secteurID) {
model.addAttribute("SecteurParent", secteurMetier.consulterUnSecteur(Long.valueOf(secteurID)));
voieDto.setSecteur(secteurID);
if (newVoieErrors.hasErrors()) {
return "views/creationVoie";
}
voieMetier.ajouterVoie(voieMapper.toVoie(voieDto));
return "redirect:/viewSecteur/" + secteurID;
}
}
| true |
db28b9652c8acad3e57dd99585c4e6b0f98b3ecc | Java | kid-way/second_hand | /second-hand-user/src/main/java/com/secondhand/user/service/impl/SellerServiceImpl.java | UTF-8 | 2,503 | 2.453125 | 2 | [] | no_license | package com.secondhand.user.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.secondhand.user.dao.SellerDao;
import com.secondhand.user.entity.Seller;
import com.secondhand.user.exception.LoginException;
import com.secondhand.user.exception.RegistException;
import com.secondhand.user.exception.UpdateException;
import com.secondhand.user.service.SellerService;
@Service
public class SellerServiceImpl implements SellerService{
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private SellerDao sellerDao;
public Seller login(String sname, String password) throws LoginException {
Seller seller = sellerDao.findSellerBySname(sname);
if(seller==null){
throw new LoginException("该卖家用户名不存在");
}else if(!seller.getPassword().equals(password)){
throw new LoginException("密码错误");
}else{
return seller;
}
}
@Transactional
public void regist(Seller seller) throws RegistException {
String sname = seller.getSname();
String sphone = seller.getSphone();
Seller sqlSeller = sellerDao.findSellerBySname(sname);
Seller sqlSeller2 = sellerDao.findSellerBySphone(sphone);
if(sqlSeller!=null){
throw new RegistException("该卖家用户名已被注册");
}else if(sqlSeller2!=null){
throw new RegistException("该手机号已被注册");
}else{
sellerDao.addSeller(seller);
}
}
@Override
public Seller findBySname(String sname) {
Seller seller = sellerDao.findSellerBySname(sname);
return seller;
}
@Override
public Seller findBySphone(String sphone) {
Seller seller = sellerDao.findSellerBySphone(sphone);
return seller;
}
@Override
@Transactional
public Seller update(Seller seller,Seller sessionSeller) {
Seller sqlSeller = sellerDao.findSellerBySname(seller.getSname());
Seller sqlSeller2 = sellerDao.findSellerBySphone(seller.getSphone());
if(sqlSeller != null && !sessionSeller.getSname().equals(sqlSeller.getSname())){
throw new UpdateException("卖家名已被注册");
}else if(sqlSeller2 != null && !sessionSeller.getSphone().equals(sqlSeller2.getSphone())){
throw new UpdateException("该手机号已被注册!");
}else{
sellerDao.update(seller);
return seller;
}
}
}
| true |
94ccc2a3ceaa18b1aacb546b275ef479fcfcbff9 | Java | kawther-brahim/back0.2 | /src/main/java/backend/repository/ExperienceRepository.java | UTF-8 | 336 | 1.867188 | 2 | [] | no_license | package backend.repository;
import backend.model.experience;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ExperienceRepository extends JpaRepository<experience, Long> {
List<experience> findByFormateurCin(long cin, Sort e);
}
| true |
1813d31f44e2718b9cce3124305f8e6c870307b2 | Java | dilky/daelim2016 | /app/src/main/java/example/expense/user/app/expense/NewExpense.java | UTF-8 | 7,632 | 2.015625 | 2 | [] | no_license | package example.expense.user.app.expense;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Calendar;
import example.expense.user.app.R;
import example.expense.user.app.common.AccountTitleSpinnerList;
import example.expense.user.app.common.CommNetwork;
import example.expense.user.app.common.DatePickerFragment;
import example.expense.user.app.common.ErrorUtils;
import example.expense.user.app.common.listener.onNetworkResponseListener;
/**
* Created by dilky on 2016-07-20.
* 신청하기 화면
*/
public class NewExpense extends AppCompatActivity implements onNetworkResponseListener {
public static EditText etPaymentDate;
private Spinner spnAccountTitle;
AccountTitleSpinnerList spinnerList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.content_new_expense);
addToolBar();
etPaymentDate = (EditText) findViewById(R.id.et_PaymentDate);
// 어제 날짜로 초기화
final Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -1);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
etPaymentDate.setTag(R.id.tag_year, year);
etPaymentDate.setTag(R.id.tag_month, month);
etPaymentDate.setTag(R.id.tag_day, day);
etPaymentDate.setText(String.format("%04d년 %2d월 %2d일", year, month + 1, day));
// 클릭시 데이트피커 보여주기
etPaymentDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDatePickerDialog(v);
}
});
// 계정코드 조회
spnAccountTitle = (Spinner)findViewById(R.id.spn_AccountTitle);
getAccounttitleCodes();
} catch (Exception e) {
ErrorUtils.AlertException(this, getString(R.string.error_msg_default_with_activity), e);
}
}
private void getAccounttitleCodes() throws Exception {
CommNetwork network = new CommNetwork(this, this);
JSONObject requestObject = new JSONObject();
network.requestToServer("ACCOUNT_L001", requestObject);
}
private void addToolBar() throws Exception {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolBar);
toolbar.setTitle(R.string.text_new_expense);
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
finish();
}
return (super.onOptionsItemSelected(menuItem));
}
private boolean emptyCheck(EditText editText) {
if (TextUtils.isEmpty(editText.getText())) {
Toast.makeText(this, getString(R.string.error_msg_required_values_are_missing), Toast.LENGTH_SHORT).show();
return true;
} else {
return false;
}
}
// 등록 버튼 클릭
public void toolbarRightButtonClick(View v) {
try {
EditText paymentStoreNm = (EditText) findViewById(R.id.et_PaymentStoreName);
EditText paymentAmount = (EditText) findViewById(R.id.et_PaymentAmount);
EditText summary = (EditText) findViewById(R.id.et_Summary);
if ( emptyCheck(paymentStoreNm)
|| emptyCheck(paymentAmount)
|| emptyCheck(summary)
|| emptyCheck(etPaymentDate) ) {
return;
}
// 서버에 저장하기
JSONObject requestObject = new JSONObject();
requestObject.put("PAYMENT_STORE_NM", paymentStoreNm.getText().toString());
requestObject.put("PAYMENT_AMT", paymentAmount.getText().toString());
requestObject.put("PAYMENT_DTTM", String.format("%04d%02d%02d", etPaymentDate.getTag(R.id.tag_year), ((Integer)etPaymentDate.getTag(R.id.tag_month) + 1), etPaymentDate.getTag(R.id.tag_day)));
requestObject.put("SUMMARY", summary.getText().toString());
requestObject.put("ACCOUNT_TTL_CD", spinnerList.getAccountTitleCd(spnAccountTitle.getSelectedItemPosition()));
requestObject.put("USER_ID", "test_user1");
Log.d("dilky", requestObject.toString());
CommNetwork network = new CommNetwork(this, this);
network.requestToServer("EXPENSE_I001", requestObject);
} catch (Exception e) {
ErrorUtils.AlertException(this, getString(R.string.error_msg_default_with_activity), e);
}
}
// 사용일자 클릭
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.setEditText(etPaymentDate);
newFragment.show(getSupportFragmentManager(), "datePicker");
}
@Override
public void onSuccess(String api_key, JSONObject response) {
try {
if ("ACCOUNT_L001".equals(api_key)) {
//
// 계정코드 조회
//
JSONArray array = response.getJSONArray("REC");
spinnerList = new AccountTitleSpinnerList(array);
ArrayAdapter<String> adapter = new ArrayAdapter<>(NewExpense.this, android.R.layout.simple_spinner_item, spinnerList.getArrayList());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnAccountTitle.setAdapter(adapter);
} else if ("EXPENSE_I001".equals(api_key)) {
//
// 경비신청
//
if ( !TextUtils.isEmpty(response.getString("EXPENSE_SEQ") ) ) {
Intent intent = new Intent(NewExpense.this, ViewExpense.class);
intent.putExtra("EXPENSE_SEQ", response.getString("EXPENSE_SEQ"));
startActivity(intent);
finish();
}
}
} catch (Exception e) {
ErrorUtils.AlertException(this, getString(R.string.error_msg_default_with_activity), e);
}
}
@Override
public void onFailure(String api_key, String error_cd, String error_msg) {
try {
if ("ACCOUNT_L001".equals(api_key)) {
Log.d("dilky", String.format("onFailure (error_cd : %s, error_msg: %s)", error_cd, error_msg) );
} else if ("EXPENSE_I001".equals(api_key)) {
}
} catch (Exception e) {
ErrorUtils.AlertException(this, getString(R.string.error_msg_default_with_activity), e);
}
}
}
| true |
c0f7320941aaedd42823b81233b17e6c1777a491 | Java | Chilukuri543/IntuitCraftDemo | /src/main/java/com/payments/intuitcraftdemo/model/Response.java | UTF-8 | 616 | 2.234375 | 2 | [] | no_license | package com.payments.intuitcraftdemo.model;
public class Response {
private String message;
private PaymentDetails paymentDetails;
public Response(String message, PaymentDetails paymentDetails) {
super();
this.message = message;
this.paymentDetails = paymentDetails;
}
public Response() {
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public PaymentDetails getPaymentDetails() {
return paymentDetails;
}
public void setPaymentDetails(PaymentDetails paymentDetails) {
this.paymentDetails = paymentDetails;
}
}
| true |
80067f73fa9313806c0182fd2a48087768489a90 | Java | match-proj/microservice-user | /microservice-user-context/src/main/java/com/match/user/context/domain/repostory/UserRepository.java | UTF-8 | 541 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package com.match.user.context.domain.repostory;
import com.match.user.context.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import java.util.Optional;
/**
* @Author zhangchao
* @Date 2019/4/25 15:33
* @Version v1.0
*/
@Repository
public interface UserRepository extends JpaRepository<User,String>, JpaSpecificationExecutor {
Optional<User> findByPhone(String phone);
}
| true |
6203f0f9f96f493d9717e0483d8c5f53c8eb8b27 | Java | umeshbsa/android-nonswipeable-viewpager-animation | /app/src/main/java/com/app/moving/activity/MainActivity.java | UTF-8 | 9,954 | 2.140625 | 2 | [] | no_license | package com.app.moving.activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.app.moving.R;
import com.app.moving.adapter.ChildPagerAdapter;
import com.app.moving.adapter.ParentPagerAdapter;
import com.app.moving.fragment.BaseFragment;
import com.app.moving.utils.Utils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener {
private final int MIN_VELOCITY = 1200;
private final int MIN_DISTANCE = 10;
private float mVelocity, mLastTouchX;
private VelocityTracker mVelocityTracker;
private boolean isMovedToRightAnimation;
private boolean isMovedToLeftAnimation;
private View mSwipeAreaView;
private RelativeLayout mChildRealativeLayout;
private ViewPager mOuterNonSwipViewPager;
private ViewPager mChildNonSwipViewPager;
private ParentPagerAdapter mParentPagerAdapter;
private ChildPagerAdapter mChildPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeAreaView = findViewById(R.id.swipe_area_view);
mChildRealativeLayout = (RelativeLayout) findViewById(R.id.child_relative_layout);
mOuterNonSwipViewPager = (ViewPager) findViewById(R.id.non_swip_outer_viewpager);
mChildNonSwipViewPager = (ViewPager) findViewById(R.id.non_swip_child_viewpager);
mSwipeAreaView.setOnTouchListener(this);
setUpPager();
final RelativeLayout parentLayout = (RelativeLayout) findViewById(R.id.s_join_login_parent_layout);
parentLayout.post(new Runnable() {
public void run() {
int height = parentLayout.getHeight();
int width = parentLayout.getWidth();
}
});
}
@Override
public void onClick(View v) {
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int index = motionEvent.getActionIndex();
int action = motionEvent.getActionMasked();
int pointerId = motionEvent.getPointerId(index);
if (pointerId > 0) {
return false;
}
switch (action) {
case MotionEvent.ACTION_DOWN: {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(motionEvent);
}
isMovedToRightAnimation = false;
isMovedToLeftAnimation = false;
final float x = motionEvent.getX();
mLastTouchX = x;
return true;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
mVelocity = VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId);
}
final float x = motionEvent.getX();
if (mLastTouchX > x && (mLastTouchX - x) > MIN_DISTANCE) {
isMovedToRightAnimation = true;
} else if (mLastTouchX < x && (x - mLastTouchX) > MIN_DISTANCE) {
isMovedToLeftAnimation = true;
}
return true;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
if (isMovedToRightAnimation && mVelocity < -MIN_VELOCITY && !isSliding) {
nextPagerItem();
} else if (isMovedToLeftAnimation && mVelocity > MIN_VELOCITY && !isSliding) {
previousPagerItem();
}
return true;
}
default: {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
return true;
}
}
}
private boolean isSliding;
private void nextPagerItem() {
isSliding = true;
BaseFragment.isRightAnimation = true;
BaseFragment fragment = mParentPagerAdapter.getFragmentArray()[mOuterNonSwipViewPager.getCurrentItem()];
if (fragment != null) {
fragment.startExitAnimation(true);
}
BaseFragment insetFragment = mChildPagerAdapter.getFragmentArray()[mOuterNonSwipViewPager.getCurrentItem()];
if (insetFragment != null) {
insetFragment.startExitAnimation(true);
}
final int totalScreens = mParentPagerAdapter.getCount();
final int maxPageIndex = totalScreens - 1;
final int nextPage = mOuterNonSwipViewPager.getCurrentItem() == maxPageIndex ? 0 : mOuterNonSwipViewPager.getCurrentItem() + 1;
if (nextPage == 0) {
mChildRealativeLayout.startAnimation(Utils.rightToLeftExitAnimation(Utils.OFFSET_3));
mChildRealativeLayout.postDelayed(new Runnable() {
@Override
public void run() {
mChildRealativeLayout.setVisibility(View.INVISIBLE);
}
}, Utils.OFFSET_3);
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (nextPage == 0) {
mChildNonSwipViewPager.setCurrentItem(0, false);
} else if (nextPage == 1) {
mChildNonSwipViewPager.setCurrentItem(mChildNonSwipViewPager.getCurrentItem() + 1);
mChildRealativeLayout.setVisibility(View.VISIBLE);
mChildRealativeLayout.startAnimation(Utils.rightToLeftEnterAnimation(Utils.OFFSET_0));
} else {
mChildNonSwipViewPager.setCurrentItem(mChildNonSwipViewPager.getCurrentItem() + 1, false);
}
if (mOuterNonSwipViewPager.getCurrentItem() == maxPageIndex) {
mOuterNonSwipViewPager.setCurrentItem(0, false);
} else {
mOuterNonSwipViewPager.setCurrentItem(mOuterNonSwipViewPager.getCurrentItem() + 1, false);
}
isSliding = false;
}
}, fragment.exitDuration());
}
private void previousPagerItem() {
isSliding = true;
BaseFragment.isRightAnimation = false;
BaseFragment fragment = mParentPagerAdapter.getFragmentArray()[mOuterNonSwipViewPager.getCurrentItem()];
if (fragment != null) {
fragment.startExitAnimation(false);
}
BaseFragment insetFragment = mChildPagerAdapter.getFragmentArray()[mOuterNonSwipViewPager.getCurrentItem()];
if (insetFragment != null) {
insetFragment.startExitAnimation(false);
}
final int totalScreens = mParentPagerAdapter.getCount();
final int maxPageIndex = totalScreens - 1;
final int previousPage = mOuterNonSwipViewPager.getCurrentItem() == 0 ? maxPageIndex : mOuterNonSwipViewPager.getCurrentItem() - 1;
if (previousPage == 0) {
mChildRealativeLayout.startAnimation(Utils.leftToRightExitAnimation(Utils.OFFSET_3));
mChildRealativeLayout.postDelayed(new Runnable() {
@Override
public void run() {
mChildRealativeLayout.setVisibility(View.INVISIBLE);
}
}, Utils.OFFSET_3);
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (previousPage == 0) {
mChildNonSwipViewPager.setCurrentItem(0, false);
} else if (previousPage == maxPageIndex) {
mChildNonSwipViewPager.setCurrentItem(maxPageIndex);
mChildRealativeLayout.setVisibility(View.VISIBLE);
mChildRealativeLayout.startAnimation(Utils.leftToRightEnterAnimation(Utils.OFFSET_0));
} else {
mChildNonSwipViewPager.setCurrentItem(mChildNonSwipViewPager.getCurrentItem() - 1, false);
}
if (mOuterNonSwipViewPager.getCurrentItem() == 0) {
mOuterNonSwipViewPager.setCurrentItem(maxPageIndex, false);
} else {
mOuterNonSwipViewPager.setCurrentItem(mOuterNonSwipViewPager.getCurrentItem() - 1, false);
}
isSliding = false;
}
}, fragment.exitDuration());
}
private void setUpPager() {
mParentPagerAdapter = new ParentPagerAdapter(getSupportFragmentManager());
mParentPagerAdapter.setProvideExtraTraining();
mOuterNonSwipViewPager.setAdapter(mParentPagerAdapter);
if (getResources().getConfiguration().screenHeightDp > 600) {
mChildRealativeLayout.getLayoutParams().height = Utils.dpToPx(this, 360);
((LinearLayout.LayoutParams) mChildNonSwipViewPager.getLayoutParams()).topMargin += Utils.dpToPx(this, 6.45f);
}
mChildPagerAdapter = new ChildPagerAdapter(getSupportFragmentManager());
mChildPagerAdapter.setProvideExtraTraining();
mChildNonSwipViewPager.setAdapter(mChildPagerAdapter);
}
}
| true |
14b3a69a9e3a35106382a188533562e4eb6b3b2e | Java | viveksharma-oodles/ODB | /src/test/java/OodlesDB/listeners.java | UTF-8 | 1,057 | 1.773438 | 2 | [] | no_license | package OodlesDB;
import java.io.IOException;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import resource.Baseclass;
public class listeners implements ITestListener {
Baseclass bs=new Baseclass();
public void onTestStart(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestFailure(ITestResult result) {
// // TODO Auto-generated method stub
result.getName();
try
{
bs.getScreenshot(result.getName());
}
catch(IOException e) {
e.printStackTrace();
}
}
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext argo) {
// TODO Auto-generated method stub
}
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
}
}
| true |
e03c51e00db15d00740b5b89d3ab4c5e1651eda3 | Java | JeremyLiu/tsc | /src/main/java/com/jec/exception/UnexpectedException.java | UTF-8 | 344 | 1.90625 | 2 | [] | no_license | package com.jec.exception;
public class UnexpectedException extends Exception {
public UnexpectedException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
private static final long serialVersionUID = -1492728407928320281L;
public UnexpectedException() {
// TODO Auto-generated constructor stub
}
}
| true |
ddecbdbffa899586024ce79c61672bcb99c4ac4f | Java | seonggwonlee/mini-project-2 | /mini-project-2-server/src/main/java/mini/project/server/pms/handler/TypeListCommand.java | UTF-8 | 1,285 | 2.734375 | 3 | [] | no_license | package mini.project.server.pms.handler;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import mini.project.server.pms.domain.Login;
import mini.project.server.pms.domain.Type;
public class TypeListCommand implements Command {
List<Type> typeList;
Login login;
public TypeListCommand(List<Type> list, Login login) {
this.typeList = list;
this.login = login;
}
@Override
public void execute(PrintWriter out, BufferedReader in) {
if (login.getAdmin() != 0) {
out.print("권한이 없습니다.");
out.println();
out.flush();
return;
}
out.println(" ");
out.println("[타입 목록]");
out.println(" ");
Iterator<Type> iterator = typeList.iterator();
while (iterator.hasNext()) {
Type type = iterator.next();
out.printf("%d, %s, %s\n",
type.getNo(),
type.getName(),
type.getIntroduction());
out.println(" ");
}
}
public Type findByName(String name) {
for (int i = 0; i < typeList.size(); i++) {
Type type = typeList.get(i);
if (type.getName().equals(name)) {
return type;
}
}
return null;
}
}
| true |
ca46015fa3aaa9399f398541f4a05487b9b782e7 | Java | armypago/armydocs_vue | /server/src/main/java/com/armydocs/server/domain/survey/Answer.java | UTF-8 | 840 | 2.28125 | 2 | [] | no_license | package com.armydocs.server.domain.survey;
import com.armydocs.server.domain.BaseTimeEntity;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
public class Answer extends BaseTimeEntity {
@EmbeddedId
private AnswerId id;
private int answerSeq;
private String answerContent;
@Builder
public Answer(AnswerId id, int answerSeq, String answerContent) {
this.id = id;
this.answerSeq = answerSeq;
this.answerContent = answerContent;
}
public void changeAnswerSeq(int answerSeq){
this.answerSeq = answerSeq;
}
public void changeAnswerContent(String answerContent){
this.answerContent = answerContent;
}
}
| true |
7f6e61f211fbd21ecbe5fa23059f46f4ad8308b7 | Java | wangzhengyangNo1/RecyclerViewStu | /app/src/main/java/com/wzhy/recyclerviewstu/divides/GridDividerItemDecoration.java | UTF-8 | 4,766 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package com.wzhy.recyclerviewstu.divides;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class GridDividerItemDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
private Drawable mDivider;
public GridDividerItemDecoration() {
super();
}
public GridDividerItemDecoration(Context context) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
final int childCount = parent.getChildCount();
final GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
final int spanCount = layoutManager.getSpanCount();
final int orientation = layoutManager.getOrientation();
boolean isDrawHorizontalDivider = true;
boolean isDrawVerticalDivider = true;
int extra = childCount % spanCount;
extra = extra == 0 ? spanCount : extra;
for (int i = 0; i < childCount; i++) {
isDrawHorizontalDivider = true;
isDrawVerticalDivider = true;
//如果是竖直方向,最右边一列不绘制竖直方向间隔
if (orientation == RecyclerView.VERTICAL && (i + 1) % spanCount == 0) {
isDrawVerticalDivider = false;
}
// //如果是竖直方向,最后一行不绘制水平方向间隔
// if (orientation == RecyclerView.VERTICAL && i >= childCount - extra) {
// isDrawHorizontalDivider = false;
// }
//如果是水平方向,最下面一行不绘制水平方向间隔
if (orientation == RecyclerView.HORIZONTAL && (i + 1) % spanCount == 0) {
isDrawHorizontalDivider = false;
}
// //如果是水平方向,最右边一列不绘制竖直方向间隔
// if (orientation == RecyclerView.HORIZONTAL && i >= childCount - extra) {
// isDrawVerticalDivider = false;
// }
if (isDrawHorizontalDivider) {
drawHorizontalDivider(c, parent, i);
}
if (isDrawVerticalDivider) {
drawVerticalDivider(c, parent, i);
}
}
}
private void drawVerticalDivider(Canvas c, RecyclerView parent, int i) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getTop() - layoutParams.topMargin;
final int bottom = child.getBottom() + layoutParams.bottomMargin;
final int left = child.getRight() + layoutParams.rightMargin;
final int right = left + mDivider.getIntrinsicWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
private void drawHorizontalDivider(Canvas c, RecyclerView parent, int i) {
final View child = parent.getChildAt(i);
final RecyclerView.LayoutParams lp = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + lp.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
final int left = child.getLeft() - lp.leftMargin;
final int right = child.getRight() + lp.rightMargin + mDivider.getIntrinsicWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(c);
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mDivider == null) {
outRect.set(0, 0, 0, 0);
return;
}
final GridLayoutManager layoutManager = (GridLayoutManager) parent.getLayoutManager();
final int spanCount = layoutManager.getSpanCount();
final int orientation = layoutManager.getOrientation();
final int position = parent.getChildAdapterPosition(view);
if (orientation == RecyclerView.VERTICAL && (position + 1) % spanCount == 0) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
} else if (orientation == RecyclerView.HORIZONTAL && (position + 1) % spanCount == 0) {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
} else {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight());
}
}
}
| true |
91e8f4d0b8d2418cbeae081908ce0fe52b34f295 | Java | lhs1553/news-helper | /news/src/main/java/com/ckpoint/news/news/repository/NewsFilterRepository.java | UTF-8 | 367 | 1.890625 | 2 | [] | no_license | package com.ckpoint.news.news.repository;
import com.ckpoint.news.news.CompanyType;
import com.ckpoint.news.news.domain.NewsFilter;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface NewsFilterRepository extends JpaRepository<NewsFilter, Long> {
List<NewsFilter> findByCompanyType(CompanyType companyType);
}
| true |
208259c7412e9925bc3389a71cfd484f7a028e24 | Java | 13522055874wwz/studygit | /shops/src/main/java/com/wz/service/MyServiceImpl.java | UTF-8 | 1,406 | 1.773438 | 2 | [] | no_license | package com.wz.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wz.entity.Shop;
import com.wz.mapper.ShopMapper;
@Service
public class MyServiceImpl implements MyService{
@Autowired
private ShopMapper sm;
@Override
public int deleteByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insert(Shop record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insertSelective(Shop record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public Shop selectByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return null;
}
@Override
public int updateByPrimaryKeySelective(Shop record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int updateByPrimaryKey(Shop record) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List selectList() {
// TODO Auto-generated method stub
return sm.selectList();
}
@Override
public int updatelikeByid(Integer id) {
// TODO Auto-generated method stub
return sm.updatelikeByid(id);
}
@Override
public int updateshouByid(Integer id) {
// TODO Auto-generated method stub
return sm.updateshouByid(id);
}
}
| true |
4988d13c00ee02393320c70ba38787d89469e4c1 | Java | willyborja95/Camello | /app/src/main/java/com/apptec/camello/mainactivity/fnotification/NotificationConstants.java | UTF-8 | 848 | 1.960938 | 2 | [] | no_license | package com.apptec.camello.mainactivity.fnotification;
import android.app.NotificationManager;
/**
* Class for have the constants about the Notification module
*/
public class NotificationConstants {
public static final String MESSAGES_CHANNEL_ID = "messages";
public static final int MESSAGES_IMPORTANCE = NotificationManager.IMPORTANCE_DEFAULT;
public static final String LOCATION_CHANNEL_ID = "location";
public static final int LOCATION_IMPORTANCE = NotificationManager.IMPORTANCE_HIGH;
/**
* Payload node names for notifications
*/
public static final String NOTIFICATION_TITLE = "title";
public static final String NOTIFICATION_MESSAGE = "message";
public static final String NOTIFICATION_SENT_DATE = "createdAt";
public static final String NOTIFICATION_EXPIRATION_DATE = "expiresAt";
}
| true |
5dd62f19087368031ef2a9e5a599f9930578a060 | Java | ntmanh2112/aptech-sem2-0907e | /Users/HungTC/Session2/src/applet/Example.java | UTF-8 | 1,118 | 3.109375 | 3 | [] | no_license | package applet;
import java.awt.*;
import java.applet.*;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Example extends Applet implements Runnable
{
/**
*
*/
private static final long serialVersionUID = 1L;
int count;
Thread objTh;
String str=" hello world, my name is Hung, class 0907E ";
public void init()
{
objTh = new Thread(this);
objTh.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
for(count = 1; count <= 20; count++) {
try {
repaint();
Thread.sleep(200);
str = str.substring(1,str.length())+str.substring(0,1);
} catch (InterruptedException e) {
}
}
}
public void paint(Graphics g) {
g.setColor(Color.green);
g.drawString(getDateTime(), 30, 30);
g.setColor(Color.blue);
g.drawString(str, 50, 50);
}
private String getDateTime() {
final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
final Date date = new Date();
return dateFormat.format(date);
}
}
| true |
5a50438d7468fb582a0c1185fed68ae8476358f0 | Java | Wis13/AddressbookGradle | /src/test/java/com/vadym/test/ContactModificationTests.java | UTF-8 | 1,007 | 2.078125 | 2 | [] | no_license | package com.vadym.test;
import com.vadym.model.ContactData;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Set;
public class ContactModificationTests extends TestBase {
@BeforeMethod
public void ensurePrecondishions() {
app.goTo().HomePage();
if (app.contact().all().size() == 0) {
File photo = new File("./mord.png");
app.contact().create(new ContactData().withId(1).withFirstname("test13")
.withLastname("rest13").withPhoto(photo), true);
}
}
@Test
public void testGroupModification() {
Set<ContactData> before = app.contact().all();
ContactData modifiedContact = before.iterator().next();
File photo = new File("./mord.png");
app.contact().modify(new ContactData().withId(modifiedContact.getId()).withFirstname("test222")
.withLastname("rest222").withPhoto(photo), true);
}
}
| true |
805a4c2ccb0b58f4384b6f581fed9266ded2468b | Java | zuz-schwarzova/classified | /src/main/java/sk/zuzmat/classified/backend/MissionManager.java | UTF-8 | 578 | 2.015625 | 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 sk.zuzmat.classified.backend;
import java.util.List;
/**
*
* @author xschwar2
*/
public interface MissionManager {
public void createMission(Mission mission);
public void updateMission(Mission mission);
public void deleteMission(Mission mission);
public Mission findMissionById(Long id);
public List<Mission> findAllMissions();
}
| true |
98c7e0191297fdd8aa06c8a3a757e52d0253f110 | Java | taquayle/ITAD242 | /Assignment_04/Assignment_04_Tyler_Quayle/src/assignment_04_tyler_quayle/SurfBoardList.java | UTF-8 | 1,724 | 3.4375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package assignment_04_tyler_quayle;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* @author Quayle
*/
public class SurfBoardList{
static class surfBoard
{
private final int lastSerialNumber = 10000;
private int serialNumber;
public surfBoard(int serial)
{
serialNumber = serial;
}
@Override public String toString()
{
return "Serial Number: " + serialNumber +
"\t out of " + lastSerialNumber;
}
}
public static void main(String[] args)
{
ArrayList<surfBoard> surfBoardList = new ArrayList<surfBoard>();
Scanner uInput = new Scanner(System.in);
char answer;
int i = 1;
do{
System.out.println("Enter Y to create a surfboard or N to exit");
answer = uInput.next().charAt(0);
if(answer == 'y' || answer == 'Y')
{
surfBoard newBoard = new surfBoard(i++);
surfBoardList.add(newBoard);
System.out.println("Surfboard Created");
}
else if(answer == 'n' || answer == 'N')
System.out.println("N entered, current list of boards:");
else{
System.out.println("Error: Invalid input");
answer = 'y';}
}while (answer == 'y' || answer == 'Y');
for(surfBoard output : surfBoardList)
System.out.println(output);
}
}
| true |
0c33381fe4471715b6761f87e6529ae48ef7b85f | Java | heshiyuanqq/dubbo_api | /src/main/java/com/dubbo/test/pojo/BaseBean.java | UTF-8 | 472 | 1.796875 | 2 | [] | no_license | package com.dubbo.test.pojo;
import java.io.Serializable;
import javax.xml.ws.ServiceMode;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BaseBean implements Serializable{
//private static final long serialVersionUID = 3652016037713542990L;
private String xxx;
private String yyy;
private Integer zzz;
public static void main(String[] args) {
BaseBean bean = new BaseBean();
}
}
| true |
268bd1201460781f45831688c12d62d0bf217589 | Java | tferfce/Sacchon | /src/main/java/gr/codehub/team5/resource/PatientDataSpecifyResource.java | UTF-8 | 580 | 2.234375 | 2 | [] | no_license | package gr.codehub.team5.resource;
import gr.codehub.team5.exceptions.NotFoundException;
import gr.codehub.team5.representation.PatientDataRepresentation;
import org.restlet.resource.Delete;
import org.restlet.resource.Put;
/**
* A request used by every Patient giving him the ability to edit his own data!
* Update
* Delete
*/
public interface PatientDataSpecifyResource {
@Delete
void deleteSpecificData() throws NotFoundException;
@Put
PatientDataRepresentation updatePData(PatientDataRepresentation patientDataRepresentation) throws NotFoundException;
}
| true |
2e382b74688ccf708f89f49bd320b332b59dc91c | Java | cmeng-git/atalk-android | /aTalk/src/main/java/org/atalk/impl/neomedia/control/AbstractControls.java | UTF-8 | 5,449 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.atalk.impl.neomedia.control;
import javax.media.Controls;
import timber.log.Timber;
/**
* Provides an abstract implementation of <code>Controls</code> which facilitates implementers by
* requiring them to only implement {@link Controls#getControls()}.
*
* @author Lyubomir Marinov
* @author Eng Chong Meng
*/
public abstract class AbstractControls implements Controls
{
/**
* Implements {@link Controls#getControl(String)}. Invokes {@link #getControls()} and then
* looks for a control of the specified type in the returned array of controls.
*
* @param controlType
* a <code>String</code> value naming the type of the control of this instance to be
* retrieved
* @return an <code>Object</code> which represents the control of this instance with the specified
* type
*/
public Object getControl(String controlType)
{
return getControl(this, controlType);
}
/**
* Gets the control of a specific <code>Controls</code> implementation of a specific type if such a
* control is made available through {@link Controls#getControls()}; otherwise, returns
* <code>null</code>.
*
* @param controlsImpl
* the implementation of <code>Controls</code> which is to be queried for its list of
* controls so that the control of the specified type can be looked for
* @param controlType
* a <code>String</code> value which names the type of the control to be retrieved
* @return an <code>Object</code> which represents the control of <code>controlsImpl</code> of the
* specified <code>controlType</code> if such a control is made available through
* <code>Controls#getControls()</code>; otherwise, <code>null</code>
*/
public static Object getControl(Controls controlsImpl, String controlType)
{
Object[] controls = controlsImpl.getControls();
if ((controls != null) && (controls.length > 0)) {
Class<?> controlClass;
try {
controlClass = Class.forName(controlType);
}
catch (ClassNotFoundException cnfe) {
controlClass = null;
Timber.w(cnfe, "Failed to find control class %s", controlType);
}
if (controlClass != null) {
for (Object control : controls) {
if (controlClass.isInstance(control))
return control;
}
}
}
return null;
}
/**
* Returns an instance of a specific <code>Class</code> which is either a control of a specific
* <code>Controls</code> implementation or the <code>Controls</code> implementation itself if it is an
* instance of the specified <code>Class</code>. The method is similar to
* {@link #getControl(Controls, String)} in querying the specified <code>Controls</code>
* implementation about a control of the specified <code>Class</code> but is different in
* looking at the type hierarchy of the <code>Controls</code> implementation for the specified
* <code>Class</code>.
*
* @param controlsImpl
* the <code>Controls</code> implementation to query
* @param controlType
* the runtime type of the instance to be returned
* @return an instance of the specified <code>controlType</code> if such an instance can be found
* among the controls of the specified <code>controlsImpl</code> or <code>controlsImpl</code> is
* an instance of the specified <code>controlType</code>; otherwise, <code>null</code>
*/
@SuppressWarnings("unchecked")
public static <T> T queryInterface(Controls controlsImpl, Class<T> controlType)
{
T control;
if (controlsImpl == null) {
control = null;
}
else {
control = (T) controlsImpl.getControl(controlType.getName());
if ((control == null) && controlType.isInstance(controlsImpl))
control = (T) controlsImpl;
}
return control;
}
/**
* Returns an instance of a specific <code>Class</code> which is either a control of a specific
* <code>Controls</code> implementation or the <code>Controls</code> implementation itself if it is an
* instance of the specified <code>Class</code>. The method is similar to
* {@link #getControl(Controls, String)} in querying the specified <code>Controls</code>
* implementation about a control of the specified <code>Class</code> but is different in looking at
* the type hierarchy of the <code>Controls</code> implementation for the specified <code>Class</code>.
*
* @param controlsImpl
* the <code>Controls</code> implementation to query
* @param controlType
* the runtime type of the instance to be returned
* @return an instance of the specified <code>controlType</code> if such an instance can be found
* among the controls of the specified <code>controlsImpl</code> or <code>controlsImpl</code> is
* an instance of the specified <code>controlType</code>; otherwise, <code>null</code>
*/
public static Object queryInterface(Controls controlsImpl, String controlType)
{
Object control;
if (controlsImpl == null) {
control = null;
}
else {
control = controlsImpl.getControl(controlType);
if (control == null) {
Class<?> controlClass;
try {
controlClass = Class.forName(controlType);
}
catch (ClassNotFoundException cnfe) {
controlClass = null;
Timber.w(cnfe, "Failed to find control class %s", controlType);
}
if ((controlClass != null) && controlClass.isInstance(controlsImpl)) {
control = controlsImpl;
}
}
}
return control;
}
}
| true |
216433dc22eacbbd80fecb02b59c21d4771d8154 | Java | AWU20181023/product | /product-server/src/main/java/com/gree/product/controller/ServerController.java | UTF-8 | 362 | 1.796875 | 2 | [] | no_license | package com.gree.product.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by 260152(AWU) on 2018/10/31 7:56.
*/
@RestController
public class ServerController {
@GetMapping("msg")
public String msg() {
return "this is prduction' msg";
}
}
| true |
490614219259dcb411a24f9b4e20d0ef5add394f | Java | DessertFox17/Intermediate-Java | /src/usogetset/modLavadorasamsung.java | UTF-8 | 764 | 2.875 | 3 | [] | no_license | package usogetset;
import java.util.Scanner;
public class modLavadorasamsung {
public void LavadoraDatosmod() {
Scanner entrada = new Scanner(System.in);
System.out.println("Ingrese el tipo de ropa");
System.out.println("Presiona: 1 - Blanca / 2 - Color");
System.out.print("-> ");
int tipoRopa = entrada.nextInt();
System.out.println("¿Cuantos kilos de ropa desea lavar?");
System.out.print("-> ");
int kilos = entrada.nextInt();
System.out.println();
LLFuncionesmod mensajero = new LLFuncionesmod(kilos, tipoRopa);
mensajero.settipoRopa(2);
System.out.println("El tipo de ropa es: " + mensajero.gettipoRopa());
mensajero.CicloFinalizado();
}
}
| true |
37db43d07f11c76aa046fb3f78399bb903658185 | Java | didacusAbella/Symposium | /src/main/java/it/blackhat/symposium/managers/AnswerManager.java | UTF-8 | 1,567 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | package it.blackhat.symposium.managers;
import it.blackhat.symposium.models.Answer;
import java.sql.SQLException;
import java.util.List;
/**
* This class describes the method signatures of Answer Manager
*
* @author Gozzetto
*/
public interface AnswerManager {
/**
* Insert an Answer given an Answer object
*
* @param answer Answer to insert
* @return true if the operation go well, false otherwise
* @throws SQLException if db errors occurred
*/
int insertAnswer(Answer answer) throws SQLException;
/**
* Remove an Answer given a id
*
* @param id AnswerId to remove
* @return true if the operation go well, false otherwise
* @throws SQLException if db errors occurred
*/
int removeAnswer(int id) throws SQLException;
/**
* Remove an Answer given the id's question
*
* @param id questionId of the questions's answers to remove
* @return true if the operation go well, false otherwise
* @throws SQLException if db errors occurred
*/
int bestAnswer(int id) throws SQLException;
/**
* Retrieves all answers related to a question
*
* @param questionId the questionId for retrieve the answers
* @return a List of tags related to the question
* @throws SQLException if db error occurred
*/
List<Answer> retrieveQuestionAnswers(int questionId) throws SQLException;
/**
* Retrieves all answers
*
* @return a List of tags related to the answers
* @throws SQLException if db error occurred
*/
List<Answer> retrieveAllQuestionAnswers() throws SQLException;
}
| true |
ee0b0427fc6da87b8dd0503f18c58148846c7791 | Java | hehaihao/Test | /project/Common/src/main/java/com/xm6leefun/common/db/utils/CustomMigration.java | UTF-8 | 525 | 2.109375 | 2 | [] | no_license | package com.xm6leefun.common.db.utils;
import io.realm.DynamicRealm;
import io.realm.RealmMigration;
import io.realm.RealmSchema;
/**
* @Description: 迁移操作的迁移类
* @Author: hhh
* @CreateDate: 2021/3/25 15:31
*/
public class CustomMigration implements RealmMigration {
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
//数据库升级操作
RealmSchema schema=realm.getSchema();
if(oldVersion == 1 && newVersion ==2){
}
}
}
| true |
185925f1458ac35552c40b4a2c2742db74d5f30f | Java | allen0224/springcloud-zjt | /services-elasticsearch/src/main/java/com/meorient/mebuyerdiscovery/elasticsearch/doc/CompanyPartStatistics.java | UTF-8 | 12,094 | 1.945313 | 2 | [] | no_license | package com.meorient.mebuyerdiscovery.elasticsearch.doc;
import org.springframework.data.elasticsearch.annotations.Document;
import java.math.BigDecimal;
import static com.meorient.mebuyerdiscovery.elasticsearch.doc.Statistics.COMPANY_PART_INDEX;
import static com.meorient.mebuyerdiscovery.elasticsearch.doc.Statistics.COMPANY_PART_TYPE;
@Document(indexName = COMPANY_PART_INDEX,type =COMPANY_PART_TYPE )
public class CompanyPartStatistics {
//公司名称
private String companyName;
//国家
private String country;
//采购编码
private String code;
//采购次数
private Long purchases;
//次数占比(当前编码采购次数/该公司总次数)*100%
private Float purchasesRatio;
//采购金额(usd)
private BigDecimal purchaseAmountUSD;
//采购金额占比(当前编码采购金额/该公司总金额)*100%
private Float purchaseAmountRatio;
//-采购重量(KG)
private Double purchaseWeight;
//-采购重量占比(当前编码采购重量/该公司总重量)*100%
private Float purchaseWeightRatio;
//-采购件数
private Long purchaseNumber;
//-采购件数占比(当前编码采购件数/该公司总件数)*100%
private Float purchaseNumberRatio;
//是否从中国进口
private Boolean InChina=false;
//从中国采购次数
private Long purchasesINChina;
//从中国采购次数占比(当前编码从中国采购件数/该编码总件数)*100%
private Float purchasesINChinaRatio;
//从中国采购金额(USD)
private BigDecimal PurchaseAmountINChinaUSD;
//从中国采购金额占比(当前编码从中国采购金额/该编码总金额)*100%
private BigDecimal PurchaseAmountINChinaUSDRatio;
//-从中国采购重量(KG)
private Double PurchaseWeightINChina;
//-从中国采购重量占比(当前编码从中国采购重量/该编码总重量)*100%
private Double PurchaseWeightINChinaRatio;
//-从中国采购件数(KG)
private Long purchaseNumberINChina;
//-从中国采购金额占比(当前编码从中国采购件数/该编码总件数)*100%
private Long purchaseNumberINRatio;
//贸易客单价USD(该编码贸易金额/该编码贸易次数)
private BigDecimal traderPrice;
private BigDecimal traderPriceCif;
private BigDecimal traderPriceUsd;
private BigDecimal traderPriceFob;
//总供应商数
private Long totalSuppliers;
//中国供应商数
private Long chinaSuppliers;
//中国供应商占比(当前编码的中国供应商数/该编码总供应商数)*100%
private Float chinaRatio;
//同行数(指采购同一编码的全球采购商数)
private Long peer;
//本国同行数(指采购同一编码的本国采购商)
private Long domesticPeers;
//本国同行占比(该编码本国同行/全球同行数)*100%
private Float domesticPeersRatio;
private BigDecimal productVlUsdCif;
private BigDecimal productVlUsd;
private BigDecimal productVlUsdFob;
private Float productVlUsdCifRatio;
private Float productVlUsdRatio;
private Float productVlUsdFobRatio;
private Float chinaProductVlUsdCifRatio;
private Float chinaProductVlUsdRatio;
private Float chinaProductVlUsdFobRatio;
public Float getChinaProductVlUsdFobRatio() {
return chinaProductVlUsdFobRatio;
}
public void setChinaProductVlUsdFobRatio(Float chinaProductVlUsdFobRatio) {
this.chinaProductVlUsdFobRatio = chinaProductVlUsdFobRatio;
}
public Float getChinaProductVlUsdCifRatio() {
return chinaProductVlUsdCifRatio;
}
public void setChinaProductVlUsdCifRatio(Float chinaProductVlUsdCifRatio) {
this.chinaProductVlUsdCifRatio = chinaProductVlUsdCifRatio;
}
public Float getChinaProductVlUsdRatio() {
return chinaProductVlUsdRatio;
}
public void setChinaProductVlUsdRatio(Float chinaProductVlUsdRatio) {
this.chinaProductVlUsdRatio = chinaProductVlUsdRatio;
}
public Float getProductVlUsdCifRatio() {
return productVlUsdCifRatio;
}
public void setProductVlUsdCifRatio(Float productVlUsdCifRatio) {
this.productVlUsdCifRatio = productVlUsdCifRatio;
}
public Float getProductVlUsdRatio() {
return productVlUsdRatio;
}
public void setProductVlUsdRatio(Float productVlUsdRatio) {
this.productVlUsdRatio = productVlUsdRatio;
}
public Float getProductVlUsdFobRatio() {
return productVlUsdFobRatio;
}
public void setProductVlUsdFobRatio(Float productVlUsdFobRatio) {
this.productVlUsdFobRatio = productVlUsdFobRatio;
}
private BigDecimal chinaProductVlUsdCif;
private BigDecimal chinaProductVlUsd;
private BigDecimal chinaProductVlUsdFob;
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getPurchases() {
return purchases;
}
public void setPurchases(Long purchases) {
this.purchases = purchases;
}
public Float getPurchasesRatio() {
return purchasesRatio;
}
public void setPurchasesRatio(Float purchasesRatio) {
this.purchasesRatio = purchasesRatio;
}
public BigDecimal getPurchaseAmountUSD() {
return purchaseAmountUSD;
}
public void setPurchaseAmountUSD(BigDecimal purchaseAmountUSD) {
this.purchaseAmountUSD = purchaseAmountUSD;
}
public Float getPurchaseAmountRatio() {
return purchaseAmountRatio;
}
public void setPurchaseAmountRatio(Float purchaseAmountRatio) {
this.purchaseAmountRatio = purchaseAmountRatio;
}
public Double getPurchaseWeight() {
return purchaseWeight;
}
public void setPurchaseWeight(Double purchaseWeight) {
this.purchaseWeight = purchaseWeight;
}
public Float getPurchaseWeightRatio() {
return purchaseWeightRatio;
}
public void setPurchaseWeightRatio(Float purchaseWeightRatio) {
this.purchaseWeightRatio = purchaseWeightRatio;
}
public Long getPurchaseNumber() {
return purchaseNumber;
}
public void setPurchaseNumber(Long purchaseNumber) {
this.purchaseNumber = purchaseNumber;
}
public Float getPurchaseNumberRatio() {
return purchaseNumberRatio;
}
public void setPurchaseNumberRatio(Float purchaseNumberRatio) {
this.purchaseNumberRatio = purchaseNumberRatio;
}
public Boolean getInChina() {
return InChina;
}
public void setInChina(Boolean inChina) {
InChina = inChina;
}
public Long getPurchasesINChina() {
return purchasesINChina;
}
public void setPurchasesINChina(Long purchasesINChina) {
this.purchasesINChina = purchasesINChina;
}
public Float getPurchasesINChinaRatio() {
return purchasesINChinaRatio;
}
public void setPurchasesINChinaRatio(Float purchasesINChinaRatio) {
this.purchasesINChinaRatio = purchasesINChinaRatio;
}
public BigDecimal getPurchaseAmountINChinaUSD() {
return PurchaseAmountINChinaUSD;
}
public void setPurchaseAmountINChinaUSD(BigDecimal purchaseAmountINChinaUSD) {
PurchaseAmountINChinaUSD = purchaseAmountINChinaUSD;
}
public BigDecimal getPurchaseAmountINChinaUSDRatio() {
return PurchaseAmountINChinaUSDRatio;
}
public void setPurchaseAmountINChinaUSDRatio(BigDecimal purchaseAmountINChinaUSDRatio) {
PurchaseAmountINChinaUSDRatio = purchaseAmountINChinaUSDRatio;
}
public Double getPurchaseWeightINChina() {
return PurchaseWeightINChina;
}
public void setPurchaseWeightINChina(Double purchaseWeightINChina) {
PurchaseWeightINChina = purchaseWeightINChina;
}
public Double getPurchaseWeightINChinaRatio() {
return PurchaseWeightINChinaRatio;
}
public void setPurchaseWeightINChinaRatio(Double purchaseWeightINChinaRatio) {
PurchaseWeightINChinaRatio = purchaseWeightINChinaRatio;
}
public Long getPurchaseNumberINChina() {
return purchaseNumberINChina;
}
public void setPurchaseNumberINChina(Long purchaseNumberINChina) {
this.purchaseNumberINChina = purchaseNumberINChina;
}
public Long getPurchaseNumberINRatio() {
return purchaseNumberINRatio;
}
public void setPurchaseNumberINRatio(Long purchaseNumberINRatio) {
this.purchaseNumberINRatio = purchaseNumberINRatio;
}
public BigDecimal getTraderPrice() {
return traderPrice;
}
public void setTraderPrice(BigDecimal traderPrice) {
this.traderPrice = traderPrice;
}
public Long getTotalSuppliers() {
return totalSuppliers;
}
public void setTotalSuppliers(Long totalSuppliers) {
this.totalSuppliers = totalSuppliers;
}
public Long getChinaSuppliers() {
return chinaSuppliers;
}
public void setChinaSuppliers(Long chinaSuppliers) {
this.chinaSuppliers = chinaSuppliers;
}
public Float getChinaRatio() {
return chinaRatio;
}
public void setChinaRatio(Float chinaRatio) {
this.chinaRatio = chinaRatio;
}
public Long getPeer() {
return peer;
}
public void setPeer(Long peer) {
this.peer = peer;
}
public Long getDomesticPeers() {
return domesticPeers;
}
public void setDomesticPeers(Long domesticPeers) {
this.domesticPeers = domesticPeers;
}
public Float getDomesticPeersRatio() {
return domesticPeersRatio;
}
public void setDomesticPeersRatio(Float domesticPeersRatio) {
this.domesticPeersRatio = domesticPeersRatio;
}
public BigDecimal getProductVlUsdCif() {
return productVlUsdCif;
}
public void setProductVlUsdCif(BigDecimal productVlUsdCif) {
this.productVlUsdCif = productVlUsdCif;
}
public BigDecimal getProductVlUsd() {
return productVlUsd;
}
public void setProductVlUsd(BigDecimal productVlUsd) {
this.productVlUsd = productVlUsd;
}
public BigDecimal getProductVlUsdFob() {
return productVlUsdFob;
}
public void setProductVlUsdFob(BigDecimal productVlUsdFob) {
this.productVlUsdFob = productVlUsdFob;
}
public BigDecimal getChinaProductVlUsdCif() {
return chinaProductVlUsdCif;
}
public void setChinaProductVlUsdCif(BigDecimal chinaProductVlUsdCif) {
this.chinaProductVlUsdCif = chinaProductVlUsdCif;
}
public BigDecimal getChinaProductVlUsd() {
return chinaProductVlUsd;
}
public void setChinaProductVlUsd(BigDecimal chinaProductVlUsd) {
this.chinaProductVlUsd = chinaProductVlUsd;
}
public BigDecimal getChinaProductVlUsdFob() {
return chinaProductVlUsdFob;
}
public void setChinaProductVlUsdFob(BigDecimal chinaProductVlUsdFob) {
this.chinaProductVlUsdFob = chinaProductVlUsdFob;
}
public BigDecimal getTraderPriceCif() {
return traderPriceCif;
}
public void setTraderPriceCif(BigDecimal traderPriceCif) {
this.traderPriceCif = traderPriceCif;
}
public BigDecimal getTraderPriceUsd() {
return traderPriceUsd;
}
public void setTraderPriceUsd(BigDecimal traderPriceUsd) {
this.traderPriceUsd = traderPriceUsd;
}
public BigDecimal getTraderPriceFob() {
return traderPriceFob;
}
public void setTraderPriceFob(BigDecimal traderPriceFob) {
this.traderPriceFob = traderPriceFob;
}
}
| true |
b7d9f9d9fa8ed1740d70b502c580bac968088dbd | Java | maksymmykytiuk/elephants | /src/main/java/com/maksymmykytiuk/elephants/model/people/Lecturer.java | UTF-8 | 1,657 | 2.390625 | 2 | [] | no_license | package com.maksymmykytiuk.elephants.model.people;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.maksymmykytiuk.elephants.model.Department;
import com.maksymmykytiuk.elephants.model.Position;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
@Entity
@Table(name = "lecturer")
@Getter
@Setter
@NoArgsConstructor
public class Lecturer {
@Id
@Column(name = "lecturer_id")
@GeneratedValue(generator = "lecture_generator")
@SequenceGenerator(
name = "lecturer_generator",
sequenceName = "lecturer_sequence"
)
private Long id;
@Column(name = "first_name")
@NotEmpty
@Size(max = 64)
private String firstName;
@Column(name = "middle_name")
@NotEmpty
@Size(max = 64)
private String middleName;
@Column(name = "last_name")
@NotEmpty
@Size(max = 64)
private String lastName;
@Column(name = "employee_id")
@NotEmpty
@Size(min = 10, max = 10)
private String employeeId;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "department_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
protected Department department;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "position_id", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
protected Position position;
}
| true |
6ba23c1e5655706608ff33a4dbe601dfcc6a8af1 | Java | spring-projects/spring-framework | /spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufEncoder.java | UTF-8 | 4,058 | 2 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.codec.protobuf;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.google.protobuf.Message;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageEncoder;
import org.springframework.lang.Nullable;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.MimeType;
/**
* An {@code Encoder} that writes {@link com.google.protobuf.Message}s
* using <a href="https://developers.google.com/protocol-buffers/">Google Protocol Buffers</a>.
*
* <p>Flux are serialized using
* <a href="https://developers.google.com/protocol-buffers/docs/techniques?hl=en#streaming">delimited Protobuf messages</a>
* with the size of each message specified before the message itself. Single values are
* serialized using regular Protobuf message format (without the size prepended before the message).
*
* <p>To generate {@code Message} Java classes, you need to install the {@code protoc} binary.
*
* <p>This encoder requires Protobuf 3 or higher, and supports
* {@code "application/x-protobuf"} and {@code "application/octet-stream"} with the official
* {@code "com.google.protobuf:protobuf-java"} library.
*
* @author Sebastien Deleuze
* @since 5.1
* @see ProtobufDecoder
*/
public class ProtobufEncoder extends ProtobufCodecSupport implements HttpMessageEncoder<Message> {
private static final List<MediaType> streamingMediaTypes = Arrays.stream(MIME_TYPES)
.map(mimeType -> new MediaType(mimeType.getType(), mimeType.getSubtype(),
Collections.singletonMap(DELIMITED_KEY, DELIMITED_VALUE)))
.toList();
@Override
public boolean canEncode(ResolvableType elementType, @Nullable MimeType mimeType) {
return Message.class.isAssignableFrom(elementType.toClass()) && supportsMimeType(mimeType);
}
@Override
public Flux<DataBuffer> encode(Publisher<? extends Message> inputStream, DataBufferFactory bufferFactory,
ResolvableType elementType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
return Flux.from(inputStream).map(message ->
encodeValue(message, bufferFactory, !(inputStream instanceof Mono)));
}
@Override
public DataBuffer encodeValue(Message message, DataBufferFactory bufferFactory,
ResolvableType valueType, @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
return encodeValue(message, bufferFactory, false);
}
private DataBuffer encodeValue(Message message, DataBufferFactory bufferFactory, boolean delimited) {
FastByteArrayOutputStream bos = new FastByteArrayOutputStream();
try {
if (delimited) {
message.writeDelimitedTo(bos);
}
else {
message.writeTo(bos);
}
byte[] bytes = bos.toByteArrayUnsafe();
return bufferFactory.wrap(bytes);
}
catch (IOException ex) {
throw new IllegalStateException("Unexpected I/O error while writing to data buffer", ex);
}
}
@Override
public List<MediaType> getStreamingMediaTypes() {
return streamingMediaTypes;
}
@Override
public List<MimeType> getEncodableMimeTypes() {
return getMimeTypes();
}
}
| true |
72468aed917e64dee109ddd0bafadfd67803793a | Java | lkloeble/translator | /src/main/java/patrologia/translator/rule/romanian/RuleDinFatsaFinder.java | UTF-8 | 942 | 2.53125 | 3 | [] | no_license | package patrologia.translator.rule.romanian;
import patrologia.translator.basicelements.Phrase;
import patrologia.translator.basicelements.Word;
import patrologia.translator.rule.Rule;
public class RuleDinFatsaFinder extends Rule {
@Override
public void apply(Word word, Phrase phrase, int position) {
Word followingWord = phrase.getWordContainerAtPosition(position + 1).getUniqueWord();
Word followingExtendedWord = phrase.getWordContainerAtPosition(position + 2).getUniqueWord();
if ("din".equals(word.getInitialValue()) &&
"femininearticle".equals(followingWord.getInitialValue()) &&
"fatsa".equals(followingExtendedWord.getInitialValue())) {
word.setInitialValue("dinfatsa");
word.setRoot("dinfatsa");
followingWord.setInitialValue("xxtoremovexx");
followingExtendedWord.setInitialValue("xxtoremovexx");
}
}
}
| true |
bedf8c9c35503b8c4852041ba2601d30e9978acc | Java | masha237/prog-intro-2020 | /java-solutions/markup/ComplexText.java | UTF-8 | 397 | 2.375 | 2 | [] | no_license | package markup;
import java.util.List;
public abstract class ComplexText extends AbstractElement implements ParagraphElement{
public ComplexText(List<ParagraphElement> a) {
super(a);
}
public String getTagBe() {
return "[/" + getTag() + "]";
}
public String getTagBb() {
return "[" + getTag() + "]";
}
protected abstract String getTag();
}
| true |
4ec6fc6bd58026b40dca2aafc649d9873f9b8a6d | Java | rtgeorgiev/MarketStore | /MarketStore/src/Card.java | UTF-8 | 483 | 3.109375 | 3 | [] | no_license |
public abstract class Card {
private Client client;
protected double turnover;
public Card(double startTurnover, Client client) {
this.client = client;
this.turnover = startTurnover;
}
abstract public double getDiscountRate();
final public double getDiscount(double amount) {
return amount * getDiscountRate() / 100;
}
final public double getTurnover() {
return turnover;
}
final public void increaseTurnover(double amount) {
this.turnover += amount;
}
}
| true |
bfe638982771acafb813fa6a70e9cbc577666074 | Java | ghadaabbes/JAVA | /src/com/esprit/entities/Promotion.java | UTF-8 | 4,983 | 1.945313 | 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.esprit.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Siala
*/
@Entity
@Table(name = "promotion")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Promotion.findAll", query = "SELECT p FROM Promotion p")
, @NamedQuery(name = "Promotion.findById", query = "SELECT p FROM Promotion p WHERE p.id = :id")
, @NamedQuery(name = "Promotion.findByDateDebutPromotion", query = "SELECT p FROM Promotion p WHERE p.dateDebutPromotion = :dateDebutPromotion")
, @NamedQuery(name = "Promotion.findByDateFinPromotion", query = "SELECT p FROM Promotion p WHERE p.dateFinPromotion = :dateFinPromotion")
, @NamedQuery(name = "Promotion.findByPourcentage", query = "SELECT p FROM Promotion p WHERE p.pourcentage = :pourcentage")})
public class Promotion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "date_debut_promotion")
@Temporal(TemporalType.DATE)
private Date dateDebutPromotion;
@Basic(optional = false)
@Column(name = "date_fin_promotion")
@Temporal(TemporalType.DATE)
private Date dateFinPromotion;
@Basic(optional = false)
@Column(name = "pourcentage")
private int pourcentage;
@JoinColumn(name = "patisserie_id", referencedColumnName = "idPatisserie")
@ManyToOne
private Patisserie patisserieId;
@JoinColumn(name = "image_id", referencedColumnName = "id")
@OneToOne
private Image imageId;
@JoinColumn(name = "produit_id", referencedColumnName = "idProduit")
@ManyToOne
private Produit produitId;
public Promotion() {
}
public Promotion(Integer id) {
this.id = id;
}
public Promotion( Produit produitId,Date dateDebutPromotion, Date dateFinPromotion, int pourcentage) {
this.produitId=produitId;
this.dateDebutPromotion = dateDebutPromotion;
this.dateFinPromotion = dateFinPromotion;
this.pourcentage = pourcentage;
}
public Promotion(Date date1, Date datef, int s) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Date getDateDebutPromotion() {
return dateDebutPromotion;
}
public void setDateDebutPromotion(Date dateDebutPromotion) {
this.dateDebutPromotion = dateDebutPromotion;
}
public Date getDateFinPromotion() {
return dateFinPromotion;
}
public void setDateFinPromotion(Date dateFinPromotion) {
this.dateFinPromotion = dateFinPromotion;
}
public int getPourcentage() {
return pourcentage;
}
public void setPourcentage(int pourcentage) {
this.pourcentage = pourcentage;
}
public Patisserie getPatisserieId() {
return patisserieId;
}
public void setPatisserieId(Patisserie patisserieId) {
this.patisserieId = patisserieId;
}
public Image getImageId() {
return imageId;
}
public void setImageId(Image imageId) {
this.imageId = imageId;
}
public Produit getProduitId() {
return produitId;
}
public void setProduitId(Produit produitId) {
this.produitId = produitId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
// @Override
// public boolean equals(Object object) {
// // TODO: Warning - this method won't work in the case the id fields are not set
// if (!(object instanceof Promotion)) {
// return false;
// }
// Promotion other = (Promotion) object;
// if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
// return false;
// }
// return true;
// }
@Override
public String toString() {
return "entites.Promotion[ id=" + id + " ]";
}
}
| true |
84a34d54dbca6b577c3568827f6c0b19606a2848 | Java | ehdwldk7400/Spring-Strart | /src/test/java/org/admin/dbTest/MemberMapperTest.java | UHC | 1,725 | 2.1875 | 2 | [] | no_license | package org.admin.dbTest;
import java.util.List;
import org.jin.mapper.MemberMapper;
import org.jin.mapper.MemberVO;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) // Ʈ ϱ SpringJUnit4ClassRunner
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class MemberMapperTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private MemberMapper memmapper;
// @Test
// public void testInsertMember() {
// MemberVO member = new MemberVO();
//
// member.setUserid("test");
// member.setUserpw("1234");
// member.setUsername("");
// member.setUsername("jin@kirininfo.com");
//
// memmapper.createMember(member);
// }
@Test
public void testReadMember() {
MemberVO member = new MemberVO();
member.setUserid("def");
logger.info("ȸ : " + memmapper.readMember(member));
}
@Test
public void testReadMemberList() {
List<MemberVO> memvo = memmapper.readMemberList();
memvo.forEach(member->logger.info(""+member));
}
@Test
public void testUpdateMember() {
MemberVO member = new MemberVO();
member.setUserpw("9999");
member.setUsername("");
member.setUserid("def");
memmapper.updateMember(member);
}
@Test
public void testDeleteMember() {
MemberVO member = new MemberVO();
member.setUserid("def");
memmapper.deleteMember(member);
}
}
| true |
a62ce9d94b77fdfb3835393118bab548dd902b0a | Java | Krusher-git/XmlTaskEpam | /src/main/java/com/kozich/xmltask/parser/FilePathParser.java | UTF-8 | 383 | 2.34375 | 2 | [] | no_license | package com.kozich.xmltask.parser;
import java.io.File;
import java.net.URL;
public class FilePathParser {
public static String filePath(String path) {
ClassLoader loader = FilePathParser.class.getClassLoader();
URL location = loader.getResource(path);
String filePath = new File(location.getFile()).getAbsolutePath();
return filePath;
}
}
| true |
8d89db41d98b8105a352cb3c2ff9bbeaf89bb2ad | Java | KyleLyu/Kyle_Finra | /src/main/java/com/kyle/demo/exception/ErrorInputException.java | UTF-8 | 267 | 2.1875 | 2 | [] | no_license | package com.kyle.demo.exception;
public class ErrorInputException extends StorageException{
public ErrorInputException(String mess) {
super(mess);
}
public ErrorInputException(String mess, Throwable cause) {
super(mess, cause);
}
} | true |
bf2ef0970458e29f8d8a7a235a9cca9fdeaa7e59 | Java | George-Cherian826/first-repo | /Resources/Utility/Excelutils.java | UTF-8 | 1,624 | 2.65625 | 3 | [] | no_license | package Utility;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excelutils
{
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
public static Object[][] getTableArray(String FilePath, String SheetName) throws Exception {
String[][] tabArray = null;
try {
FileInputStream ExcelFile = new FileInputStream(FilePath);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
int totalRows = ExcelWSheet.getLastRowNum();
int totalCols= ExcelWSheet.getRow(0).getLastCellNum();
tabArray=new String[totalRows][totalCols];
int ci=0,cj=0;
for (int i=1;i<=totalRows;i++)
{
cj=0;
for (int j=0;j<=totalCols-1;j++)
{
tabArray[ci][cj]=ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
cj++;
}
ci++;
}
}
catch (FileNotFoundException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
catch (IOException e){
System.out.println("Could not read the Excel sheet");
e.printStackTrace();
}
return(tabArray);
}
}
| true |
be8122af1e65520bb87e5b2a5a99039687a2aa56 | Java | 123qweqwe123/PEACE3 | /.svn/pristine/be/be8122af1e65520bb87e5b2a5a99039687a2aa56.svn-base | UTF-8 | 851 | 1.648438 | 2 | [] | no_license | package com.bdcor.pip.web.qn.service;
import com.bdcor.pip.web.qn.domain.*;
import com.bdcor.pip.web.qn.filter.EventCheckFilter;
import org.springframework.ui.Model;
import java.util.List;
/**
* Description:
* <pre>
* </pre>
* Author: huangrupeng
* Create: 17/5/11 下午3:51
*/
public interface EventCheckService {
List<PipCommEventVO1> getEventCheckList(EventCheckFilter filter);
void getEventInfo(String eventCode, Model model);
void saveOrUpdate(PipCommEventCheck1 check, PipCommEventCheckEr1 er);
PipCommEventCheckEr1 getErByEventCode(String eventCode);
/**
* 添加审核用户
*/
boolean addAuditUser();
String addEvent(String eventCode, Model model);
List<PipCommEventExportVO> getEvent2exportList(EventCheckFilter filter);
String updateEventCheckStatus(String eventCodeList);
}
| true |
8a4703554a5ead4155f2b90c4edba3ae862100a8 | Java | Akram-Nayak/JulyAutomationMorningBatch | /Web Automation/src/com/sgtesting/selenium/pageobject/ActiPagePratice.java | UTF-8 | 3,508 | 1.828125 | 2 | [] | no_license | package com.sgtesting.selenium.pageobject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class ActiPagePratice
{
public ActiPagePratice(WebDriver oBrowser)
{
PageFactory.initElements(oBrowser, this);
}
private WebElement username;
public WebElement getUserName()
{
return username;
}
private WebElement pwd;
public WebElement getPassword()
{
return pwd;
}
@FindBy(xpath="//*[@id=\'loginButton\']/div")
private WebElement oLogin;
public WebElement getLoginButton()
{
return oLogin;
}
private WebElement gettingStartedShortcutsPanelId;
public WebElement getFlyOutWin()
{
return gettingStartedShortcutsPanelId;
}
@FindBy(xpath="//*[@id=\'topnav\']/tbody/tr[1]/td[5]/a/div[2]")
private WebElement user;
public WebElement getUser()
{
return user;
}
@FindBy(xpath="//*[@id=\'createUserDiv\']/div")
private WebElement adduser;
public WebElement getAddUser()
{
return adduser;
}
private WebElement firstName;
public WebElement getFirstName()
{
return firstName;
}
private WebElement lastName;
public WebElement getLastName()
{
return lastName;
}
private WebElement email;
public WebElement getEmail()
{
return email;
}
private WebElement userDataLightBox_usernameField;
public WebElement getUser1()
{
return userDataLightBox_usernameField;
}
private WebElement userDataLightBox_passwordField;
public WebElement getUser1Password()
{
return userDataLightBox_passwordField;
}
private WebElement passwordCopy;
public WebElement getPasswordCopy()
{
return passwordCopy;
}
@FindBy(xpath="//*[@id='userDataLightBox_commitBtn\']")
private WebElement creatuser;
public WebElement getCreatUser()
{
return creatuser;
}
@FindBy(xpath="//*[@id=\'welcomeScreenBoxId\']/div[3]/div/span[1]")
private WebElement welcomenote;
public WebElement getWelcomeNote()
{
return welcomenote;
}
// selecting user1(ms dhoni) //
@FindBy(xpath="//*[@id=\'userListTableContainer\']/table/tbody/tr[1]/td[1]")
private WebElement selectuser1;
public WebElement getSelectUser1()
{
return selectuser1;
}
// click by admin on modifypassword
@FindBy(xpath="//*[@id=\'userDataLightBox_passwordField\']")
private WebElement modifynewpassword;
public WebElement getModifyNewPassword()
{
return modifynewpassword;
}
// click by admin on modifyretyppassword
@FindBy(xpath="//*[@id=\'userDataLightBox_passwordCopyField\']")
private WebElement modifyretyppassword;
public WebElement getModifyRetypPassword()
{
return modifyretyppassword;
}
// click on save changes
private WebElement buttonTitle;
public WebElement getSaveChanges()
{
return buttonTitle;
}
// selecting user2(virat kholi)
@FindBy(xpath="//*[@id=\'userListTableContainer\']/table/tbody/tr[2]/td[1]/table/tbody/tr/td/div[1]/span[2]")
private WebElement selectuser2;
public WebElement getSelectUser2()
{
return selectuser2;
}
// selecting user2(Rohit Sharma)
@FindBy(xpath="//*[@id=\'userListTableContainer\']/table/tbody/tr[3]/td[1]/table/tbody/tr/td/div[1]/span[2]")
private WebElement selectuser3;
public WebElement getSelectUser3()
{
return selectuser3;
}
private WebElement delectuser;
public WebElement getDelectUser()
{
return delectuser;
}
@FindBy(xpath="//*[@id=\'logoutLink\']")
private WebElement oLogout;
public WebElement getLogout()
{
return oLogout;
}
}
| true |
92f944e7604622f1b46d9970d981bef048767fee | Java | jangseokgyu/java-algorithm | /dynamic_prog_baekjoon_2011.java | UTF-8 | 1,053 | 3.375 | 3 | [
"MIT"
] | permissive | import java.util.Scanner;
//존냉 어렵낸 ㅅㅂ 하다 안되서 소스 봤다 ㅅㅂ 아 제기랄.
public class Main {
public static void getPossible(String code) {
long[] dynamic=new long[code.length()+1];
dynamic[0]=1;
dynamic[1]=1;
if(code.charAt(0)=='0'){//0으로 시작하는 경우
System.out.println(0);
return;
}
for(int i=1; i<code.length(); i++) {
char pri = code.charAt(i - 1);//이전 숫자
if(code.charAt(i) >= '1' && code.charAt(i)<='9'){//혼자올수있음
dynamic[i+1]+=dynamic[i];
dynamic[i+1]%=1000000;
}
if (!(pri == '0' || pri > '2' || (pri == '2' && code.charAt(i) > '6'))) {
dynamic[i + 1] += dynamic[i-1];
dynamic[i+1]%=1000000;
}
dynamic[i + 1] %= 1000000000;
}
System.out.println(dynamic[code.length()]%1000000000);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String code = scan.next();
getPossible(code);
}
}
| true |
686366e6015aea4eca2013e7a08265ad2f08fcf9 | Java | chandusekhar/btpn_portal | /src/main/java/com/sybase365/mobiliser/web/dashboard/base/SpringAware.java | UTF-8 | 409 | 1.84375 | 2 | [] | no_license | package com.sybase365.mobiliser.web.dashboard.base;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
*
* @author all
*/
public final class SpringAware implements ApplicationContextAware {
@Override
public void setApplicationContext(final ApplicationContext appContext) {
SpringAdapter.setContext(appContext);
}
}
| true |
b2d8c86a299db65d6f6fd7958f005e467653df11 | Java | HutnikMaksim/forMaxim | /src/by/it/kolesnikov/jd02_01/Basket.java | UTF-8 | 1,092 | 3.15625 | 3 | [] | no_license | package by.it.kolesnikov.jd02_01;
import java.util.*;
class Basket {
static void basket() {
StringBuffer sb =new StringBuffer();
List<String> goods = new ArrayList<>();
List<String> basketGoods = new ArrayList<>();
List<Integer> prices = new ArrayList<>();
List<Integer> price = new ArrayList<>();
for (Map.Entry<String, Integer> entry : Good.goods().entrySet()){
String el = entry.getKey();
Integer pr = entry.getValue();
goods.add(el);
prices.add(pr);
}
int count = Helper.getRandom(1,4);
String delimiter = "";
int sum=0;
for (int i = 0; i < count; i++) {
int rnd = Helper.getRandom(3);
String good = goods.get(rnd);
int pr = prices.get(rnd);
basketGoods.add(good);
price.add(pr);
sum=sum+price.get(i);
sb.append(delimiter);
sb.append(basketGoods.get(i));
delimiter=", ";
}
System.out.println(sb+": costs $"+sum);
}
}
| true |
b46c4e0c6c380317a2c18bf1fd0a41a54710c571 | Java | KruskalLin/SECII | /Client/src/main/java/ui/inventoryui/inventoryReceiptui/InventoryOverflowDamageTreeTable.java | UTF-8 | 5,015 | 2 | 2 | [] | no_license | package ui.inventoryui.inventoryReceiptui;
import com.jfoenix.controls.*;
import com.jfoenix.controls.cells.editors.IntegerTextFieldEditorBuilder;
import com.jfoenix.controls.cells.editors.TextFieldEditorBuilder;
import com.jfoenix.controls.cells.editors.base.GenericEditableTreeTableCell;
import com.jfoenix.controls.datamodels.treetable.RecursiveTreeObject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import ui.common.BoardController;
import ui.util.ColumnDecorator;
import ui.util.ListPopup;
import ui.util.PaneFactory;
import vo.inventoryVO.inventoryReceiptVO.ReceiptGoodsItemVO;
import java.util.ArrayList;
import java.util.List;
public class InventoryOverflowDamageTreeTable extends JFXTreeTableView<ReceiptGoodsItemVO> {
private ObservableList<ReceiptGoodsItemVO> observableList = FXCollections.observableArrayList();
private BoardController boardController;
private StackPane mainpane;
public InventoryOverflowDamageTreeTable() {
super();
mainpane = PaneFactory.getMainPane();
ColumnDecorator columnDecorator = new ColumnDecorator();
this.setEditable(true);
JFXTreeTableColumn<ReceiptGoodsItemVO, String> goodsID = new JFXTreeTableColumn<>("GoodsID");
goodsID.setPrefWidth(115.5);
goodsID.setEditable(true);
columnDecorator.setupCellValueFactory(goodsID, ReceiptGoodsItemVO::goodsIdProperty);
goodsID.setCellFactory((TreeTableColumn<ReceiptGoodsItemVO, String> param) -> {
return new GenericEditableTreeTableCell<>(new TextFieldEditorBuilder());
});
goodsID.setOnEditCommit((TreeTableColumn.CellEditEvent<ReceiptGoodsItemVO, String> t) -> {
t.getTreeTableView().getTreeItem(t.getTreeTablePosition().getRow()).getValue().goodsIdProperty().set(t.getNewValue());
});
JFXTreeTableColumn<ReceiptGoodsItemVO, String> goodsName = new JFXTreeTableColumn<>("GoodsName");
goodsName.setPrefWidth(115.5);
columnDecorator.setupCellValueFactory(goodsName, ReceiptGoodsItemVO::goodsNameProperty);
goodsName.setCellFactory((TreeTableColumn<ReceiptGoodsItemVO, String> param) -> {
return new GenericEditableTreeTableCell<>(new TextFieldEditorBuilder());
});
goodsName.setOnEditCommit((TreeTableColumn.CellEditEvent<ReceiptGoodsItemVO, String> t) -> {
t.getTreeTableView().getTreeItem(t.getTreeTablePosition().getRow()).getValue().goodsNameProperty().set(t.getNewValue());
});
JFXTreeTableColumn<ReceiptGoodsItemVO, Integer> inventoryNum = new JFXTreeTableColumn<>("InventoryNum");
inventoryNum.setPrefWidth(115.5);
columnDecorator.setupCellValueFactory(inventoryNum, l -> l.inventoryNumProperty().asObject());
inventoryNum.setCellFactory((TreeTableColumn<ReceiptGoodsItemVO, Integer> param) -> {
return new GenericEditableTreeTableCell<>(new IntegerTextFieldEditorBuilder());
});
inventoryNum.setOnEditCommit((TreeTableColumn.CellEditEvent<ReceiptGoodsItemVO, Integer> t) -> {
t.getTreeTableView().getTreeItem(t.getTreeTablePosition().getRow()).getValue().inventoryNumProperty().set(t.getNewValue());
});
JFXTreeTableColumn<ReceiptGoodsItemVO, Integer> factNum = new JFXTreeTableColumn<>("FactNum");
factNum.setPrefWidth(115.5);
columnDecorator.setupCellValueFactory(factNum, l -> l.factNumProperty().asObject());
factNum.setCellFactory((TreeTableColumn<ReceiptGoodsItemVO, Integer> param) -> {
return new GenericEditableTreeTableCell<>(new IntegerTextFieldEditorBuilder());
});
factNum.setOnEditCommit((TreeTableColumn.CellEditEvent<ReceiptGoodsItemVO, Integer> t) -> {
t.getTreeTableView().getTreeItem(t.getTreeTablePosition().getRow()).getValue().factNumProperty().set(t.getNewValue());
});
TreeItem<ReceiptGoodsItemVO> root = new RecursiveTreeItem<>(observableList, RecursiveTreeObject::getChildren);
this.setRoot(root);
this.setEditable(true);
this.setShowRoot(false);
this.getColumns().setAll(goodsID, goodsName, inventoryNum, factNum);
}
public void setList(List<ReceiptGoodsItemVO> goods) {
observableList.setAll(goods);
}
public void removeGood(ReceiptGoodsItemVO good) {
observableList.remove(good);
}
public void addGood(ReceiptGoodsItemVO good) {
observableList.add(good);
}
public void clear(){
observableList.clear();
}
public ArrayList<ReceiptGoodsItemVO> getList(){
ArrayList<ReceiptGoodsItemVO> arrayList = new ArrayList<>();
observableList.forEach(i->arrayList.add(i));
return arrayList;
}
}
| true |
5d4a39cf9319637ddbe98b409992da14bf8475cf | Java | dianaDivi/cts_lab | /PersonalSpital/src/ro/ase/CTS/clase/Asistent.java | UTF-8 | 209 | 2.25 | 2 | [] | no_license | package ro.ase.CTS.clase;
public class Asistent extends PersonalSpital{
public Asistent(String nume) {
super(nume);
}
@Override
public String toString() {
return "Asistent " + getNume();
}
}
| true |
608df3d331a5d6155070fab57c21bd4b956f85e2 | Java | TryRevilo/RevCoreInit-Libbed | /rev-lib-core-app-plugins/src/main/java/rev/ca/rev_lib_core_app_plugins/rev_video_plugin/rev_plugin_views/rev_pluggable_menus/RevVideoPluggableMenuItem.java | UTF-8 | 4,943 | 1.78125 | 2 | [] | no_license | package rev.ca.rev_lib_core_app_plugins.rev_video_plugin.rev_plugin_views.rev_pluggable_menus;
import android.content.Context;
import androidx.core.content.ContextCompat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
import rev.ca.rev_lib_core_app_plugins.R;
import rev.ca.rev_lib_core_views.rev_core_views.rev_input_form_views.IRevInputFormView;
import rev.ca.rev_lib_core_views.rev_core_views.rev_input_form_views.RevSubmitFormViewContainer;
import rev.ca.rev_lib_core_views.rev_core_views.rev_pluggable_inline_views.RevPluggableViewImpl;
import rev.ca.rev_lib_core_views.rev_core_views.rev_pluggable_menues.ICreateRevPluggableMenuItem;
import rev.ca.rev_lib_core_views.rev_core_views.rev_pluggable_menues.RevPluggableMenuItemVM;
import rev.ca.rev_lib_core_views.rev_pluggable_views_impl.RevConstantinePluggableViewsServices;
import rev.ca.rev_lib_gen_functions.RevLibGenConstantine;
import rev.ca.rev_gen_lib_pers.rev_varags_data.RevPersGenFunctions;
import rev.ca.rev_gen_lib_pers.rev_varags_data.RevVarArgsData;
import rev.ca.revlibviews.rev_core_input_forms.RevCoreInputFormTextView;
import rev.ca.revlibviews.rev_core_layouts.RevCoreLayoutsLinearLayout;
/**
* Created by rev on 1/19/18.
*/
public class RevVideoPluggableMenuItem implements ICreateRevPluggableMenuItem {
private RevVarArgsData revVarArgsData;
private Context mContext;
private RevCoreLayoutsLinearLayout revCoreLayoutsLinearLayout;
private RevCoreInputFormTextView revCoreInputFormTextView;
public RevVideoPluggableMenuItem(RevVarArgsData revVarArgsData) {
revVarArgsData = RevPersGenFunctions.REV_VAR_ARGS_DATA_RESOLVER(revVarArgsData);
this.revVarArgsData = revVarArgsData;
this.mContext = revVarArgsData.getmContext();
revCoreLayoutsLinearLayout = new RevCoreLayoutsLinearLayout(mContext);
revCoreInputFormTextView = new RevCoreInputFormTextView(mContext);
}
@Override
public String REV_PLUGGABLE_MENU_ITEM_VM_NAME() {
return "add_rev_video";
}
@Override
public List<String> REV_PLUGGABLE_MENU_CONTAINER_NAME() {
return Arrays.asList("rev_core_gen_publisher_options_menu", "rev_bag_options_menu");
}
@Override
public RevPluggableMenuItemVM create_REV_PLUGGABLE_MENU_ITEM_VM() {
LinearLayout linearLayout = revCoreLayoutsLinearLayout.getHorizontalRevLinearLayout_WRAPPED_ALL();
ImageView imageView = new ImageView(mContext);
imageView.setPadding(0, 0, 0, 0);
imageView.setImageResource(R.drawable.ic_add_a_photo_black_48dp);
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.teal_dark));
int imageSize = (int) (RevLibGenConstantine.REV_IMAGE_SIZE_TINY * 1.5);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(imageSize, imageSize);
layoutParams.gravity = (Gravity.TOP);
imageView.setLayoutParams(layoutParams);
TextView textView = revCoreInputFormTextView.getRevExtraSmallNormalTextView_NO_PADDING_LINK();
textView.setText("Upload video");
LinearLayout.LayoutParams textView_LP = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textView_LP.gravity = (Gravity.BOTTOM);
textView_LP.setMargins((int) (RevLibGenConstantine.REV_MARGIN_TINY * 0.5), 0, 0, 0);
textView.setLayoutParams(textView_LP);
linearLayout.addView(imageView);
linearLayout.addView(textView);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
revVarArgsData.setRevViewType("RevCreateNewObjectVideoForm");
IRevInputFormView iRevInputFormView = (IRevInputFormView) RevConstantinePluggableViewsServices.revViewCreator_REV_PLUGIN_INPUT_FORMS_MAP(revVarArgsData);
iRevInputFormView.createRevInputForm();
RevPluggableViewImpl.REV_RESET_REV_PLUGGABLE_INLINE_VIEW(
"user_profile_center_cct_view_LL",
new RevSubmitFormViewContainer(mContext).getRevSubmitFormViewContainer(iRevInputFormView));
}
});
RevPluggableMenuItemVM revPluggableMenuItemVM = new RevPluggableMenuItemVM();
revPluggableMenuItemVM.setRevPluggableMenuItemName("add_rev_video");
revPluggableMenuItemVM.setRevPluggableMenuName(Arrays.asList("rev_core_gen_publisher_options_menu", "rev_bag_options_menu", "rev_user_options_menu"));
revPluggableMenuItemVM.setRevPluggableMenuView(linearLayout);
return revPluggableMenuItemVM;
}
}
| true |
62ac2b622c2e0374aa2163a20ec2f0c9a7bdca8a | Java | e98877331/HearthStoneWinRate | /src/wcm/towolf/hearthstonewr/view/detail/GameHistoryListView.java | UTF-8 | 3,464 | 2.234375 | 2 | [] | no_license | package wcm.towolf.hearthstonewr.view.detail;
import itri.u9lab.towolf.ratiofixer.RatioFixer;
import java.util.ArrayList;
import wcm.towolf.hearthstonewr.R;
import wcm.towolf.hearthstonewr.db.DBHelper;
import wcm.towolf.hearthstonewr.db.DBTBRoleGames;
import wcm.towolf.hearthstonewr.model.datatype.AddDateRoleGame;
import wcm.towolf.hearthstonewr.model.datatype.RoleGame;
import wcm.towolf.hearthstonewr.model.datatype.RoleType;
import android.content.Context;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class GameHistoryListView extends ListView {
Context mContext;
public GameHistoryListView(Context context,int roleID) {
super(context);
mContext = context;
// TODO Auto-generated constructor stub
this.setBackgroundResource(R.drawable.detail_bg);
this.setAdapter(new DetailListAdapter(roleID));
}
private String ts(int i)
{
return Integer.toString(i);
}
public class DetailListAdapter extends BaseAdapter {
ArrayList<AddDateRoleGame> list;
// List<ListItem> list = new ArrayList<ListItem>();
public DetailListAdapter(int roleID) {
DBTBRoleGames dbtable = new DBTBRoleGames(DBHelper.sharedInstance());
this.list = dbtable.getAllGameForRoleID(roleID);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new ListItemView(mContext);
}
AddDateRoleGame rg = list.get(position);
((ListItemView) convertView).setData(rg);
return convertView;
}
}
public class ListItemView extends RelativeLayout {
ImageView heroIcon;
TextView gameResultView;
TextView addDateView;
RatioFixer rf;
public ListItemView(Context context) {
super(context);
rf = RatioFixer.getGlobalRatioFixer();
RelativeLayout relativeLayout = new RelativeLayout(context);
relativeLayout.setBackgroundResource(R.drawable.main_list_item_bg);
this.addView(relativeLayout, rf.getLayoutParam(768, 200, 0, 0));
heroIcon = new ImageView(context);
relativeLayout.addView(heroIcon,rf.getLayoutParam(120, 180, 30, 10));
gameResultView = new TextView(context);
gameResultView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 4.45f * 10.0f * rf.getRatio());
gameResultView.setTextColor(Color.parseColor("#FFF8C6"));
gameResultView.setGravity(Gravity.CENTER);
relativeLayout.addView(gameResultView, rf.getLayoutParam(120, 120, 190, 40));
addDateView = new TextView(context);
addDateView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 4.45f * 9.0f * rf.getRatio());
addDateView.setTextColor(Color.parseColor("#FFF8C6"));
addDateView.setGravity(Gravity.CENTER);
relativeLayout.addView(addDateView, rf.getLayoutParam(330, 120, 300, 40));
}
public void setData(AddDateRoleGame rg) {
heroIcon.setImageResource(RoleType.getRoleRes(rg.getEnemyRoleType()));
gameResultView.setText(rg.getIsWin() ? "Win":"Lose");
addDateView.setText(rg.getAddDate());
}
}
}
| true |
8946fe14ec84426d8e6cc0017a54f85f877d5afb | Java | Minarajaa/homework2 | /src/exotp2/De.java | UTF-8 | 328 | 2.046875 | 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 exotp2;
/**
*
* @author 1997
*/
public class De {
public int hasard() {
return (int) (Math.random() * 6) + 1;
}
}
| true |
d567aeeceae14cacb691bbd1af7442631ecb9cc1 | Java | sametkaya/Java_Swing_Programming | /Swing_Friday_Coding/Swing_Working/src/Work_1/Soru_1.java | UTF-8 | 10,832 | 2.265625 | 2 | [
"MIT"
] | permissive | /*
* 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 Work_1;
import java.awt.Color;
import java.awt.Point;
import java.util.StringTokenizer;
import javax.swing.DefaultListModel;
/**
*
* @author samet
*/
public class Soru_1 extends javax.swing.JFrame {
/**
* Creates new form Soru_1
*/
public Soru_1() {
initComponents();
jComboBox1.addItem("şili");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btn_click = new javax.swing.JButton();
btn_new = new javax.swing.JButton();
jCheckBox1 = new javax.swing.JCheckBox();
btn_kac = new javax.swing.JButton();
jComboBox1 = new javax.swing.JComboBox<>();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btn_click.setText("Click");
btn_click.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_clickActionPerformed(evt);
}
});
getContentPane().add(btn_click, new org.netbeans.lib.awtextra.AbsoluteConstraints(89, 13, -1, -1));
btn_new.setText("New");
btn_new.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_newActionPerformed(evt);
}
});
getContentPane().add(btn_new, new org.netbeans.lib.awtextra.AbsoluteConstraints(103, 68, -1, -1));
jCheckBox1.setText("Visible");
jCheckBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jCheckBox1ItemStateChanged(evt);
}
});
getContentPane().add(jCheckBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(151, 13, -1, -1));
btn_kac.setText("Kac");
btn_kac.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
btn_kacFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
btn_kacFocusLost(evt);
}
});
btn_kac.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_kacMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_kacMouseExited(evt);
}
});
getContentPane().add(btn_kac, new org.netbeans.lib.awtextra.AbsoluteConstraints(107, 122, -1, -1));
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "İstanbul", "Ankara", "Bayburt", "Sivas", "Giresun" }));
getContentPane().add(jComboBox1, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 70, 170, 40));
jList1.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "fdsfsd" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(jList1);
getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 180, 170, 110));
jButton1.setText("Aktar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 130, -1, -1));
jButton2.setText("jButton2");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 130, -1, -1));
jLabel1.setText("jLabel1");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 180, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_clickActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_clickActionPerformed
// TODO add your handling code here:
this.dispose();
}//GEN-LAST:event_btn_clickActionPerformed
private void btn_newActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_newActionPerformed
// TODO add your handling code here:
Soru_1 newsoru1=new Soru_1();
newsoru1.setDefaultCloseOperation(3);
newsoru1.setVisible(true);
}//GEN-LAST:event_btn_newActionPerformed
private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCheckBox1ItemStateChanged
// TODO add your handling code here:
if(jCheckBox1.isSelected())
{
btn_click.setVisible(false);
}
else
{
btn_click.setVisible(true);
}
}//GEN-LAST:event_jCheckBox1ItemStateChanged
private void btn_kacMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_kacMouseEntered
// TODO add your handling code here:
//btn_kac.setLocation(new Point(btn_kac.getLocation().x+5,btn_kac.getLocation().y+5 ));
btn_kac.setVisible(false);
}//GEN-LAST:event_btn_kacMouseEntered
private void btn_kacMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_kacMouseExited
// TODO add your handling code here:
btn_kac.setVisible(true);
}//GEN-LAST:event_btn_kacMouseExited
private void btn_kacFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_btn_kacFocusGained
// TODO add your handling code here:
btn_kac.setBackground(Color.red);
}//GEN-LAST:event_btn_kacFocusGained
private void btn_kacFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_btn_kacFocusLost
// TODO add your handling code here:
btn_kac.setBackground(Color.green);
}//GEN-LAST:event_btn_kacFocusLost
DefaultListModel lm=new DefaultListModel();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
for (int i = 0; i < jComboBox1.getItemCount(); i++) {
lm.addElement(jComboBox1.getItemAt(i));
}
jList1.setModel(lm);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
jLabel1.setText(jComboBox1.getSelectedItem().toString());
String satir = "[0]|1|[2]|4|3";
StringTokenizer st = new StringTokenizer(satir, "|");
while (st.hasMoreElements()) {
String mytoken1 = st.nextElement().toString();
if(!(mytoken1.contains("[") || mytoken1.contains("]")))
{
System.out.println(mytoken1);
}
// StringTokenizer st2 = new StringTokenizer(mytoken1, " ");
// while (st2.hasMoreElements()) {
// String mytoken2 = st2.nextElement().toString();
// // System.out.println(mytoken2);
// mytoken2 = mytoken2.replace("[", "").replace("]", "");
// System.out.println(mytoken2);
// }
}
}//GEN-LAST:event_jButton2ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Soru_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Soru_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Soru_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Soru_1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Soru_1().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_click;
private javax.swing.JButton btn_kac;
private javax.swing.JButton btn_new;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JCheckBox jCheckBox1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JList<String> jList1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| true |
92169104958015fd24326d6d1964be2ba5cf81d1 | Java | Guozha/BUY_SERVER | /src/com/guozha/buyserver/persistence/beans/BuyOrderMenuGoods.java | UTF-8 | 2,327 | 1.867188 | 2 | [] | no_license | package com.guozha.buyserver.persistence.beans;
import com.guozha.buyserver.dal.object.AbstractDO;
public class BuyOrderMenuGoods extends AbstractDO {
private Integer orderMenuGoodsId;
private Integer orderId;
private Integer orderMenuId;
private Integer marketId;
private Integer goodsId;
private String goodsName;
private String goodsImg;
private Integer backTypeId;
private String unit;
private Integer unitPrice;
private Integer amount;
private Integer price;
private Integer goodsStar;
public Integer getOrderMenuGoodsId() {
return orderMenuGoodsId;
}
public void setOrderMenuGoodsId(Integer orderMenuGoodsId) {
this.orderMenuGoodsId = orderMenuGoodsId;
}
public Integer getOrderId() {
return orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
public Integer getOrderMenuId() {
return orderMenuId;
}
public void setOrderMenuId(Integer orderMenuId) {
this.orderMenuId = orderMenuId;
}
public Integer getMarketId() {
return marketId;
}
public void setMarketId(Integer marketId) {
this.marketId = marketId;
}
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsImg() {
return goodsImg;
}
public void setGoodsImg(String goodsImg) {
this.goodsImg = goodsImg;
}
public Integer getBackTypeId() {
return backTypeId;
}
public void setBackTypeId(Integer backTypeId) {
this.backTypeId = backTypeId;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public Integer getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Integer unitPrice) {
this.unitPrice = unitPrice;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Integer getGoodsStar() {
return goodsStar;
}
public void setGoodsStar(Integer goodsStar) {
this.goodsStar = goodsStar;
}
}
| true |
c9a441de1c02a47d10dcd9f5fc0b007e887f0a47 | Java | wangpengda1210/Tic-Tac-Toe-with-AI | /Problems/Finding an alignment using a scoring function/src/Main.java | UTF-8 | 2,741 | 3.15625 | 3 | [] | no_license | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
String[] result = findEditAlignment(scanner.nextLine(), scanner.nextLine());
System.out.println(result[2]);
System.out.println(result[0]);
System.out.println(result[1]);
}
private static String[] findEditAlignment(String first, String second) {
int[][] distanceMatrix = findEditDistance(first, second);
int i = first.length();
int j = second.length();
StringBuilder firstBuilder = new StringBuilder();
StringBuilder secondBuilder = new StringBuilder();
while (i > 0 || j > 0) {
if (i > 0 && j > 0 &&
distanceMatrix[i][j] == distanceMatrix[i - 1][j - 1] +
match(first.charAt(i - 1), second.charAt(j - 1))) {
firstBuilder.append(first.charAt(i - 1));
secondBuilder.append(second.charAt(j - 1));
i--;
j--;
} else if (j > 0 && distanceMatrix[i][j] == distanceMatrix[i][j - 1] + 2) {
firstBuilder.append("-");
secondBuilder.append(second.charAt(j - 1));
j--;
} else if (i > 0 && distanceMatrix[i][j] == distanceMatrix[i - 1][j] + 2) {
firstBuilder.append(first.charAt(i - 1));
secondBuilder.append("-");
i--;
}
}
return new String[] { firstBuilder.reverse().toString(),
secondBuilder.reverse().toString(),
String.valueOf(distanceMatrix[first.length()][second.length()]) };
}
private static int[][] findEditDistance(String first, String second) {
int[][] distanceMatrix = new int[first.length() + 1][second.length() + 1];
for (int i = 0; i < first.length() + 1; i++) {
distanceMatrix[i][0] = i * 2;
}
for (int i = 0; i < second.length() + 1; i++) {
distanceMatrix[0][i] = i * 2;
}
for (int i = 1; i < first.length() + 1; i++) {
for (int j = 1; j < second.length() + 1; j++) {
int insCost = distanceMatrix[i][j - 1] + 2;
int delCost = distanceMatrix[i - 1][j] + 2;
int subCost = distanceMatrix[i - 1][j - 1] +
match(first.charAt(i - 1), second.charAt(j - 1));
distanceMatrix[i][j] = Math.min(Math.min(insCost, delCost), subCost);
}
}
return distanceMatrix;
}
private static int match(char char1, char char2) {
return char1 == char2 ? 0 : 3;
}
} | true |
fe72c3c3830ccdff281cf6476dfce5393a3ed3fd | Java | booky0081/NewPatientMonitor | /app/src/main/java/BluetoothParser/FluidPaser.java | UTF-8 | 1,516 | 2.703125 | 3 | [] | no_license | package BluetoothParser;
public class FluidPaser extends BaseParser {
private String weight;
private int type = 0;
@Override
public boolean Parse(String message) {
if (message.startsWith("urination:")) {
type = 1;
weight = message.substring("urination:".length());
}
else if (message.startsWith("panWt:")) {
type = 2;
weight = message.substring("panWt:".length());
}
else if (message.startsWith("FCWater:")) {
type = 3;
weight = message.substring("FCWater:".length());
}
else if (message.startsWith("drink:")) {
type = 4;
weight = message.substring("drink:".length());
}
else if (message.startsWith("beforeAdd:")) {
type = 5;
weight = message.substring("beforeAdd:".length());
}
else if (message.startsWith("bottleWt:")) {
type = 6;
weight = message.substring("bottleWt:".length());
}
else if (message.startsWith("urineBag:")) {
type = 7;
weight = message.substring("urineBag:".length());
}
else if (message.startsWith("beforeEmptyWt:")) {
type =7;
weight = message.substring("beforeEmptyWt:".length());
}
return true;
}
public int getType(){
return this.type;
}
public String getWeight(){
return this.weight;
}
}
| true |
2c32ae12b35aa82a7ae0e791ec0cd8973b9bb372 | Java | huanghetang/leyou | /leyou-item/leyou-item-service/src/test/java/com/leyou/Test.java | UTF-8 | 1,370 | 2.078125 | 2 | [] | no_license | package com.leyou;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.pojo.Category;
import com.leyou.pojo.CategoryBrand;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Map;
/**
* @author zhoumo
* @datetime 2018/7/20 12:07
* @desc
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ItemServiceApp.class)
public class Test {
@Autowired
private CategoryMapper categoryMapper;
@org.junit.Test
public void test1(){
Category category = new Category();
category.setId(null);
category.setName("景甜");
category.setIsParent(false);
category.setParentId(0l);
category.setSort(1);
int i = categoryMapper.insertSelective(category);
System.out.println("i = " + i);
}
@org.junit.Test
public void test2(){
List<Map<String, String>> map = categoryMapper.queryCategoryAndBrand(325402l);
System.out.println("map = " + map);
}
@org.junit.Test
public void test3(){
List<CategoryBrand> categoryBrands = categoryMapper.queryCategoryBrand(325402l);
System.out.println("categoryBrands = " + categoryBrands);
}
}
| true |
bebee5a87b95477468a7283edaea4cd1b9e3d3ae | Java | asifkhalil212/CMDBJavaApplication | /CMDBAppServerMappings/src/main/java/com/jmh/cmdb/serviceImpl/ApplicationServiceImpl.java | UTF-8 | 1,067 | 2.40625 | 2 | [] | no_license | package com.jmh.cmdb.serviceImpl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jmh.cmdb.daoImpl.ApplicationDAOImpl;
import com.jmh.cmdb.entity.Application;
@Service
public class ApplicationServiceImpl {
@Autowired
private ApplicationDAOImpl applicationDAOImpl;
public Collection<Application> findAllAppsDetails(){
System.out.println("serviceclass");
List<Application> apps = new ArrayList<>();
for(Application app: applicationDAOImpl.findAll()){
apps.add(app);
}
//System.out.println(apps);
return apps;
}
public void deleteApp(Integer id) {
applicationDAOImpl.deleteById(id);
}
public Application findApplication(int id)
{
System.out.println(applicationDAOImpl.findById(id));
return applicationDAOImpl.findById(id).orElse(null);
}
public void saveApplication(Application application) {
applicationDAOImpl.save(application);
}
}
| true |
5b4e5dde99d52eb6b2ca4017635c1a433658c8f7 | Java | deepcloudlabs/dcl364-2021-may-31 | /stockmarket/src/com/example/stockmarket/repository/StockRepository.java | UTF-8 | 313 | 2.09375 | 2 | [
"MIT"
] | permissive | package com.example.stockmarket.repository;
import java.util.Collection;
import com.example.stockmarket.entity.Stock;
public interface StockRepository extends GenericRepository<Stock, String> {
Collection<Stock> findByCompany(String company);
Collection<Stock> findByPriceBetween(double min, double max);
}
| true |
7caae623d9decd4e76d53db6c52c6f1f59cb8f3d | Java | Poloz/org.roadside | /src/org/roadside/items/Item.java | UTF-8 | 146 | 1.671875 | 2 | [] | no_license |
package org.roadside.items;
/**
*
* @author Poloz
*/
public class Item {
public int weight;
public int condition;
}
| true |
868837e7af1a91f186e8cfac83f7e5b57a0f373b | Java | Dilschat/GA4GH-Demo | /biosamples-v4-demo/utils/xml/src/main/java/uk/ac/ebi/biosamples/utils/XmlFragmenter.java | UTF-8 | 4,603 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | package uk.ac.ebi.biosamples.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* Utility class that reads an input stream of XML (with SAX) and calls a
* provided handler for each element of interest. The handler is given a DOM
* populated element to do something with
*
*
* @author faulcon
*
*/
@Service
public class XmlFragmenter {
private SAXParserFactory factory = SAXParserFactory.newInstance();
private XmlFragmenter() {};
public void handleStream(InputStream inputStream, String encoding, ElementCallback... callback)
throws ParserConfigurationException, SAXException, IOException {
InputSource isource = new InputSource(inputStream);
isource.setEncoding(encoding);
DefaultHandler handler = new FragmentationHandler(callback);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(isource, handler);
}
private class FragmentationHandler extends DefaultHandler {
private final List<ElementCallback> callbacks;
private final List<Document> doc;
private final List<Boolean> inRegion;
private final List<Stack<Element>> elementStack;
private final List<StringBuilder> textBuffer;
public FragmentationHandler(ElementCallback... callbacks) {
this.callbacks = Arrays.asList(callbacks);
this.doc = new ArrayList<>(this.callbacks.size());
this.inRegion = new ArrayList<>(this.callbacks.size());
this.elementStack = new ArrayList<>(this.callbacks.size());
this.textBuffer = new ArrayList<>(this.callbacks.size());
for (ElementCallback callback : callbacks) {
doc.add(null);
inRegion.add(false);
elementStack.add(new Stack<Element>());
textBuffer.add(new StringBuilder());
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
for (int i = 0; i < callbacks.size(); i++) {
if (callbacks.get(i).isBlockStart(uri, localName, qName, attributes)) {
inRegion.set(i, true);
doc.set(i, DocumentHelper.createDocument());
}
if (inRegion.get(i)) {
addTextIfNeeded(i);
Element el;
if (elementStack.get(i).size() == 0) {
el = doc.get(i).addElement(qName);
} else {
el = elementStack.get(i).peek().addElement(qName);
}
for (int j = 0; j < attributes.getLength(); j++) {
el.addAttribute(attributes.getQName(j), attributes.getValue(j));
}
elementStack.get(i).push(el);
}
}
}
@Override
public void endElement(String uri, String localName, String qName) {
for (int i = 0;i < callbacks.size(); i++) {
if (inRegion.get(i)) {
addTextIfNeeded(i);
elementStack.get(i).pop();
if (elementStack.get(i).isEmpty()) {
// do something with the element
try {
callbacks.get(i).handleElement(doc.get(i).getRootElement());
} catch (Exception e) {
throw new RuntimeException(e);
}
inRegion.set(i, false);
doc.set(i, null);
}
}
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
for (int i = 0;i < callbacks.size(); i++) {
if (inRegion.get(i)) {
textBuffer.get(i).append(ch, start, length);
}
}
}
// Outputs text accumulated under the current node
private void addTextIfNeeded(int i) {
if (textBuffer.get(i).length() > 0) {
Element el = elementStack.get(i).peek();
el.addText(textBuffer.get(i).toString());
textBuffer.get(i).delete(0, textBuffer.get(i).length());
}
}
};
public interface ElementCallback {
/**
* This function is passed a DOM element of interest for further processing.
*
* @param e
* @throws Exception
*/
public void handleElement(Element e) throws Exception;
/**
* This functions determines if an element is of interest and should be handled
* once parsing is complete.
*
* @param uri
* @param localName
* @param qName
* @param attributes
* @return
*/
public boolean isBlockStart(String uri, String localName, String qName, Attributes attributes);
}
}
| true |
c304a2792dc7ad51a85f3b61656baefac3f0b0ca | Java | tigersshi/Bookie | /app/src/main/java/com/karambit/bookie/InfoActivity.java | UTF-8 | 9,165 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package com.karambit.bookie;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.karambit.bookie.helper.ElevationScrollListener;
import com.karambit.bookie.helper.TypefaceSpan;
/**
* This activity takes an integer array extra for which info titles are expanded on activity start.
*/
public class InfoActivity extends AppCompatActivity {
public static final int INFO_CODE_REQUESTS = 0;
public static final int INFO_CODE_TRANSACTIONS = 1;
public static final int INFO_CODE_POINT = 2;
public static final int INFO_CODE_FEEDBACK = 3;
public static final int INFO_CODE_CREDITS = 4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
SpannableString s = new SpannableString(getResources().getString(R.string.info));
s.setSpan(new TypefaceSpan(this, "comfortaa.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
s.setSpan(new AbsoluteSizeSpan((int) convertDpToPixel(18, this)), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(s);
actionBar.setElevation(0);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_primary_text_color);
final ScrollView infoScrollView = (ScrollView) findViewById(R.id.infoScrollView);
infoScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
int scrollY = infoScrollView.getScrollY();
actionBar.setElevation(ElevationScrollListener.getActionbarElevation(scrollY));
}
});
final ImageView infoDropDown_0 = (ImageView) findViewById(R.id.infoDropDownImage_0);
final ImageView infoDropDown_1 = (ImageView) findViewById(R.id.infoDropDownImage_1);
final ImageView infoDropDown_2 = (ImageView) findViewById(R.id.infoDropDownImage_2);
final ImageView infoDropDown_3 = (ImageView) findViewById(R.id.infoDropDownImage_3);
final ImageView infoDropDown_4 = (ImageView) findViewById(R.id.infoDropDownImage_4);
final TextView infoContent_0 = (TextView) findViewById(R.id.infoContent_0);
final TextView infoContent_1 = (TextView) findViewById(R.id.infoContent_1);
final TextView infoContent_2 = (TextView) findViewById(R.id.infoContent_2);
final TextView infoContent_3 = (TextView) findViewById(R.id.infoContent_3);
final TextView infoContent_4 = (TextView) findViewById(R.id.infoContent_4);
LinearLayout infoContainer_0 = (LinearLayout) findViewById(R.id.infoTitleContainer_0);
LinearLayout infoContainer_1 = (LinearLayout) findViewById(R.id.infoTitleContainer_1);
LinearLayout infoContainer_2 = (LinearLayout) findViewById(R.id.infoTitleContainer_2);
LinearLayout infoContainer_3 = (LinearLayout) findViewById(R.id.infoTitleContainer_3);
LinearLayout infoContainer_4 = (LinearLayout) findViewById(R.id.infoTitleContainer_4);
// Expanded info titles on beginning of activity
int[] infoCodes = getIntent().getIntArrayExtra("info_codes");
if (infoCodes != null) {
for (int code : infoCodes) {
switch (code) {
case INFO_CODE_REQUESTS:
infoDropDown_1.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
infoContent_1.setVisibility(View.VISIBLE);
break;
case INFO_CODE_TRANSACTIONS:
infoDropDown_0.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
infoContent_0.setVisibility(View.VISIBLE);
break;
case INFO_CODE_POINT:
infoDropDown_2.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
infoContent_2.setVisibility(View.VISIBLE);
break;
case INFO_CODE_FEEDBACK:
infoDropDown_3.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
infoContent_3.setVisibility(View.VISIBLE);
break;
case INFO_CODE_CREDITS:
infoDropDown_4.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
infoContent_4.setVisibility(View.VISIBLE);
break;
}
}
}
infoContainer_0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (infoContent_0.getVisibility() == View.GONE) {
infoContent_0.setVisibility(View.VISIBLE);
infoDropDown_0.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
} else {
infoContent_0.setVisibility(View.GONE);
infoDropDown_0.setImageResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
}
}
});
infoContainer_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (infoContent_1.getVisibility() == View.GONE) {
infoContent_1.setVisibility(View.VISIBLE);
infoDropDown_1.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
} else {
infoContent_1.setVisibility(View.GONE);
infoDropDown_1.setImageResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
}
}
});
infoContainer_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (infoContent_2.getVisibility() == View.GONE) {
infoContent_2.setVisibility(View.VISIBLE);
infoDropDown_2.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
} else {
infoContent_2.setVisibility(View.GONE);
infoDropDown_2.setImageResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
}
}
});
infoContainer_3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (infoContent_3.getVisibility() == View.GONE) {
infoContent_3.setVisibility(View.VISIBLE);
infoDropDown_3.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
} else {
infoContent_3.setVisibility(View.GONE);
infoDropDown_3.setImageResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
}
}
});
infoContainer_4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (infoContent_4.getVisibility() == View.GONE) {
infoContent_4.setVisibility(View.VISIBLE);
infoDropDown_4.setImageResource(R.drawable.ic_keyboard_arrow_up_black_24dp);
} else {
infoContent_4.setVisibility(View.GONE);
infoDropDown_4.setImageResource(R.drawable.ic_keyboard_arrow_down_black_24dp);
}
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
finish();
return true;
}
default:
return false;
}
}
/**
* This method converts dp unit to equivalent pixels, depending on device density.
*
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
* @param context Context to get resources and device specific display metrics
* @return A float value to represent px equivalent to dp depending on device density
*/
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return px;
}
}
| true |