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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bf22b37b114cea19df050c75080b299a62865abd | Java | CodeQuit/mmo-network.old | /Server/lib-server/src/ru/mmo/global/network/utils/NetworkUtil.java | UTF-8 | 4,652 | 2.6875 | 3 | [] | no_license | package ru.mmo.global.network.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;
import ru.mmo.global.network.engine.buffer.NioBuffer;
/**
* @author Felixx
*/
public class NetworkUtil
{
/**
* check if IP address match pattern
* *
*
* @param pattern
* *.*.*.* , 192.168.1.0-255 , *
* @param address
* -
* 192.168.1.1<BR>
* <code>address = 10.2.88.12 pattern = *.*.*.* result: true<BR>
* address = 10.2.88.12 pattern = * result: true<BR>
* address = 10.2.88.12 pattern = 10.2.88.12-13 result: true<BR>
* address = 10.2.88.12 pattern = 10.2.88.13-125 result: false<BR></code>
* @return true if address match pattern
* @author KID, -Nemesiss-
*/
static final byte[] HEX_CHAR_TABLE = {(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f'};
private static Logger _log = Logger.getLogger(NetworkUtil.class);
public static boolean checkIPMatching(String pattern, String address)
{
if(pattern.equals("*.*.*.*") || pattern.equals("*"))
{
return true;
}
String[] mask = pattern.split("\\.");
String[] ip_address = address.split("\\.");
for(int i = 0; i < mask.length; i++)
{
if(mask[i].equals("*") || mask[i].equals(ip_address[i]))
{
// none
}
else if(mask[i].contains("-"))
{
byte min = Byte.parseByte(mask[i].split("-")[0]);
byte max = Byte.parseByte(mask[i].split("-")[1]);
byte ip = Byte.parseByte(ip_address[i]);
if(ip < min || ip > max)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
public static String printData(byte[] data, int len)
{
final StringBuilder result = new StringBuilder(len * 4);
int counter = 0;
for(int i = 0; i < len; i++)
{
if(counter % 16 == 0)
{
result.append(fillHex(i, 4) + ": ");
}
result.append(fillHex(data[i] & 0xff, 2) + " ");
counter++;
if(counter == 16)
{
result.append(" ");
int charpoint = i - 15;
for(int a = 0; a < 16; a++)
{
int t1 = 0xFF & data[charpoint++];
if(t1 > 0x1f && t1 < 0x80)
{
result.append((char) t1);
}
else
{
result.append('.');
}
}
result.append("\n");
counter = 0;
}
}
int rest = data.length % 16;
if(rest > 0)
{
for(int i = 0; i < 17 - rest; i++)
{
result.append(" ");
}
int charpoint = data.length - rest;
for(int a = 0; a < rest; a++)
{
int t1 = 0xFF & data[charpoint++];
if(t1 > 0x1f && t1 < 0x80)
{
result.append((char) t1);
}
else
{
result.append('.');
}
}
result.append("\n");
}
return result.toString();
}
public static String fillHex(int data, int digits)
{
String number = Integer.toHexString(data);
for(int i = number.length(); i < digits; i++)
{
number = "0" + number;
}
return number;
}
public static String printData(byte[] raw)
{
return printData(raw, raw.length);
}
public static String printData(java.nio.ByteBuffer buf)
{
byte[] data = new byte[buf.remaining()];
buf.get(data);
String hex = printData(data, data.length);
buf.position(buf.position() - data.length);
return hex;
}
public static String printData(NioBuffer buf)
{
byte[] data = new byte[buf.remaining()];
buf.get(data);
String hex = printData(data, data.length);
buf.position(buf.position() - data.length);
return hex;
}
public static String getHex(byte b)
{
String result = "";
int index = 0;
int v = b & 0xFF;
byte[] hex = new byte[2];
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
try
{
result = new String(hex, "ASCII");
}
catch(Exception e)
{}
return result;
}
public static String getHex(byte[] raw)
{
String result = "";
int index = 0;
byte[] hex = new byte[2 * raw.length];
for(byte b : raw)
{
int v = b & 0xFF;
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
try
{
result = new String(hex, "ASCII");
}
catch(Exception e)
{}
return result;
}
/** Переводит строку с IP или домена в массив байт айпишника */
public static byte[] parseIpToBytes(String address)
{
InetAddress inetAddr = null;
try
{
inetAddr = InetAddress.getByName(address);
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
return inetAddr.getAddress();
}
} | true |
e052888b1f82710c455a8348d54d35eed04ab92b | Java | cmFodWx5YWRhdjEyMTA5/NewsReader_MVVM_And_LiveData | /app/src/main/java/com/example/mvvmandlivedata/db/ResultDatabase.java | UTF-8 | 1,773 | 2.234375 | 2 | [] | no_license | package com.example.mvvmandlivedata.db;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.example.mvvmandlivedata.until.FieldsConverter;
import com.example.mvvmandlivedata.until.Result;
import static androidx.room.Room.databaseBuilder;
@Database(entities = Result.class, version = 1)
@TypeConverters({FieldsConverter.class})
public abstract class ResultDatabase extends RoomDatabase{
public static ResultDatabase instance;
public abstract ResultDao resultDao();
public static synchronized ResultDatabase getInstance(Context context) {
if(instance == null){
instance = databaseBuilder(context, ResultDatabase.class, "result_database")
.fallbackToDestructiveMigration()
.addCallback(callback)
.build();
}
return instance;
}
private static RoomDatabase.Callback callback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
new PopulateDbAsyncTask(instance).execute();
}
};
private static class PopulateDbAsyncTask extends AsyncTask<Result, Void, Void> {
private ResultDao resultDao;
public PopulateDbAsyncTask(ResultDatabase resultDatabase) {
this.resultDao = resultDatabase.resultDao();
}
@Override
protected Void doInBackground(Result... results) {
resultDao.insert(results[0]);
return null;
}
}
}
| true |
55b0f4e54da38cb893b9a7988b8e9c1e9e6bc0a8 | Java | manhot001/StoreApplication | /app/src/main/java/mitgo/iii/org/tw/storeapplication/API/Member/MemberLiked.java | UTF-8 | 3,011 | 2.5625 | 3 | [] | no_license | package mitgo.iii.org.tw.storeapplication.API.Member;
import android.app.Activity;
import android.content.SharedPreferences;
import org.json.JSONException;
import org.json.JSONObject;
import mitgo.iii.org.tw.storeapplication.Model.APIurlSet;
import mitgo.iii.org.tw.storeapplication.Model.NetWork;
/*
商品收藏狀態api
1.新增post method
2.判斷使用者是否登入,是則塞入member_id進url
2.1否則則塞入-1,回傳結果為false
3.註冊監聽事件
4.若回傳值不為null則解析回傳狀態
5.若回傳值為null則回傳網路錯誤
6.解析後回傳result,message
*/
public class MemberLiked {
APIurlSet book = new APIurlSet();
private SharedPreferences sharedPreferences;
private final String memberSharedPreferences = "member";
private final String member_idSharedPreferences = "member_id";
private NetWork.GetMethod method = null;
private MemberLikedInterface memberLikedInterface = new MemberLikedInterface() {
@Override
public void onDoneListener(Boolean result, String message) {
//如果沒有setOnDoneListener進入到這裡不會crash
}
};
public MemberLiked(final Activity activity, Integer product_id) {
final NetWork apimethod = new NetWork(activity);
sharedPreferences = activity.getSharedPreferences(memberSharedPreferences, 0);
final Integer member_id = sharedPreferences.getInt(member_idSharedPreferences,-1);
method = apimethod.setGetMethod(book.getProductLiked(product_id, member_id),book.time_out);
method.setOnDoneListener(new NetWork.OnDoneListener() {
@Override
public void onDone(Object result) {
if(result!=null){
Object response = parseMemberLike((JSONObject) result);
if(response instanceof Boolean){
memberLikedInterface.onDoneListener(true, null);
}else if(response instanceof String) {
memberLikedInterface.onDoneListener(false, response.toString());
}
}else memberLikedInterface.onDoneListener(false,apimethod.netErr);
}
});
}
//解析商品收藏狀態結果
private Object parseMemberLike(JSONObject input) {
try {
if (Boolean.valueOf(input.getString("result").toString())) {
return true;
} else {
String err = input.getString("message");
return err;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
public void setOnDoneListener(MemberLikedInterface callBack){
this.memberLikedInterface = callBack;
}
public interface MemberLikedInterface {
public void onDoneListener(Boolean result,String message);
}
public void Cancel(Boolean cancel){
if(method!=null)method.cancel(cancel);
}
}
| true |
221414874aac2750fea314c47c5b3018e4cd28a0 | Java | kevinramsey/CZ-Plugins | /MDCheck/src/main/java/com/melissadata/kettle/support/MDControlSpaceKeyAdapter.java | UTF-8 | 8,708 | 1.953125 | 2 | [] | no_license | package com.melissadata.kettle.support;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeSet;
import com.melissadata.kettle.MDCheckMeta;
import org.eclipse.jface.window.DefaultToolTip;
import org.eclipse.jface.window.ToolTip;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.i18n.GlobalMessages;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.gui.GUIResource;
/**
* Borrowed and adapted from the kettle ControlSpaceKeyAdapter class
*/
public class MDControlSpaceKeyAdapter extends KeyAdapter {
private static final String MDCHECK_RESULT_CODE = "MDCheck.ResultCode.";
private static Class<?> PKG = MDCheckMeta.class;
private static final PropsUI props = PropsUI.getInstance();
private Text control;
private int checkTypes;
private Shell shell;
private List list;
private String[] resultCodes;
public MDControlSpaceKeyAdapter(Text control, int checkTypes) {
this.control = control;
this.checkTypes = checkTypes;
}
@Override
public void keyPressed(KeyEvent e) {
// CTRL-<SPACE> --> Display list of result codes
if (isHotKey(e)) {
e.doit = false;
// textField.setData(TRUE) indicates we have transitioned from the textbox to list mode...
// This will be set to false when the list selection has been processed
// and the list is being disposed of.
control.setData(Boolean.TRUE);
// Drop down a list of result codes...
Rectangle bounds = control.getBounds();
Point location = GUIResource.calculateControlPosition(control);
shell = new Shell(control.getShell(), SWT.NONE);
shell.setSize(bounds.width, 200);
shell.setLocation(location.x, location.y + bounds.height);
shell.setLayout(new FillLayout());
list = new List(shell, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL);
props.setLook(list);
list.setItems(getResultCodes());
final DefaultToolTip toolTip = new DefaultToolTip(list, ToolTip.RECREATE, true);
// toolTip.setImage(GUIResource.getInstance().getImageSpoon());
toolTip.setHideOnMouseDown(true);
toolTip.setRespectMonitorBounds(true);
toolTip.setRespectDisplayBounds(true);
toolTip.setPopupDelay(350);
list.addSelectionListener(new SelectionAdapter() {
// Enter or double-click: picks the variable
//
@Override
public synchronized void widgetDefaultSelected(SelectionEvent e) {
applyChanges();
}
// Select a variable name: display the value in a tool tip
//
@Override
public void widgetSelected(SelectionEvent event) {
if (list.getSelectionCount() <= 0) { return; }
Rectangle shellBounds = shell.getBounds();
String rc = list.getSelection()[0];
int i = rc.indexOf(" - ");
if (i != 0) {
rc = rc.substring(0, i);
}
String rcDescription = getResultCodeDetail(rc);
if (rcDescription != null) {
toolTip.setText(rcDescription);
toolTip.hide();
toolTip.show(new Point(shellBounds.width, 0));
}
}
});
list.addKeyListener(new KeyAdapter() {
@Override
public synchronized void keyPressed(KeyEvent e) {
if ((e.keyCode == SWT.CR) && ((e.keyCode & SWT.CONTROL) == 0) && ((e.keyCode & SWT.SHIFT) == 0)) {
applyChanges();
}
}
});
list.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent event) {
shell.dispose();
if (!control.isDisposed()) {
control.setData(Boolean.FALSE);
}
}
});
shell.open();
}
}
/*
* Add the text to the control
*/
private void applyChanges() {
if (control.isDisposed()) { return; }
if (list.getSelectionCount() <= 0) { return; }
String rc = list.getSelection()[0];
int i = rc.indexOf(" - ");
if (i != 0) {
rc = rc.substring(0, i);
}
i = rc.indexOf(".");
if (i != 0) {
rc = rc.substring(i + 1);
}
rc = "[" + rc + "]";
control.insert(rc);
if (!shell.isDisposed()) {
shell.dispose();
}
if (!control.isDisposed()) {
control.setData(Boolean.FALSE);
}
}
/*
* Returns the description of a result code
*/
private String getResultCodeDetail(String rc) {
String description = BaseMessages.getString(PKG, MDCHECK_RESULT_CODE + rc + ".Detail");
if ((description != null) && description.startsWith("!")) {
description = null;
}
return description;
}
/*
* Returns the list of currently defined result codes
*/
private String[] getResultCodes() {
if (resultCodes == null) {
java.util.List<String> rcs = new ArrayList<String>();
boolean doName = (checkTypes & MDCheckMeta.MDCHECK_NAME) != 0;
boolean doAddress = (checkTypes & MDCheckMeta.MDCHECK_ADDRESS) != 0;
boolean doEmail = (checkTypes & MDCheckMeta.MDCHECK_EMAIL) != 0;
boolean doPhone = (checkTypes & MDCheckMeta.MDCHECK_PHONE) != 0;
boolean doSmartMover = (checkTypes & MDCheckMeta.MDCHECK_SMARTMOVER) != 0;
boolean doMatchUp = (checkTypes & MDCheckMeta.MDCHECK_MATCHUP) != 0;
boolean doMatchUpGlobal = (checkTypes & MDCheckMeta.MDCHECK_MATCHUP_GLOBAL) != 0;
boolean doIpLocator = (checkTypes & MDCheckMeta.MDCHECK_IPLOCATOR) != 0;
if (doName) {
rcs.addAll(getResultCodes("Name", "NS")); // name success
rcs.addAll(getResultCodes("Name", "NE")); // name error
}
if (doAddress || doSmartMover) {
// Address verify is called as part of smart mover
rcs.addAll(getResultCodes("Addr", "AS")); // address success
rcs.addAll(getResultCodes("Addr", "AE")); // address error
rcs.addAll(getResultCodes("Addr", "AC")); // address check
if (!doSmartMover) {
// Geocoder is NOT called during smart mover
rcs.addAll(getResultCodes("Geo", "GS")); // geo-coder success
rcs.addAll(getResultCodes("Geo", "GE")); // geo-coder error
rcs.addAll(getResultCodes("Geo", "DE")); // geo-coder error
}
}
if (doEmail) {
rcs.addAll(getResultCodes("Email", "ES")); // email success
rcs.addAll(getResultCodes("Email", "EE")); // email error
rcs.addAll(getResultCodes("Email", "DE")); // email error
}
if (doPhone) {
rcs.addAll(getResultCodes("Phone", "PS")); // phone success
rcs.addAll(getResultCodes("Phone", "PE")); // phone error
}
if (doSmartMover) {
rcs.addAll(getResultCodes("Smart", "CS"));
rcs.addAll(getResultCodes("Smart", "CM"));
}
if (doMatchUp || doMatchUpGlobal) {
rcs.addAll(getResultCodes("Matchup", "MS")); // matchup success
}
if (doIpLocator) {
rcs.addAll(getResultCodes("IpLocator", "IS"));
rcs.addAll(getResultCodes("IpLocator", "IE"));
}
resultCodes = rcs.toArray(new String[rcs.size()]);
}
return resultCodes;
}
/*
* Returns the defined error codes that begin with the given prefix
*/
private Collection<String> getResultCodes(String category, String prefix) {
Set<String> rcs = new TreeSet<String>();
ResourceBundle bundle = GlobalMessages.getBundle(PKG.getPackage().getName() + ".messages.messages", PKG);
if (bundle != null) {
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()) {
String rc = keys.nextElement();
String categoryPrefix = MDCHECK_RESULT_CODE + category + ".";
if (rc.startsWith(categoryPrefix + prefix)) {
rc = rc.substring(categoryPrefix.length());
int i = rc.indexOf(".");
if (i != -1) {
rc = rc.substring(0, i);
}
String msg = BaseMessages.getString(PKG, categoryPrefix + rc);
rc = category + "." + rc + " - " + msg;
rcs.add(rc);
}
}
}
return rcs;
}
/**
* Determines if this is the ctrl-space hot key. Handles language sensitivities.
*
* @param e
* @return
*/
private boolean isHotKey(KeyEvent e) {
if (System.getProperty("user.language").equals("zh")) {
return (e.character == ' ') && ((e.stateMask & SWT.CONTROL) != 0) && ((e.stateMask & SWT.ALT) != 0);
} else if (System.getProperty("os.name").startsWith("Mac OS X")) {
return (e.character == ' ') && ((e.stateMask & SWT.MOD1) != 0) && ((e.stateMask & SWT.ALT) == 0);
} else {
return (e.character == ' ') && ((e.stateMask & SWT.CONTROL) != 0) && ((e.stateMask & SWT.ALT) == 0);
}
}
}
| true |
f41c97e309cf9adec3751c730a929ae1aba7352b | Java | valoeghese/Zoesteria-2 | /src/main/java/valoeghese/zoesteria/common/util/LossyDoubleCache.java | UTF-8 | 1,842 | 3 | 3 | [
"MIT"
] | permissive | package valoeghese.zoesteria.common.util;
import java.util.Arrays;
public class LossyDoubleCache implements DoubleGridOperator {
public LossyDoubleCache(int size, DoubleGridOperator operator) {
int arrSize = 1; // 2^n = 2 * (2^(n-1))
int nextArrSize;
while (true) {
if ((nextArrSize = (arrSize << 1)) > size) {
break;
}
arrSize = nextArrSize;
}
if (arrSize > size) {
throw new RuntimeException("LossyCache " + arrSize + " must be smaller or equal to given Cache size! (" + size + ")");
}
this.mask = arrSize - 1;
this.positions = new long[arrSize];
this.data = new double[arrSize];
this.operator = operator;
Arrays.fill(this.positions, Long.MAX_VALUE);
}
private final int mask;
private final long[] positions;
private final double[] data;
private final DoubleGridOperator operator;
@Override
public double get(int x, int y) {
try {
long pos = asLong(x, y);
int loc = mix5(x, y) & this.mask;
if (this.positions[loc] != pos) {
this.positions[loc] = pos;
return this.data[loc] = this.operator.get(x, y);
} else {
return this.data[loc];
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("LossyCache broke! You'll need to restart your game (or perhaps just reload the world), sadly. If this issue persists, let me (Valoeghese) know!");
throw new RuntimeException(e);
}
}
private static int mix5(int a, int b) {
return (((a >> 4) & 1) << 9) |
(((b >> 4) & 1) << 8) |
(((a >> 3) & 1) << 7) |
(((b >> 3) & 1) << 6) |
(((a >> 2) & 1) << 5) |
(((b >> 2) & 1) << 4) |
(((a >> 1) & 1) << 3) |
(((b >> 1) & 1) << 2) |
((a & 1) << 1) |
(b & 1);
}
// from minecraft
public static long asLong(int chunkX, int chunkZ) {
return (long)chunkX & 4294967295L | ((long)chunkZ & 4294967295L) << 32;
}
}
| true |
003bfba6933dac7224820e668107248110aa9ae1 | Java | jay-yeo/designPatterns | /src/main/java/facade/Ford.java | UTF-8 | 369 | 2.53125 | 3 | [] | no_license | package facade;
public class Ford implements CarShop, Garage {
private static int generatedId = 0;
public void carId() {
generatedId++;
System.out.println("F" + generatedId);
}
public void price() {
System.out.println(" 3.000.000 USD");
}
public void getEngine() {
System.out.println("American V8");
}
}
| true |
b74cb6abc749e1e0dd4e151c65266a51c90f215a | Java | AnKoushinist/hikaru-bottakuri-slot | /keiji/source/java/com/vungle/publisher/g.java | UTF-8 | 1,418 | 1.859375 | 2 | [] | no_license | package com.vungle.publisher;
import com.vungle.publisher.gm.a;
import dagger.MembersInjector;
import javax.inject.Provider;
/* compiled from: vungle */
public final class g implements MembersInjector<b> {
static final /* synthetic */ boolean a = (!g.class.desiredAssertionStatus());
private final Provider<ql> b;
private final Provider<a> c;
private final Provider<a> d;
public final /* synthetic */ void injectMembers(Object obj) {
b bVar = (b) obj;
if (bVar == null) {
throw new NullPointerException("Cannot inject members into a null reference");
}
bVar.eventBus = (ql) this.b.get();
bVar.b = (a) this.c.get();
bVar.c = (a) this.d.get();
}
private g(Provider<ql> provider, Provider<a> provider2, Provider<a> provider3) {
if (a || provider != null) {
this.b = provider;
if (a || provider2 != null) {
this.c = provider2;
if (a || provider3 != null) {
this.d = provider3;
return;
}
throw new AssertionError();
}
throw new AssertionError();
}
throw new AssertionError();
}
public static MembersInjector<b> a(Provider<ql> provider, Provider<a> provider2, Provider<a> provider3) {
return new g(provider, provider2, provider3);
}
}
| true |
d05ab0130e16515b2da72b1dcd5d45346163556a | Java | jether2011/alura-classes | /microservice-alura-online-course/microsservicos-parte-2-workspace-aula-5/loja/src/main/java/br/com/alura/microservice/loja/dto/InfoPedidoDTO.java | UTF-8 | 418 | 1.992188 | 2 | [
"MIT"
] | permissive | package br.com.alura.microservice.loja.dto;
public class InfoPedidoDTO {
private Long id;
private Integer tempoDePreparo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getTempoDePreparo() {
return tempoDePreparo;
}
public void setTempoDePreparo(Integer tempoDePreparo) {
this.tempoDePreparo = tempoDePreparo;
}
}
| true |
f830e586c5914f69a395ad821e31a2b0064e4c83 | Java | kkagill/Decompiler-IQ-Option | /Source Code/5.5.1/sources/com/pro100svitlo/creditCardNfcReader/iso7816emv/c.java | UTF-8 | 2,176 | 1.96875 | 2 | [] | no_license | package com.pro100svitlo.creditCardNfcReader.iso7816emv;
import com.pro100svitlo.creditCardNfcReader.a.a;
import com.pro100svitlo.creditCardNfcReader.model.enums.CountryCodeEnum;
import com.pro100svitlo.creditCardNfcReader.model.enums.CurrencyEnum;
import com.pro100svitlo.creditCardNfcReader.model.enums.TransactionTypeEnum;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
/* compiled from: EmvTerminal */
public final class c {
private static final SecureRandom egw = new SecureRandom();
public static byte[] a(e eVar) {
Object bytes;
Object obj = new byte[eVar.getLength()];
if (eVar.aRJ() == b.eeF) {
f fVar = new f();
fVar.fZ(true);
fVar.ga(true);
bytes = fVar.getBytes();
} else if (eVar.aRJ() == b.edL) {
bytes = a.lj(org.apache.commons.lang3.c.g(String.valueOf(CountryCodeEnum.FR.getNumeric()), eVar.getLength() * 2, "0"));
} else if (eVar.aRJ() == b.edg) {
bytes = a.lj(org.apache.commons.lang3.c.g(String.valueOf(CurrencyEnum.EUR.getISOCodeNumeric()), eVar.getLength() * 2, "0"));
} else if (eVar.aRJ() == b.ecY) {
bytes = a.lj(new SimpleDateFormat("yyMMdd").format(new Date()));
} else if (eVar.aRJ() == b.eda) {
bytes = new byte[]{(byte) TransactionTypeEnum.PURCHASE.getKey()};
} else if (eVar.aRJ() == b.edq) {
bytes = a.lj("00");
} else if (eVar.aRJ() == b.eed) {
bytes = new byte[]{(byte) 34};
} else if (eVar.aRJ() == b.eeb) {
bytes = new byte[]{(byte) -32, (byte) -96, (byte) 0};
} else if (eVar.aRJ() == b.eem) {
bytes = new byte[]{(byte) -114, (byte) 0, (byte) -80, (byte) 80, (byte) 5};
} else if (eVar.aRJ() == b.eeU) {
bytes = a.lj("7345123215904501");
} else {
if (eVar.aRJ() == b.eef) {
egw.nextBytes(obj);
}
bytes = null;
}
if (bytes != null) {
System.arraycopy(bytes, 0, obj, 0, Math.min(bytes.length, obj.length));
}
return obj;
}
}
| true |
33aec8f1028bcb21248339d070326025e5694f84 | Java | superbrandmall/microservice | /onlineleasing-file/src/main/java/com/sbm/module/onlineleasing/file/upload/biz/IUploadMethodService.java | UTF-8 | 442 | 1.742188 | 2 | [] | no_license | package com.sbm.module.onlineleasing.file.upload.biz;
import com.sbm.module.onlineleasing.base.fileuploaddetail.domain.TOLFileUploadDetail;
import org.springframework.web.multipart.MultipartFile;
public interface IUploadMethodService {
/**
* 上传数据具体实现方法
*
* @param detail
* @param file
*/
void uploadMethod(TOLFileUploadDetail detail, MultipartFile file);
void setFileInfo(TOLFileUploadDetail detail);
}
| true |
369b1d8564233aa0d51d174ee47dac45fcfb1bb4 | Java | liqi328/TrustRanker | /src/diseasesimilarity/DiseaseDiseaseSimilarity.java | UTF-8 | 364 | 2.3125 | 2 | [] | no_license | package diseasesimilarity;
public interface DiseaseDiseaseSimilarity {
public double getTwoDiseaseSimilarity(String omimId1, String omimId2);
/*
* similarity = (1 - alpha) * thisDiseaseSimilarity + alpha * anotherDiseaseSimilarity
* */
public void addDiseaseDiseaseSimilarity(DiseaseDiseaseSimilarity anotherDiseaseSimilarity, double alpha);
}
| true |
55e667948a3c7beb973d59172f63c0c72e7958dd | Java | jdbaltazar/Pilmico | /src/common/entity/product/Product.java | UTF-8 | 12,721 | 2.546875 | 3 | [] | no_license | package common.entity.product;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import common.entity.product.exception.NegativeValueException;
import common.entity.product.exception.NotEnoughQuantityException;
import common.entity.product.exception.ZeroKilosPerSackException;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@OneToMany(mappedBy = "product", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Price> prices = new HashSet<Price>();
@Column(name = "kilos_per_sack")
private double kilosPerSack;
@Column
private boolean available;
@Column(name = "quantity_in_sack")
private double sacks;
@Column(name = "quantity_in_kilo")
private double kilosOnDisplay;
@ManyToOne(cascade = CascadeType.PERSIST)
@JoinColumn(name = "category")
private Category category;
@Column(name = "allow_alert")
private boolean allowAllert;
public Product() {
super();
}
public Product(String name, Date dateUpdated, double pricePerSack, double pricePerKilo, double kilosPerSack, boolean available, double sacks,
double kilosOnDisplay, Category category, boolean allowAllert) {
super();
this.name = name;
prices.add(new Price(this, dateUpdated, pricePerSack, pricePerKilo));
this.kilosPerSack = kilosPerSack;
this.available = available;
this.sacks = sacks;
this.kilosOnDisplay = kilosOnDisplay;
this.category = category;
this.allowAllert = allowAllert;
}
public Product(String name, String description, Date dateUpdated, double pricePerSack, double pricePerKilo, double kilosPerSack,
boolean available, double sacks, double kilosOnDisplay, Category category, boolean allowAllert) {
super();
this.name = name;
this.description = description;
prices.add(new Price(this, dateUpdated, pricePerSack, pricePerKilo));
this.kilosPerSack = kilosPerSack;
this.available = available;
this.sacks = sacks;
this.kilosOnDisplay = kilosOnDisplay;
this.category = category;
this.allowAllert = allowAllert;
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Price> getPriceHistory() {
return orderPriceHistory(copyPrices(prices));
}
private List<Price> copyPrices(Set<Price> orig) {
List<Price> copy = new ArrayList<Price>();
for (Price p : orig) {
Price p2 = new Price(p.getProduct(), p.getDateUpdated(), p.getPricePerSack(), p.getPricePerKilo());
p2.setId(p.getId());
copy.add(p2);
}
return copy;
}
private List<Price> orderPriceHistory(List<Price> prices) {
List<Price> ordered = new ArrayList<Price>();
int origSize = prices.size();
for (int i = 0; i < origSize; i++) {
Price temp = getMostRecentPriceIn(prices);
ordered.add(temp);
prices.remove(prices.indexOf(temp));
}
return ordered;
}
private Price getMostRecentPriceIn(List<Price> prices) {
Price mostRecent = null;
for (Price p : prices) {
if (mostRecent == null)
mostRecent = p;
else {
if (p.getDateUpdated().after(mostRecent.getDateUpdated()))
mostRecent = p;
}
}
return mostRecent;
}
public void addPrice(Price price) {
prices.add(price);
}
public Price getCurrentPrice() {
Price currentPrice = null;
for (Price p : prices) {
if (currentPrice == null)
currentPrice = p;
else {
if (p.getDateUpdated().after(currentPrice.getDateUpdated()))
currentPrice = p;
}
}
return currentPrice;
}
public double getCurrentPricePerSack() {
Price p = getCurrentPrice();
if (p != null)
return getCurrentPrice().getPricePerSack();
return 0;
}
public double getCurrentPricePerKilo() {
Price p = getCurrentPrice();
if (p != null)
return getCurrentPrice().getPricePerKilo();
return 0;
}
public double getKilosPerSack() {
return kilosPerSack;
}
public String getKilosPerSackDescription() {
String s = "";
if (kilosPerSack == 0d) {
s = "0";
} else {
// check if has no decimal portions
if ((kilosPerSack * 100) % 100 != 0) {
s = String.format("%.2f", kilosPerSack);
} else {
s = (int) kilosPerSack + "";
}
}
return s;
}
public void setKilosPerSack(double kilosPerSack) throws Exception {
if (kilosPerSack < 0d)
throw new NegativeValueException();
this.kilosPerSack = kilosPerSack;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public double getSacks() {
return sacks;
}
public String getSacksDescription() {
String s = "";
if (sacks == 0d) {
s = "0";
} else {
// check if has no decimal portions
if ((sacks * 100) % 100 != 0) {
s = String.format("%.2f", sacks);
} else {
s = (int) sacks + "";
}
}
return s;
}
public String getKilosOnDisplayDescription() {
String s = "";
if (kilosOnDisplay == 0d) {
s = "0";
} else {
// check if has no decimal portions
if ((kilosOnDisplay * 100) % 100 != 0) {
s = String.format("%.2f", kilosOnDisplay);
} else {
s = (int) kilosOnDisplay + "";
}
}
return s;
}
public double getKilosOnDisplay() {
return kilosOnDisplay;
}
public double getTotalQuantityInSack() {
return totalSacks(sacks, kilosOnDisplay, kilosPerSack);
}
public double getTotalQuantityInKilo() {
return totalKilos(sacks, kilosOnDisplay, kilosPerSack);
}
public String getQuantityDescription() {
String desc = "";
if (getTotalQuantityInKilo() == 0d) {
desc = "0 kilos remaining";
} else {
if (sacks > 0d) {
desc = sacks + " sack/s";
if (kilosOnDisplay > 0d)
desc = desc + " and ";
}
if (kilosOnDisplay > 0d) {
desc = desc + kilosOnDisplay + " kilo/s";
}
desc = desc + " remaining";
}
return desc;
}
public String getSimplifiedQuantity() {
String desc = "";
if (getTotalQuantityInKilo() == 0d) {
desc = "0";
} else {
String s1 = "0";
String s2 = "0";
// check if has no decimal portions
if ((sacks * 100) % 100 != 0) {
s1 = String.format("%.2f", sacks);
} else {
s1 = (int) sacks + "";
}
if ((kilosOnDisplay * 100) % 100 != 0) {
s2 = String.format("%.2f", kilosOnDisplay);
} else {
s2 = (int) kilosOnDisplay + "";
}
desc = s1 + ", " + s2;
}
return desc;
}
public void setQuantity(double sacks, double kilosOnDisplay) throws Exception {
if (valid(sacks, kilosOnDisplay, kilosPerSack)) {
this.sacks = sacks;
this.kilosOnDisplay = kilosOnDisplay;
}
}
public void incrementQuantity(double sacksIncrement, double kilosOnDisplayIncrement) throws Exception {
if (valid(sacksIncrement, kilosOnDisplayIncrement, kilosPerSack)) {
ProductQuantity pQuantity = computeIncrementResult(sacks, kilosOnDisplay, kilosPerSack, sacksIncrement, kilosOnDisplayIncrement);
this.sacks = pQuantity.getQuantityInSack();
this.kilosOnDisplay = pQuantity.getQuantityInKilo();
}
}
public void decrementQuantity(double decrementQuantityInSack, double decrementQuantityInKilo) throws Exception {
if (valid(decrementQuantityInSack, decrementQuantityInKilo, kilosPerSack)) {
ProductQuantity pQuantity = computeDecrementResult(sacks, kilosOnDisplay, kilosPerSack, decrementQuantityInSack, decrementQuantityInKilo);
this.sacks = pQuantity.getQuantityInSack();
this.kilosOnDisplay = pQuantity.getQuantityInKilo();
}
}
public boolean isOnDisplay() {
return (kilosOnDisplay > 0d);
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public boolean isAllowAllert() {
return allowAllert;
}
public void setAllowAllert(boolean allowAllert) {
this.allowAllert = allowAllert;
}
public String toString() {
return name;
}
public static boolean valid(double sacks, double kilos, double kilosPerSack) throws NegativeValueException, ZeroKilosPerSackException {
if (sacks < 0d || kilos < 0d)
throw new NegativeValueException();
if (kilosPerSack <= 0d)
throw new ZeroKilosPerSackException();
return true;
}
public static boolean validIncrement(double sacks, double kilosOnDisplay, double kilosPerSack, double sacksIncrement,
double kilosOnDisplayIncrement) throws NegativeValueException, ZeroKilosPerSackException {
if (valid(sacksIncrement, kilosOnDisplayIncrement, kilosPerSack)) {
return true;
}
return false;
}
public static boolean validDecrement(double sacks, double kilosOnDisplay, double kilosPerSack, double sacksDecrement,
double kilosOnDisplayDecrement) throws NegativeValueException, NotEnoughQuantityException, ZeroKilosPerSackException {
if (valid(sacksDecrement, kilosOnDisplayDecrement, kilosPerSack)) {
double kilosQuantity = totalKilos(sacks, kilosOnDisplay, kilosPerSack);
double decrementKilosQuantity = totalKilos(sacksDecrement, kilosOnDisplayDecrement, kilosPerSack);
if (decrementKilosQuantity > kilosQuantity)
throw new NotEnoughQuantityException();
}
return true;
}
public static ProductQuantity computeIncrementResult(double sacks, double kilosOnDisplay, double kilosPerSack, double sacksIncrement,
double kilosOnDisplayIncrement) throws NegativeValueException, NotEnoughQuantityException, ZeroKilosPerSackException {
ProductQuantity pQuantity = new ProductQuantity(sacks, kilosOnDisplay, kilosPerSack);
if (validIncrement(sacks, kilosOnDisplay, kilosPerSack, sacksIncrement, kilosOnDisplayIncrement)) {
pQuantity = new ProductQuantity(sacks + sacksIncrement, kilosOnDisplay + kilosOnDisplayIncrement, kilosPerSack);
}
return pQuantity;
}
public static ProductQuantity computeDecrementResult(double sacks, double kilosOnDisplay, double kilosPerSack, double sacksDecrement,
double kilosOnDisplayDecrement) throws NegativeValueException, NotEnoughQuantityException, ZeroKilosPerSackException {
ProductQuantity pQuantity = new ProductQuantity(sacks, kilosOnDisplay, kilosPerSack);
if (validDecrement(sacks, kilosOnDisplay, kilosPerSack, sacksDecrement, kilosOnDisplayDecrement)) {
if (kilosOnDisplayDecrement <= kilosOnDisplay) {
pQuantity = new ProductQuantity(sacks - sacksDecrement, kilosOnDisplay - kilosOnDisplayDecrement, kilosPerSack);
} else {
double kilosQuantity = totalKilos(sacks, kilosOnDisplay, kilosPerSack);
double decrementKilosQuantity = totalKilos(sacksDecrement, kilosOnDisplayDecrement, kilosPerSack);
kilosQuantity -= decrementKilosQuantity;
pQuantity = simplify(kilosQuantity, kilosPerSack);
}
}
return pQuantity;
}
public static double totalSacks(double sacks, double kilos, double klsPerSk) {
return sacks + (kilos / klsPerSk);
}
public static double totalKilos(double sacks, double kilos, double klsPerSk) {
return (sacks * klsPerSk) + kilos;
}
public static ProductQuantity simplify(double totalQuantityInKilo, double kilosPerSack) throws NegativeValueException, ZeroKilosPerSackException {
if (valid(0d, totalQuantityInKilo, kilosPerSack)) {
double rawResult = totalQuantityInKilo / kilosPerSack;
// rounded two decimal result
double roundedTwodecimalResult = Math.round(rawResult * 100.0d) / 100.0d;
double sacks = Math.floor(roundedTwodecimalResult);
// double kilos = ((roundedTwodecimalResult -
// Math.floor(roundedTwodecimalResult)) * 100.0d) / 100.0d;
double kilos = totalQuantityInKilo % kilosPerSack;
ProductQuantity pq = new ProductQuantity(sacks, kilos, kilosPerSack);
return pq;
} else {
throw new NegativeValueException();
}
}
}
| true |
2be6902edd75808d178b2e302ca3fe5450ccf694 | Java | Lee-jh01/healthychallenge | /src/main/java/member/controller/CheckController.java | UTF-8 | 2,237 | 2.171875 | 2 | [] | no_license | package member.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import common.controller.SuperClass;
import dao.MemberDao;
@Controller
public class CheckController extends SuperClass {
@Autowired
@Qualifier("mdao")
private MemberDao mdao;
@Autowired
private MemberMailSendService mailsender;
@RequestMapping(value="emailCheck.me", method= RequestMethod.GET)
public @ResponseBody String emailCheck(
@RequestParam("email") String email) {
String result = mdao.emailCheck(email)+"";
return result;
}
@RequestMapping(value="alterStatus.me", method = RequestMethod.GET)
public String alterStatus(
@RequestParam("email") String email,
@RequestParam("key") String key) {
int cnt = mdao.AlterStatus(email, key);
System.out.println("AlterStatus 성공 여부 : "+cnt);
return "meInsertSuccess";
}
// 이메일 찾기
@RequestMapping(value = "emailSearch.me", method = RequestMethod.POST)
@ResponseBody
public String emailSearch(
@RequestParam("name") String name,
@RequestParam("birth") String birth) {
System.out.println("check mapping 들어옴");
System.out.println("name : "+name);
System.out.println("birth : "+birth);
String result = mdao.searchEmail(name, birth);
System.out.println("result : "+result);
return result;
}
// 비밀번호 찾기
@RequestMapping(value = "passwordSearch.me", method = RequestMethod.GET)
@ResponseBody
public String passwordSearch(
@RequestParam("email") String email,
@RequestParam("birth") String birth,
HttpServletRequest request) {
System.out.println("여기 들어왔습니다!");
int cnt = mailsender.mailSendWithPassword(email, birth, request);
String result = cnt + "";
System.out.println("메일 보내기 완료!");
System.out.println(result);
return result;
}
}
| true |
3497ee7f7f1a066d55accf788874a865d66a8c1d | Java | hondacrv2560/ClientCarService | /app/src/main/java/com/example/client/Models/Client.java | UTF-8 | 1,502 | 2.484375 | 2 | [] | no_license | package com.example.client.Models;
import java.io.Serializable;
public class Client implements Serializable {
public String UserId;
public String nameSurnameNewClient;
public String numPhoneNewClient;
public String govNumberCarNewClient;
public String manufacturerCarNewClient;
public String modelCarNewClient;
public String setDataBirthday;
public Client(){
}
public Client(String userId, String nameSurnameNewClient, String numPhoneNewClient, String govNumberCarNewClient, String manufacturerCarNewClient, String modelCarNewClient, String setDataBirthday) {
UserId = userId;
this.nameSurnameNewClient = nameSurnameNewClient;
this.numPhoneNewClient = numPhoneNewClient;
this.govNumberCarNewClient = govNumberCarNewClient;
this.manufacturerCarNewClient = manufacturerCarNewClient;
this.modelCarNewClient = modelCarNewClient;
this.setDataBirthday = setDataBirthday;
}
public String getNameSurnameNewClient() {
return nameSurnameNewClient;
}
public String getNumPhoneNewClient() {
return numPhoneNewClient;
}
public String getGovNumberCarNewClient() {
return govNumberCarNewClient;
}
public String getManufacturerCarNewClient() {
return manufacturerCarNewClient;
}
public String getModelCarNewClient() {
return modelCarNewClient;
}
public String getSetDataBirthday() {
return setDataBirthday;
}
}
| true |
70ea6242cafbae9d29f43de75d1bec99fa371439 | Java | Jeffery336699/EMWMatrix | /EMWMatrix2/src/main/java/cc/emw/mobile/project/entities/Column.java | UTF-8 | 266 | 1.773438 | 2 | [] | no_license | package cc.emw.mobile.project.entities;
import java.io.Serializable;
/**
* Created by jven.wu on 2016/5/12.
*/
public class Column implements Serializable {
public String Header;
public int Width;
public boolean IsText;
public boolean IsValue;
}
| true |
8a815b976022244625925832097e13e6c849c496 | Java | DeJayDev/discord-rpc | /src/main/java/net/arikia/dev/drpc/DiscordRPC.java | UTF-8 | 2,850 | 1.65625 | 2 | [
"MIT"
] | permissive | <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.arikia.dev</groupId>
<artifactId>discord-rpc</artifactId>
<name>DiscordRPC</name>
<version>1.5.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>4.5.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.github.Vatuu</groupId>
<artifactId>discord-rpc-binaries</artifactId>
<version>3.3.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>unpack</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
<configuration>
<includeGroupIds>com.github.Vatuu</includeGroupIds>
<includeArtifactIds>discord-rpc-binaries</includeArtifactIds>
<outputDirectory>${project.build.directory}/binaries-resources</outputDirectory>
<overWriteReleases>true</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<filtering>false</filtering>
<directory>${project.build.directory}/binaries-resources</directory>
</resource>
<resource>
<filtering>false</filtering>
<directory>${basedir}/src/main/resources</directory>
</resource>
</resources>
<finalName>discord-rpc</finalName>
</build>
</project>
| true |
3e1cb031e722e9be64bcf9ea1cfcfc1db630b2df | Java | TimParrotte/DailyArchaeology | /src/main/java/com/dailyarchaeology/museum_artifacts/domain/HarvardItem.java | UTF-8 | 11,261 | 2 | 2 | [] | no_license | package com.dailyarchaeology.museum_artifacts.domain;
import java.util.List;
public class HarvardItem implements MuseumItem{
private String accessionMethod;
private Integer accessionYear;
private Integer accessLevel; // Maybe an ENUM of (0,1).
private String century;
private String classification;
private Integer classificationId;
private String colors;
private Integer colorCount;
private String commentary;
private String contact;
private Integer contextualtextcount;
private String copyright;
private String creditLine;
private String culture;
private String dated;
private Integer dateBegin;
private Integer dateEnd;
private String dateOfFirstPageView;
private String dateOfLastPageView;
private String department;
private String description;
private String dimensions;
private String division;
private String edition;
private Integer exhibitionCount;
private Integer groupCount;
private Integer id;
private Integer imageCount;
private Integer imagePermissionLevel; // ENUM (0, 1, 2)
private List<HarvardImage> images;
private String labelText;
private String lastUpdate;
private Integer lendingPermissionLevel; // ENUM (0, 1, 2)
private Integer marksCount;
private String medium;
private Integer mediaCount;
private Integer objectId;
private String objectNumber;
private String period;
private Integer periodId;
private Integer peopleCount;
private String primaryImageUrl;
private String provenance;
private Integer publicationCount;
private Integer rank;
private Integer relatedCount;
private List<HarvardSeeAlso> seeAlso;
private String signed;
private String standardReferenceNumber;
private String state;
private String style;
private String technique;
private Integer techniqueId;
private String title;
private Integer titlesCount;
private Integer totalPageViews;
private Integer totalUniquePageViews;
private String url;
private Integer verificationLevel; // ENUM 0-4
private String verificationLevelDescription;
private List<HarvardWorkType> workTypes;
public HarvardItem() {};
public String getAccessionMethod() {
return accessionMethod;
}
public void setAccessionMethod(String accessionMethod) {
this.accessionMethod = accessionMethod;
}
public Integer getAccessionYear() {
return accessionYear;
}
public void setAccessionYear(Integer accessionYear) {
this.accessionYear = accessionYear;
}
public Integer getAccessLevel() {
return accessLevel;
}
public void setAccessLevel(Integer accessLevel) {
this.accessLevel = accessLevel;
}
public String getCentury() {
return century;
}
public void setCentury(String century) {
this.century = century;
}
public String getClassification() {
return classification;
}
public void setClassification(String classification) {
this.classification = classification;
}
public Integer getClassificationId() {
return classificationId;
}
public void setClassificationId(Integer classificationId) {
this.classificationId = classificationId;
}
public String getColors() {
return colors;
}
public void setColors(String colors) {
this.colors = colors;
}
public Integer getColorCount() {
return colorCount;
}
public void setColorCount(Integer colorCount) {
this.colorCount = colorCount;
}
public String getCommentary() {
return commentary;
}
public void setCommentary(String commentary) {
this.commentary = commentary;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public Integer getContextualTextCount() {
return contextualtextcount;
}
public void setContextualTextCount(Integer contextualtextcount) {
this.contextualtextcount = contextualtextcount;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getCreditLine() {
return creditLine;
}
public void setCreditLine(String creditLine) {
this.creditLine = creditLine;
}
public String getCulture() {
return culture;
}
public void setCulture(String culture) {
this.culture = culture;
}
public String getDated() {
return dated;
}
public void setDated(String dated) {
this.dated = dated;
}
public Integer getDateBegin() {
return dateBegin;
}
public void setDateBegin(Integer dateBegin) {
this.dateBegin = dateBegin;
}
public Integer getDateEnd() {
return dateEnd;
}
public void setDateEnd(Integer dateEnd) {
this.dateEnd = dateEnd;
}
public String getDateOfFirstPageView() {
return dateOfFirstPageView;
}
public void setDateOfFirstPageView(String dateOfFirstPageView) {
this.dateOfFirstPageView = dateOfFirstPageView;
}
public String getDateOfLastPageView() {
return dateOfLastPageView;
}
public void setDateOfLastPageView(String dateOfLastPageView) {
this.dateOfLastPageView = dateOfLastPageView;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDimensions() {
return dimensions;
}
public void setDimensions(String dimensions) {
this.dimensions = dimensions;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getEdition() {
return edition;
}
public void setEdition(String edition) {
this.edition = edition;
}
public Integer getExhibitionCount() {
return exhibitionCount;
}
public void setExhibitionCount(Integer exhibitionCount) {
this.exhibitionCount = exhibitionCount;
}
public Integer getGroupCount() {
return groupCount;
}
public void setGroupCount(Integer groupCount) {
this.groupCount = groupCount;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getImageCount() {
return imageCount;
}
public void setImageCount(Integer imageCount) {
this.imageCount = imageCount;
}
public Integer getImagePermissionLevel() {
return imagePermissionLevel;
}
public void setImagePermissionLevel(Integer imagePermissionLevel) {
this.imagePermissionLevel = imagePermissionLevel;
}
public List<HarvardImage> getImages() {
return images;
}
public void setImages(List<HarvardImage> images) {
this.images = images;
}
public String getLabelText() {
return labelText;
}
public void setLabelText(String labelText) {
this.labelText = labelText;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Integer getLendingPermissionLevel() {
return lendingPermissionLevel;
}
public void setLendingPermissionLevel(Integer lendingPermissionLevel) {
this.lendingPermissionLevel = lendingPermissionLevel;
}
public Integer getMarksCount() {
return marksCount;
}
public void setMarksCount(Integer marksCount) {
this.marksCount = marksCount;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public Integer getMediaCount() {
return mediaCount;
}
public void setMediaCount(Integer mediaCount) {
this.mediaCount = mediaCount;
}
public Integer getObjectId() {
return objectId;
}
public void setObjectId(Integer objectId) {
this.objectId = objectId;
}
public String getObjectNumber() {
return objectNumber;
}
public void setObjectNumber(String objectNumber) {
this.objectNumber = objectNumber;
}
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public Integer getPeriodId() {
return periodId;
}
public void setPeriodId(Integer periodId) {
this.periodId = periodId;
}
public Integer getPeopleCount() {
return peopleCount;
}
public void setPeopleCount(Integer peopleCount) {
this.peopleCount = peopleCount;
}
public String getPrimaryImageUrl() {
return primaryImageUrl;
}
public void setPrimaryImageUrl(String primaryImageUrl) {
this.primaryImageUrl = primaryImageUrl;
}
public String getProvenance() {
return provenance;
}
public void setProvenance(String provenance) {
this.provenance = provenance;
}
public Integer getPublicationCount() {
return publicationCount;
}
public void setPublicationCount(Integer publicationCount) {
this.publicationCount = publicationCount;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
public Integer getRelatedCount() {
return relatedCount;
}
public void setRelatedCount(Integer relatedCount) {
this.relatedCount = relatedCount;
}
public List<HarvardSeeAlso> getSeeAlso() {
return seeAlso;
}
public void setSeeAlso(List<HarvardSeeAlso> seeAlso) {
this.seeAlso = seeAlso;
}
public String getSigned() {
return signed;
}
public void setSigned(String signed) {
this.signed = signed;
}
public String getStandardReferenceNumber() {
return standardReferenceNumber;
}
public void setStandardReferenceNumber(String standardReferenceNumber) {
this.standardReferenceNumber = standardReferenceNumber;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
public String getTechnique() {
return technique;
}
public void setTechnique(String technique) {
this.technique = technique;
}
public Integer getTechniqueId() {
return techniqueId;
}
public void setTechniqueId(Integer techniqueId) {
this.techniqueId = techniqueId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getTitlesCount() {
return titlesCount;
}
public void setTitlesCount(Integer titlesCount) {
this.titlesCount = titlesCount;
}
public Integer getTotalPageViews() {
return totalPageViews;
}
public void setTotalPageViews(Integer totalPageViews) {
this.totalPageViews = totalPageViews;
}
public Integer getTotalUniquePageViews() {
return totalUniquePageViews;
}
public void setTotalUniquePageViews(Integer totalUniquePageViews) {
this.totalUniquePageViews = totalUniquePageViews;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getVerificationLevel() {
return verificationLevel;
}
public void setVerificationLevel(Integer verificationLevel) {
this.verificationLevel = verificationLevel;
}
public String getVerificationLevelDescription() {
return verificationLevelDescription;
}
public void setVerificationLevelDescription(String verificationLevelDescription) {
this.verificationLevelDescription = verificationLevelDescription;
}
public List<HarvardWorkType> getWorkTypes() {
return workTypes;
}
public void setWorkTypes(List<HarvardWorkType> workTypes) {
this.workTypes = workTypes;
}
@Override
public UniversalItemDto toUniversalItemDto() {
return null;
}
}
| true |
dbb3db213b6d5de2301d0d60b52d01cad6db5478 | Java | simusco/tour-guide | /src/main/java/com/moma/trip/po/Discovery.java | UTF-8 | 1,648 | 1.953125 | 2 | [] | no_license | package com.moma.trip.po;
import java.util.Date;
public class Discovery {
private String discoveryId;
private String name;
private String description;
private Date publishTime;
private String tags;
private String imageURL;
private String type;
private String author;
private String url;
private String isRec = "no";
public String getDiscoveryId() {
return discoveryId;
}
public void setDiscoveryId(String discoveryId) {
this.discoveryId = discoveryId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getPublishTime() {
return publishTime;
}
public void setPublishTime(Date publishTime) {
this.publishTime = publishTime;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIsRec() {
return isRec;
}
public void setIsRec(String isRec) {
this.isRec = isRec;
}
}
| true |
689fe9a4a4e0d1be0e8ca7f89704c73504bd63f6 | Java | renwfy/BeiAngAir_V4.0s | /beiAngAir_V40s/src/main/java/com/beiang/airdog/net/business/homer/GetDevInfoPair.java | UTF-8 | 2,993 | 2.03125 | 2 | [] | no_license | package com.beiang.airdog.net.business.homer;
import java.util.List;
import com.android.volley.Request.Method;
import com.beiang.airdog.net.business.homer.GetDevInfoPair.ReqGetDevInfo;
import com.beiang.airdog.net.business.homer.GetDevInfoPair.RspGetDevInfo;
import com.beiang.airdog.net.httpcloud.aync.ServerDefinition.APIServerAdrs;
import com.beiang.airdog.net.httpcloud.aync.ServerDefinition.APIServerMethod;
import com.beiang.airdog.net.httpcloud.aync.abs.AbsReqMsg;
import com.beiang.airdog.net.httpcloud.aync.abs.AbsRspMsg;
import com.beiang.airdog.net.httpcloud.aync.abs.AbsSmartNetReqRspPair;
import com.beiang.airdog.net.httpcloud.aync.abs.BaseMsg.ReqMsgBase;
import com.beiang.airdog.net.httpcloud.aync.abs.BaseMsg.RspMsgBase;
import com.beiang.airdog.net.httpcloud.aync.abs.ReqCbk;
import com.google.gson.JsonSerializer;
import com.google.gson.annotations.SerializedName;
public class GetDevInfoPair extends AbsSmartNetReqRspPair<ReqGetDevInfo, RspGetDevInfo>{
public void sendRequest(String ownerId,ReqCbk<RspMsgBase> cbk) {
ReqMsgBase req = new ReqGetDevInfo(ownerId);
sendMsg(req, cbk);
}
public static class ReqGetDevInfo extends AbsReqMsg{
@SerializedName("params")
public GetDevInfoPama pama = new GetDevInfoPama();
public ReqGetDevInfo(String ownerId) {
// TODO Auto-generated constructor stub
pama.ownerId = ownerId;
}
public static class GetDevInfoPama{
@SerializedName("owner_id")
public String ownerId;
}
@Override
public String getReqMethod() {
// TODO Auto-generated method stub
return APIServerMethod.HOMER_GetDevice.getMethod();
}
}
public static class RspGetDevInfo extends AbsRspMsg {
@SerializedName("data")
public List<Data> data;
public static class Data {
@SerializedName("uid")//设备在系统中分配的唯一ID
public int uid;
@SerializedName("nickname")
public String nickname;
@SerializedName("role")//身份
public String role;
@SerializedName("owner_id")//设备ID
public String ownerId;
@SerializedName("ndevice_sn")//子设备ID”
public String ndeviceSn;
@SerializedName("product_id")//产品ID
public String productId;
@SerializedName("status")//online/outline
public String status;
@SerializedName("type")//硬件类型
public String type;
@SerializedName("module")//功能类型
public String module;
}
}
@Override
public String getUri() {
return APIServerAdrs.HOMER;
}
@Override
public Class<RspGetDevInfo> getResponseType() {
return RspGetDevInfo.class;
}
@Override
public int getHttpMethod() {
// TODO Auto-generated method stub
return Method.POST;
}
@Override
public JsonSerializer<ReqGetDevInfo> getExcludeJsonSerializer() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean sendMsg(ReqMsgBase req, ReqCbk<RspMsgBase> cbk) {
// TODO Auto-generated method stub
return sendMsg(req, cbk, req.getTag());
}
}
| true |
d718c9bbe804016d50b1f811ce3339f6dbfa4cd3 | Java | juclopezso/moviles20182 | /Reto9/app/src/main/java/co/edu/unal/empresassqlite/MainActivity.java | UTF-8 | 5,850 | 2.359375 | 2 | [] | no_license | package co.edu.unal.empresassqlite;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import DB.CompanyOperations;
import Model.Company;
public class MainActivity extends AppCompatActivity {
private Button mCreateButton;
private Button mUpdateButton;
private Button mDeleteButton;
private Button mListButton;
private CompanyOperations companyOps;
private static final String EXTRA_COM_ID = "co.edu.unal.empresassqlite.companyId";
private static final String EXTRA_CREATE_UPDATE = "co.edu.unal.empresassqlite.create_update";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCreateButton = (Button) findViewById(R.id.button_create);
mUpdateButton = (Button) findViewById(R.id.button_update);
mDeleteButton = (Button) findViewById(R.id.button_delete);
mListButton = (Button)findViewById(R.id.button_list);
mCreateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,CreateUpdateCompany.class);
i.putExtra(EXTRA_CREATE_UPDATE, "Create");
startActivity(i);
}
});
mUpdateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCompanyIdAndUpdate();
}
});
mDeleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCompanyIdAndDelete();
}
});
mListButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ListAllCompanies.class);
startActivity(i);
}
});
}
public void getCompanyIdAndUpdate(){
LayoutInflater li = LayoutInflater.from(this);
View getCompanyIdView = li.inflate(R.layout.dialog_get_company_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setView(getCompanyIdView);
final EditText userInput = (EditText) getCompanyIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
companyOps = new CompanyOperations(MainActivity.this);
companyOps.open();
try {
companyOps.getCompany( Long.parseLong(userInput.getText().toString()) );
Intent i = new Intent(MainActivity.this, CreateUpdateCompany.class);
i.putExtra(EXTRA_CREATE_UPDATE, "Update");
i.putExtra(EXTRA_COM_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}catch( Exception e ){
Toast.makeText( MainActivity.this, "No company found with the given id.", Toast.LENGTH_SHORT ).show();
}
companyOps.close();
}
}).create()
.show();
}
public void getCompanyIdAndDelete(){
LayoutInflater li = LayoutInflater.from(this);
View getCompanyIdView = li.inflate(R.layout.dialog_get_company_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getCompanyIdView);
final EditText userInput = (EditText) getCompanyIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
companyOps = new CompanyOperations(MainActivity.this);
companyOps.open();
try {
companyOps.deleteCompany( Long.parseLong(userInput.getText().toString()) );
Toast t = Toast.makeText(MainActivity.this,"Company removed",Toast.LENGTH_SHORT);
t.show();
}catch( Exception e ){
Toast.makeText( MainActivity.this, "No company found with the given id.", Toast.LENGTH_SHORT ).show();
}
companyOps.close();
}
}).create()
.show();
}
@Override
protected void onResume() {
super.onResume();
if( companyOps != null ) companyOps.open();
}
@Override
protected void onPause() {
super.onPause();
if( companyOps != null ) companyOps.close();
}
}
| true |
e7e6b8872b92c9eaa4df320f48f562f1697c3dc4 | Java | Julien-Somasundaram/Projet | /MMO/MMO/src/Client.java | WINDOWS-1252 | 1,924 | 2.828125 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
/*
* www.codeurjava.com
*/
public class Client {
public static void main(String[] args) {
Maps maps=new Maps();
final Socket clientSocket;
final ObjectInputStream in;
final ObjectOutputStream out;
final Scanner sc = new Scanner(System.in);//pour lire partir du clavier
try {
clientSocket = new Socket("127.0.0.1",5000);
//flux pour envoyer
out = new ObjectOutputStream(clientSocket.getOutputStream());
in = new ObjectInputStream(clientSocket.getInputStream());
Thread envoyer = new Thread(new Runnable() {
@Override
public void run() {
try {
out.writeObject(maps.Maps);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread recevoir = new Thread(new Runnable() {
ArrayList<Case> maps2=new ArrayList<Case>();
@Override
public void run() {
try {
maps2=(ArrayList<Case>) in.readObject();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
recevoir.start();
} catch (IOException e) {
e.printStackTrace();
}
}
} | true |
9a987476294cddbdadddeac78cfca88111cf95a8 | Java | ssubash/freshandfresh | /freshandfresh/src/main/java/com/freshandfresh/api/util/Constant.java | UTF-8 | 1,650 | 1.773438 | 2 | [] | no_license | package com.freshandfresh.api.util;
public class Constant {
public static final String ROLE_USER = "ROLE_USER";
public static final String ROLE_DELIVERY = "ROLE_DELIVERY";
public static final String ROLE_ADMIN = "ROLE_ADMIN";
/*
* User management operation messages
*/
public static final String USER_REGISTER_SUCCESS = "user.register.success";
public static final String USER_SAVE_SUCCESS = "user.save.success";
public static final String USER_DEACTIVE_SUCCESS = "user.deactive.success";
public static final String USER_ACTIVE_SUCCESS = "user.active.success";
public static final String USER_ADDRESS_SAVE_SUCCESS = "user.address.save.success";
public static final String USER_ADDRESS_DELETE_SUCCESS = "user.address.delete.success";
/*
* Product management operation messages
*/
public static final String PRODUCT_CATEGORY_SAVE_SUCCESS = "product.category.save.success";
public static final String PRODUCT_CATEGORY_DEACTIVE_SUCCESS = "product.category.deactive.success";
public static final String PRODUCT_CATEGORY_ACTIVE_SUCCESS = "product.category.active.success";
public static final String PRODUCT_ITEM_SAVE_SUCCESS = "product.item.save.success";
public static final String PRODUCT_ITEM_DEACTIVE_SUCCESS = "product.item.deactive.success";
public static final String PRODUCT_ITEM_ACTIVE_SUCCESS = "product.item.active.success";
/*
* Order management operation messages
*/
public static final String ORDER_SAVE_SUCCESS = "order.save.success";
public static final String ITEM_NOT_PRESENT = "item.not.select";
public static final String ORDER_INVALID = "order.invalid";
}
| true |
68a6dbe996faef253b40c37dea373c89306cb4d7 | Java | Ahmed-Basalib10/TypesOfMenusInAndroid | /app/src/main/java/com/example/myapplication/MainActivity.java | UTF-8 | 6,586 | 2.203125 | 2 | [] | no_license | package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1,e2;
TextView t;
Button b;
private ActionMode actionMode;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button) findViewById(R.id.bottom);
t =(TextView) findViewById(R.id.t3) ;
e1=(EditText) findViewById(R.id.t1);
e2=(EditText) findViewById(R.id.t2);
// floating contexual menu
registerForContextMenu(e1);
registerForContextMenu(e2);
// action mode contexual menu
t.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if(actionMode!=null){
return false;
}
actionMode=MainActivity.this.startActionMode(actionModeCallBack);
return true;
}
});
}
private ActionMode.Callback actionModeCallBack=new ActionMode.Callback() {
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.action_mode,menu);
mode.setTitle("Choose ur option");
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.i6:
Toast.makeText(MainActivity.this,"share is selected ",Toast.LENGTH_SHORT).show();
mode.finish();
return true;
case R.id.i7:
Toast.makeText(MainActivity.this,"delete is selected ",Toast.LENGTH_SHORT).show();
mode.finish();
return true;
default:
return false;
}
}
@Override
public void onDestroyActionMode(ActionMode mode) {
actionMode=null;
}
};
// floating contexual menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
switch (v.getId()){
case R.id.t1:
getMenuInflater().inflate(R.menu.contextual_menu,menu);
menu.setHeaderTitle("choose one");
break;
case R.id.t2:
getMenuInflater().inflate(R.menu.contextual_menu2,menu);
menu.setHeaderTitle("choose one");
break;
}
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.i1:
Toast.makeText(this,"option1 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.i2:
Toast.makeText(this,"option2 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.i3:
Toast.makeText(this,"option1 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.it4:
Toast.makeText(this,"option2 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.i5:
Toast.makeText(this,"option3 selected",Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
// option menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.t5:
Toast.makeText(this, "share item", Toast.LENGTH_SHORT).show();
return true;
case R.id.it4:
Toast.makeText(this, "call item", Toast.LENGTH_SHORT).show();
return true;
case R.id.it1:
Toast.makeText(this, "setting item", Toast.LENGTH_SHORT).show();
return true;
case R.id.it2:
Toast.makeText(this, "status item", Toast.LENGTH_SHORT).show();
return true;
case R.id.t6:
Toast.makeText(this, "sub1 item", Toast.LENGTH_SHORT).show();
return true;
case R.id.t7:
Toast.makeText(this, "sub2 item", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// popup menu
public void showPopup(View view) {
PopupMenu pm=new PopupMenu(MainActivity.this,view);
pm.getMenuInflater().inflate(R.menu.popup_menu,pm.getMenu());
pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.i8:
Toast.makeText(MainActivity.this,"1 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.i9:
Toast.makeText(MainActivity.this,"2 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.i10:
Toast.makeText(MainActivity.this,"3 selected",Toast.LENGTH_SHORT).show();
return true;
case R.id.i11:
Toast.makeText(MainActivity.this,"4 selected",Toast.LENGTH_SHORT).show();
return true;
default:
return false;
}
}
});
pm.show();
}
}
| true |
2c3c58a77932a888222c86d90888875131e96068 | Java | yejianfengblue/steins-gate-airline | /sga-booking/src/main/java/com/yejianfengblue/sga/booking/config/JacksonCustomization.java | UTF-8 | 394 | 1.71875 | 2 | [] | no_license | package com.yejianfengblue.sga.booking.config;
import com.fasterxml.jackson.databind.Module;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.jackson.datatype.money.MoneyModule;
@Configuration
class JacksonCustomization {
@Bean
public Module moneyModule() {
return new MoneyModule();
}
} | true |
abe29ad80c652c31d2b35e61208adff598fc5355 | Java | JasonTheKitten/bot | /luwu/src/main/java/everyos/bot/luwu/run/command/modules/welcome/WelcomeServer.java | UTF-8 | 3,026 | 2.421875 | 2 | [
"MIT"
] | permissive | package everyos.bot.luwu.run.command.modules.welcome;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import everyos.bot.chat4j.entity.ChatGuild;
import everyos.bot.luwu.core.database.DBDocument;
import everyos.bot.luwu.core.database.DBObject;
import everyos.bot.luwu.core.entity.ChannelID;
import everyos.bot.luwu.core.entity.Connection;
import everyos.bot.luwu.core.entity.Server;
import everyos.bot.luwu.util.Tuple;
import reactor.core.publisher.Mono;
public class WelcomeServer extends Server {
public WelcomeServer(Connection connection, ChatGuild guild, Map<String, DBDocument> documents) {
super(connection, guild, documents);
}
public Mono<WelcomeServerInfo> getInfo() {
return getGlobalDocument().map(doc->{
return new WelcomeServerInfoImp(doc.getObject());
});
}
public Mono<Void> edit(Consumer<WelcomeServerEditSpec> func) {
return getGlobalDocument().flatMap(doc->{
func.accept(new WelcomeServerEditSpecImp(doc.getObject()));
return doc.save();
});
}
private class WelcomeServerEditSpecImp implements WelcomeServerEditSpec {
private DBObject object;
public WelcomeServerEditSpecImp(DBObject object) {
this.object = object;
}
@Override
public void setWelcomeMessage(ChannelID output, String message) {
if (output == null) {
object.remove("wmsg");
object.remove("wmsgc");
return;
}
object.set("wmsg", message);
object.set("wmsgc", output.getLong());
}
@Override
public void setLeaveMessage(ChannelID output, String message) {
if (output == null) {
object.remove("lmsg");
object.remove("lmsgc");
return;
}
object.set("lmsg", message);
object.set("lmsgc", output.getLong());
}
@Override
public WelcomeServerInfo getInfo() {
return new WelcomeServerInfoImp(object);
}
}
private class WelcomeServerInfoImp implements WelcomeServerInfo {
private DBObject object;
public WelcomeServerInfoImp(DBObject object) {
this.object = object;
}
@Override
public Optional<Tuple<ChannelID, String>> getWelcomeMessage() {
if (!object.has("wmsgc")) {
return Optional.empty();
}
ChannelID channelID = new ChannelID(getConnection(),
object.getOrDefaultLong("wmsgc", -1L), getClient().getID());
String message = object.getOrDefaultString("wmsg", "Edge case: this should not be returned");
return Optional.of(Tuple.of(channelID, message));
}
@Override
public Optional<Tuple<ChannelID, String>> getLeaveMessage() {
if (!object.has("lmsgc")) {
return Optional.empty();
}
ChannelID channelID = new ChannelID(getConnection(),
object.getOrDefaultLong("lmsgc", -1L), getClient().getID());
String message = object.getOrDefaultString("lmsg", "Edge case: this should not be returned");
return Optional.of(Tuple.of(channelID, message));
}
}
public static WelcomeServerFactory type = new WelcomeServerFactory();
}
| true |
6c0475e18f7fe6991266bd7e053140053a489e17 | Java | altkachuk/lampsplus | /app/src/main/java/com/zugara/atproj/lampsplus/ui/fragments/ActionsFragment.java | UTF-8 | 7,814 | 1.796875 | 2 | [] | no_license | package com.zugara.atproj.lampsplus.ui.fragments;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.zugara.atproj.lampsplus.R;
import com.zugara.atproj.lampsplus.presenters.ActionsPresenter;
import com.zugara.atproj.lampsplus.ui.fragments.base.BaseFragment;
import com.zugara.atproj.lampsplus.utils.IntentUtils;
import com.zugara.atproj.lampsplus.views.ActionsView;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by andre on 26-Jan-19.
*/
public class ActionsFragment extends BaseFragment implements ActionsView {
@BindView(R.id.canvasButtonHolder)
LinearLayout canvasButtonHolder;
@BindView(R.id.sessionButtonHolder)
LinearLayout sessionButtonHolder;
@BindView(R.id.uploadButton)
Button uploadButton;
@BindView(R.id.mirrorButton)
Button mirrorButton;
@BindView(R.id.copyButton)
Button copyButton;
@BindView(R.id.deleteButton)
Button deleteButton;
@BindView(R.id.shadowButton)
ImageView shadowButton;
@BindView(R.id.completeButton)
Button completeButton;
@BindView(R.id.backButton)
Button backButton;
@BindView(R.id.nextButton)
Button nextButton;
@BindView(R.id.invoiceButton)
Button invoiceButton;
@BindView(R.id.designButton)
Button designButton;
private ActionsPresenter actionsPresenter;
private ProgressDialog progressDialog;
//-------------------------------------------------------------
// Lifecycle override
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_actions, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initPreloader();
actionsPresenter = new ActionsPresenter(getActivity().getApplicationContext(), this);
}
//-------------------------------------------------------------
// Handlers
@OnClick(R.id.uploadButton)
public void onClickUploadButton() {
actionsPresenter.upload();
}
@OnClick(R.id.mirrorButton)
public void onClickMirrorButton() {
actionsPresenter.mirror();
}
@OnClick(R.id.copyButton)
public void onClickCopyButton() {
actionsPresenter.copy();
}
@OnClick(R.id.deleteButton)
public void onClickDeleteButton() {
actionsPresenter.delete();
}
@OnClick(R.id.shadowButton)
public void onClickShadowButon() {
actionsPresenter.increaseShadow();
}
@OnClick(R.id.completeButton)
public void onCompleteButton() {
actionsPresenter.disableCanvas();
actionsPresenter.complete();
}
@OnClick(R.id.backButton)
public void onClickBackButton() {
actionsPresenter.enableCanvas();
actionsPresenter.clearShadow();
actionsPresenter.back();
}
@OnClick(R.id.nextButton)
public void onClickNextButton() {
actionsPresenter.next();
}
@OnClick(R.id.invoiceButton)
public void onClickInvoiceButton() {
actionsPresenter.gotoInvoice();
}
@OnClick(R.id.designButton)
public void onClickDesignButton() {
actionsPresenter.gotoDesign();
}
@OnClick(R.id.sendButton)
public void onClickSendButton() {
actionsPresenter.sendByEmail();
}
@OnClick(R.id.printButton)
public void onClickPrintButton() {
actionsPresenter.print();
}
@OnClick(R.id.newSessionButton)
public void onClickNewSessionButton() {
actionsPresenter.enableCanvas();
actionsPresenter.clear();
actionsPresenter.newSession();
}
//-------------------------------------------------------------
// LoadingView methods
@Override
public void showPreloader() {
progressDialog.show();
}
@Override
public void hidePreloader() {
progressDialog.dismiss();
}
@Override
public void showErrorMessage(String message) {
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.name_has_illegal_characters), Toast.LENGTH_SHORT).show();
}
@Override
public void showErrorMessage(int messageResId) {
showErrorMessage(getString(messageResId));
}
//-------------------------------------------------------------
// ActionsView methods
@Override
public void enableLampButtons(boolean enable) {
mirrorButton.setEnabled(enable);
copyButton.setEnabled(enable);
deleteButton.setEnabled(enable);
if (enable) {
mirrorButton.setAlpha(0.75f);
copyButton.setAlpha(0.75f);
deleteButton.setAlpha(0.75f);
} else {
mirrorButton.setAlpha(1f);
copyButton.setAlpha(1f);
deleteButton.setAlpha(1f);
}
}
@Override
public void gotoCanvasState() {
uploadButton.setVisibility(View.VISIBLE);
mirrorButton.setVisibility(View.VISIBLE);
copyButton.setVisibility(View.VISIBLE);
deleteButton.setVisibility(View.VISIBLE);
completeButton.setVisibility(View.VISIBLE);
backButton.setVisibility(View.GONE);
nextButton.setVisibility(View.GONE);
shadowButton.setVisibility(View.GONE);
}
@Override
public void gotoCompleteState() {
uploadButton.setVisibility(View.GONE);
mirrorButton.setVisibility(View.GONE);
copyButton.setVisibility(View.GONE);
deleteButton.setVisibility(View.GONE);
completeButton.setVisibility(View.GONE);
backButton.setVisibility(View.VISIBLE);
nextButton.setVisibility(View.VISIBLE);
shadowButton.setVisibility(View.VISIBLE);
}
@Override
public void showCanvasButtons() {
canvasButtonHolder.setVisibility(View.VISIBLE);
}
@Override
public void hideCanvasButtons() {
canvasButtonHolder.setVisibility(View.GONE);
}
@Override
public void showSessionButtons() {
sessionButtonHolder.setVisibility(View.VISIBLE);
}
@Override
public void hideSessionButtons() {
sessionButtonHolder.setVisibility(View.GONE);
}
@Override
public void showCreateSessionFragment() {
getActivity().getFragmentManager().findFragmentById(R.id.createSessionFragment).getView().setVisibility(View.VISIBLE);
}
@Override
public void updateShadowButton(float percent) {
int buttonRes = -1;
if (percent == 0) buttonRes = R.mipmap.light_100;
else if (percent < 0.75f) buttonRes = R.mipmap.light_50;
else buttonRes = R.mipmap.light_0;
shadowButton.setImageResource(buttonRes);
}
@Override
public void gotoInvoiceState() {
invoiceButton.setVisibility(View.GONE);
designButton.setVisibility(View.VISIBLE);
}
@Override
public void gotoDesignState() {
invoiceButton.setVisibility(View.VISIBLE);
designButton.setVisibility(View.GONE);
}
//-------------------------------------------------------------
// Private
private void initPreloader() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(getString(R.string.loading));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
}
| true |
f2bf6562031572484545fc8818d7c9d5f74ac519 | Java | saisatish9652/devops | /2.java | UTF-8 | 15 | 1.648438 | 2 | [] | no_license | hi am all good
| true |
70c8e748842764969af9c43e1bbbfc6592bc1391 | Java | bedbanan/Spring-Boot-Blog | /src/main/java/com/lalala/service/impl/AuthorityServiceImpl.java | UTF-8 | 656 | 2.171875 | 2 | [] | no_license | package com.lalala.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lalala.pojo.Authority;
import com.lalala.repository.AuthorityRepository;
import com.lalala.service.AuthorityService;
/*
* AuthorityServiceImpl接口的实现
*/
@Service
public class AuthorityServiceImpl implements AuthorityService{
/*
* 作为Bean标签自动注入 数据库操作s
*/
@Autowired
private AuthorityRepository authorityRepository;
@Override
public Authority getAuthorityById(Long id) {
return authorityRepository.findOne(id); //根据ID查找数据
}
}
| true |
6f9887f77adde524d03b2d8f310adb937ca33a46 | Java | pologood/dianping-cache | /squirrel-client/src/main/java/com/dianping/squirrel/client/config/zookeeper/CacheEvent.java | UTF-8 | 740 | 2.21875 | 2 | [] | no_license | package com.dianping.squirrel.client.config.zookeeper;
public class CacheEvent {
enum CacheEventType {
ServiceChange, CategoryChange, VersionChange, KeyRemove, BatchKeyRemove, ServiceRemove
}
private CacheEventType type;
private Object content;
public CacheEvent() {}
public CacheEvent(CacheEventType type, Object content) {
this.type = type;
this.content = content;
}
public CacheEventType getType() {
return type;
}
public void setType(CacheEventType type) {
this.type = type;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
}
| true |
12a536d4aa5bd896322c7f90c40e3e22047dd72b | Java | robertszczygielski/BankApp | /src/main/java/org/banking/accounts/Account.java | UTF-8 | 1,074 | 3.0625 | 3 | [] | no_license | package org.banking.accounts;
import java.math.BigDecimal;
public abstract class Account {
private BigDecimal balance;
private BigDecimal interests;
private int accountNumber;
private static int numberOfAccounts = 1;
Account() {
accountNumber = numberOfAccounts++;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
if (this.balance == null) {
this.balance = balance;
}
this.balance = this.balance.add(balance);
}
public BigDecimal getInterests() {
return interests;
}
public void setInterests(BigDecimal interests) {
this.interests = interests;
}
public void withdraw(BigDecimal amount) {
this.balance = this.balance.subtract(amount);
}
@Override
public String toString() {
return "Account{" +
"balance=" + balance +
", interests=" + interests +
", accountNumber=" + accountNumber +
'}';
}
}
| true |
fd3026fb0c2a14db0d3e190080ce468bf11b0fd9 | Java | newSue/SFABASE | /src/main/java/com/winchannel/mss/mobile/data/generator/cache/DefaultCompressCacheImpl.java | UTF-8 | 3,093 | 2.65625 | 3 | [] | no_license | package com.winchannel.mss.mobile.data.generator.cache;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* @author xianghui
*
*/
public class DefaultCompressCacheImpl extends AbstractCacheImpl implements Serializable {
private volatile Map<String, Object> cache = new HashMap<String, Object>();
public DefaultCompressCacheImpl() {
}
public DefaultCompressCacheImpl(String name) {
super(name);
}
@Override
public void put(String key, Object obj) {
cache.put(key, gzip((String) obj));
this.setUpdated(System.currentTimeMillis());
}
@Override
public void putAll(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
this.cache.put(entry.getKey(), gzip((String) entry.getValue()));
}
this.setUpdated(System.currentTimeMillis());
}
@Override
public Object get(String key) {
return ungzip((byte[]) cache.get(key));
}
@Override
public boolean containsKey(String key) {
return cache.containsKey(key);
}
@Override
public Object remove(String key) {
return cache.remove(key);
}
@Override
public void destroy() {
if (cache != null) {
cache.clear();
}
}
private static byte[] gzip(String str) {
if (str == null || str.length() == 0) {
return null;
}
ByteArrayOutputStream out = null;
GZIPOutputStream zip = null;
try {
out = new ByteArrayOutputStream();
zip = new GZIPOutputStream(out);
zip.write(str.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return out.toByteArray();
}
private static String ungzip(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
GZIPInputStream gzipis = null;
try {
out = new ByteArrayOutputStream();
in = new ByteArrayInputStream(bytes);
gzipis = new GZIPInputStream(in);
byte[] buffer = new byte[2048];
int offset = -1;
while ((offset = gzipis.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
return out.toString("UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzipis != null) {
try {
gzipis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
}
| true |
dc0069dd80422eb8bd0c6aa7f4b082fd35574ebe | Java | Wnbj/JavaSoftUni | /TextProcessingAndRegex/src/ExtractWords.java | UTF-8 | 493 | 3.25 | 3 | [] | no_license | import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExtractWords {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
String input = console.nextLine();
String pattern = "([a-zA-Z])+";
Pattern patt = Pattern.compile(pattern);
Matcher match = patt.matcher(input);
while (match.find()) {
System.out.print(match.group() + " ");
}
}
}
| true |
5dbcde0075041eb7c90d5095f6346b7ed2a630df | Java | parcka/csv-process | /src/main/java/com/parcka/csvprocess/core/CSVReader.java | UTF-8 | 3,530 | 2.671875 | 3 | [] | no_license | package com.parcka.csvprocess.core;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.stream.Stream;
@Slf4j
@Component
public class CSVReader {
private static final String COMMA_DELIMITER = ",";
public void processFile() throws FileNotFoundException {
log.info("Reading file....");
//Data que se va a buscar
String dataToFind = "data/data-to-find.txt";
Path pathDataToFind = Paths.get(getFileUriFromResources(dataToFind));
//Data donde buscar
String dataWhereFind = "data/copy-import.csv";
Path pathDataWhereFind = Paths.get(getFileUriFromResources(dataWhereFind));
//Archivo resultado
String result = "data/result.csv";
Path pathResult = Paths.get(getFileUriFromResources(result));
try (Stream<String> stream = Files.lines(pathDataWhereFind)) {
stream.forEach(
(element) -> {
HashMap<String, String> newMap = new HashMap<>();
String id = element.split(COMMA_DELIMITER)[0];
newMap.put(id, element);
try (Stream<String> innerStream = Files.lines(pathDataToFind)) {
innerStream.forEach(
(line) -> {
String newLine = "";
String[] lineElement = element.split(COMMA_DELIMITER);
if (lineElement[0].equals(line)) {
log.info("ES IGUAL {} == {}", lineElement[0], element.split(COMMA_DELIMITER)[0]);
newLine = element + "x";
newMap.put(line, newLine);
}
}
);
} catch (Exception e) {
log.error("Error {}", e);
}
newMap.put(id,
newMap.get(id)
+ "\n");
try {
Files.write(pathResult, newMap.get(id).getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
log.error("Error {}", e);
}
log.info(newMap.toString());
});
} catch (IOException e) {
log.error("ERROR {}", e);
}
}
private URI getFileUriFromResources(String relativeResourcesPath) {
URI uri = null;
URL url = null;
url = getClass().getClassLoader().getResource(relativeResourcesPath);
try {
uri = url.toURI().normalize();
} catch (Exception e) {
log.error("ERROR {}", e);
}
return uri;
}
private void createIfnoExist(String relativeResourcesPath) {
try {
Files.createFile(Paths.get(relativeResourcesPath));
} catch (IOException e) {
log.error("ERROR {}", e);
}
}
}
| true |
641ed63a86f70876cf2a15ba1a43d01889ad2cd6 | Java | kulwantsharma/learning-project | /src/main/java/string/WordExistsInMatrix.java | UTF-8 | 1,511 | 3.4375 | 3 | [] | no_license | package string;
public class WordExistsInMatrix {
public static void main(String[] args) {
char[][] mat = {
{'o', 'f', 'a', 's'},
{'l', 'l', 'q', 'w'},
{'z', 'o', 'w', 'k'}
};
String word = "follow";
System.out.println(doesWordExists(mat, word));
}
private static boolean doesWordExists(char[][] mat, String word) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
if (doesWordExistsUtil(mat, i, j, new boolean[mat.length][mat[0].length], word, 0)) {
return true;
}
}
}
return false;
}
private static boolean doesWordExistsUtil(char[][] mat, int i, int j, boolean[][] visited, String word, int k) {
if (i < 0 || j < 0 || i == mat.length || j == mat[0].length) {
return false;
}
if (visited[i][j]) {
return false;
}
if (mat[i][j] != word.charAt(k)) {
return false;
}
visited[i][j] = true;
if (k == word.length() - 1 && mat[i][j] == word.charAt(k)) return true;
return doesWordExistsUtil(mat, i - 1, j, visited, word, k + 1)
|| doesWordExistsUtil(mat, i + 1, j, visited, word, k + 1)
|| doesWordExistsUtil(mat, i, j - 1, visited, word, k + 1)
|| doesWordExistsUtil(mat, i, j + 1, visited, word, k + 1);
}
}
| true |
04ae941d3ecb80c56cef98e3e117d1a3b941d50e | Java | ViktoriaTeliuk/voting | /src/main/java/restaurant/voting/model/Menu.java | UTF-8 | 1,819 | 2.4375 | 2 | [] | no_license | package restaurant.voting.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.validator.constraints.Range;
import javax.persistence.*;
import java.math.BigInteger;
import java.util.List;
@Entity
@Table(name = "menu")
public class Menu extends AbstractNamedEntity {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "restaurant_id")
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
private Restaurant restaurant;
@Column(name = "price", nullable = false)
@Range(min = 1)
private BigInteger price;
@Column(name = "enabled", columnDefinition = "bool default true")
private Boolean enabled;
@OneToMany(mappedBy = "menu")
@JsonIgnore
private List<DayMenu> dayMenuList;
public Restaurant getRestaurant() {
return restaurant;
}
public void setRestaurant(Restaurant restaurant) {
this.restaurant = restaurant;
}
public BigInteger getPrice() {
return price;
}
public void setPrice(BigInteger mealPrice) {
this.price = mealPrice;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Menu() {
}
public Menu(Restaurant restaurant, Integer id, String name, BigInteger price, boolean enabled) {
this.restaurant = restaurant;
this.id = id;
this.name = name;
this.price = price;
this.enabled = enabled;
}
public Menu(Menu menu) {
this.id = menu.id;
this.enabled = menu.enabled;
this.price = menu.price;
this.name = menu.name;
this.restaurant = menu.restaurant;
}
}
| true |
7ae957500e3f2fdbaadb72401827ce645697684c | Java | mortonliao/admin | /src/main/java/com/longhum/admin/controller/ResourceController.java | UTF-8 | 4,282 | 2.03125 | 2 | [] | no_license | package com.longhum.admin.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.longhum.admin.entity.ResultSimpleDate;
import com.longhum.admin.entity.TreeResource;
import com.longhum.admin.model.SysResource;
import com.longhum.admin.service.SysService;
/**
* @author liaoxiaohu
* @date 2017年5月14日
* @info
*/
@Controller
@RequestMapping("/resource")
public class ResourceController {
@Autowired
private SysService sysService;
@RequestMapping("/manager.do")
public String menuList(HttpServletRequest request,ModelMap map){
return "/system/resource";
}
@RequestMapping("/allResource.do")
@ResponseBody
public List<SysResource> allResource(HttpServletRequest request){
List<SysResource> list = sysService.findAllMenu();
sysService.initResourceList(list,request.getContextPath());
return list;
}
@RequestMapping("/allResource2.do")
@ResponseBody
public List<TreeResource> allresource2(HttpServletRequest request){
List<SysResource> list = sysService.findAllMenu();
List<SysResource> list2 = sysService.findByUserNameOrParentIdOrPreateIdsOrType(null,null,(String)SecurityUtils.getSubject().getPrincipal(), null);
sysService.initResourceList(list,request.getContextPath());
List<TreeResource> result = new ArrayList<TreeResource>();
for (SysResource sysResource : list) {
TreeResource r = new TreeResource();
BeanUtils.copyProperties(sysResource, r);
if(list2.contains(sysResource)){
r.setChecked(true);
}
result.add(r);
}
return result;
}
@RequestMapping("/allResource3.do")
@ResponseBody
public List<TreeResource> allresource3(HttpServletRequest request,Long roleId){
List<SysResource> list = sysService.findAllMenu();
List<SysResource> list2 = sysService.findByRoleId(roleId);
sysService.initResourceList(list,request.getContextPath());
List<TreeResource> result = new ArrayList<TreeResource>();
for (SysResource sysResource : list) {
TreeResource r = new TreeResource();
BeanUtils.copyProperties(sysResource, r);
if(list2.contains(sysResource)){
r.setChecked(true);
}
result.add(r);
}
return result;
}
@RequestMapping("/save.do")
@ResponseBody
/**
*
*
* @author liaoxiaohu
* @date 2017年5月28日
* @param request
* @param resource
* @return@RequestParam(name="file",required=true) MultipartFile file
* ,@RequestParam(value="iconFile",required=false) MultipartFile iconFile
*/
public ResultSimpleDate save(HttpServletRequest request,SysResource resource,@RequestParam(value="iconFile",required=false) MultipartFile iconFile){
//int x = 1/0;
//MultipartFile file = resource.getFile();
if(iconFile != null){
String[] type = iconFile.getContentType().split("/");
if(type[0].equals("image")){
try {
String fileName = "/img/icon/reousrce_"+System.currentTimeMillis()+"."+type[1];
resource.setIcon(fileName);
iconFile.transferTo(new File("/usr/local/var/www"+fileName));
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}else{
return ResultSimpleDate.error("不是有效文件");
}
}
sysService.saveResource(resource);
return ResultSimpleDate.ok("操作成功", resource);
}
@RequestMapping("/saveIcon.do")
@ResponseBody
/**
*
*
* @author liaoxiaohu
* @date 2017年5月28日
* @param request
* @param resource
* @return@RequestParam(name="file",required=true) MultipartFile file
*/
public ResultSimpleDate saveIcon(HttpServletRequest request){
return ResultSimpleDate.ok("操作成功");
}
}
| true |
51c68ccd395c2c237af80738d9abf354d1a6c841 | Java | MohammedZ666/prescription2 | /app/src/main/java/android/ztech/com/prescription/TrialExpiredLockerDialog.java | UTF-8 | 4,473 | 2.140625 | 2 | [] | no_license | package android.ztech.com.prescription;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Zishan on 23/Nov/2016.
*/
public class TrialExpiredLockerDialog extends DialogFragment {
TrialExpiredLockerDialog.OnPositiveClickListener mCallback;
BroadcastReceiver smsKeyReciever;
AlertDialog alertDialog;
EditText mEditText;
View view;
public interface OnPositiveClickListener {
void entryCheckTrial();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (TrialExpiredLockerDialog.OnPositiveClickListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
LayoutInflater inflater = getActivity().getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
view =inflater.inflate(R.layout.dialog_signin,null);
mEditText=(EditText)view.findViewById(R.id.password);
builder.setMessage("Your app is deactivated. Please contact your developer")
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey (DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP && !event.isCanceled()) {
Activity openingAct= getActivity();
openingAct.finish();
}
return false;
}
});
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
smsKeyReciever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get the data (SMS data) bound to intent
SmsMessage[] msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent);
SmsMessage sms = msgs[0];
byte[]data= sms.getUserData();
String message="";
for (int index=0; index < data.length; index++) {
message += Character.toString((char) data[index]);
}
if(message.equals(".obaida.zisan.19678.%.1_*.*##")) {
Toast.makeText(getActivity(), "Congrats! You just bought the premium version. Enjoy....", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
mCallback.entryCheckTrial();
}
// for(int i=0;i<msgs.length;i++){
//
// if(msgs[i]!=null){
//
//
//
//
// }
// }
}
};
// Create the AlertDialog object and return it
return alertDialog;
}
@Override
public void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("android.intent.action.DATA_SMS_RECEIVED");
intentFilter.setPriority(9999);
intentFilter.addDataScheme("sms");
intentFilter.addDataAuthority("*", "8126");
Log.e("registerd reciever","smskeyreceiver");
getActivity().registerReceiver(smsKeyReciever, intentFilter);
}
@Override
public void onStop() {
super.onStop();
Log.e("unregisterd reciever","smskeyreceiver");
getActivity().unregisterReceiver(smsKeyReciever);
}
}
| true |
7379e0c2adbd6faf6ec39d88b55714761a3ce215 | Java | Jpolloj/functionalProgramming | /src/main/java/com/programacionFuncional/dummy/funciones/interfazBiFunction/ejercicio/Tienda.java | UTF-8 | 698 | 3.0625 | 3 | [] | no_license | package com.programacionFuncional.dummy.funciones.interfazBiFunction.ejercicio;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
public interface Tienda {
static String venta(Productos productos, Double pago, BiFunction<Double, Double, String> biFunction){
return biFunction.apply(pago, productos.getPrecio());
}
static List<Productos> descuentoCarrito(List<Productos> productos, Double descuento, BiFunction<Productos, Double, Productos> biFunction ){
List<Productos> descuentos = new ArrayList<>();
productos.forEach( (item) -> descuentos.add( biFunction.apply(item, descuento)));
return descuentos;
}
}
| true |
9c9c5089f2ae4fca4d1363c20e197943fa371b9a | Java | siyingpoof/Orbital | /app/src/main/java/com/example/alvinaong/alive/Log_Vol.java | UTF-8 | 6,960 | 1.984375 | 2 | [] | no_license | package com.example.alvinaong.alive;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.bumptech.glide.load.resource.bitmap.RecyclableBufferedInputStream;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.bumptech.glide.Glide;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class Log_Vol extends AppCompatActivity {
private TextView tvName, tvGender, tvSchool, tvContact, tvEmail, tvAccHours;
private ImageView ivImage;
private ProgressBar progressBar;
private String Uid;
private Volunteer currUser;
private int accHours;
private RecyclerView myRV;
private EventAdapterVolLog myAdapter;
private List<Event> eventList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_vol);
tvName = findViewById(R.id.tvName);
tvGender = findViewById(R.id.tvGender);
tvSchool = findViewById(R.id.tvSchool);
tvContact = findViewById(R.id.tvContact);
tvEmail = findViewById(R.id.tvEmail);
tvAccHours = findViewById(R.id.tvAccHours);
ivImage = findViewById(R.id.ivVolImage);
progressBar = findViewById(R.id.progressBar);
tvAccHours = findViewById(R.id.tvAccHours);
Uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("volunteers").child(Uid);
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
currUser = dataSnapshot.getValue(Volunteer.class);
tvName.setText(currUser.getName());
tvGender.setText(currUser.getGender());
tvSchool.setText(currUser.getSchool());
tvEmail.setText(currUser.getEmail());
tvContact.setText(currUser.getContactNumber());
// Progress bar
accHours = currUser.getHours();
tvAccHours.setText(accHours + " hours");
progressBar.setMax(100);
// progressBar.setIndeterminate(false);
progressBar.setProgress(accHours);
StorageReference storageReference = FirebaseStorage.getInstance().getReference("volunteers").child(Uid+".jpg");
Glide.with(Log_Vol.this).load(storageReference).into(ivImage);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
eventList = new ArrayList<>();
// Recycler view
myRV = (RecyclerView) findViewById(R.id.recyclerview_id_vollog);
myRV.setHasFixedSize(true);
myRV.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new EventAdapterVolLog(eventList);
myRV.setAdapter(myAdapter);
// read in data from firebase
readFirebase();
}
private void readFirebase() {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("volunteers").child(Uid).child("events");
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
final String currEventID = dataSnapshot.getValue().toString();
DatabaseReference myEventRef = FirebaseDatabase.getInstance().getReference("events");
myEventRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
Event eventToCheck = dataSnapshot.getValue(Event.class);
String checkID = eventToCheck.getEventID();
if (checkID.equals(currEventID)) {
eventList.add(eventToCheck);
myAdapter.notifyItemInserted(eventList.size() - 1);
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar_vol_log, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.volGuide:
startActivity(new Intent(Log_Vol.this, Help_Vol.class));
return true;
case R.id.itemHome:
startActivity(new Intent(Log_Vol.this, Home_Vol.class));
return true;
case R.id.itemLogout:
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(Log_Vol.this, Login.class));
finish();
return true;
}
return true;
}
}
| true |
27bcfd1cc65f9b53738a30ca51e79ca47626a974 | Java | JuanManuel98/Proyectos | /Compilador/src/gramatica/Regla.java | UTF-8 | 2,662 | 3.203125 | 3 | [] | no_license | package gramatica;
import java.util.ArrayList;
import java.util.List;
public class Regla {
private String noTerminal;
private List<String> terminales;
private List<Atributo> atributos;
public Regla(String noTerminal) {
this.noTerminal = noTerminal;
this.terminales = new ArrayList<String>();
this.atributos = new ArrayList<Atributo>();
}
public void asignarTerminales(List<String> terminales) {
this.terminales = new ArrayList<String>();
this.terminales.addAll(terminales);
}
public void agregarAtributos(List<String> atributos) {
for(String stringAtributo : atributos) {
String partir[] = stringAtributo.split("=");
String nombreAtributo = partir[0].substring(1);
String stringConstruccion = partir[1];
for(Integer k = 2; k < partir.length; k++) { stringConstruccion += "=" + partir[k]; }
List<String> construccion = new ArrayList<String>();
if(stringConstruccion.contains("?") == true) {
stringConstruccion = stringConstruccion.replace("?", "#");
String separar[] = stringConstruccion.split("#");
String condicion = separar[0];
String signoComparacion = null;
if(condicion.contains("!=") == true) { signoComparacion = "!="; }
if(condicion.contains("==") == true) { signoComparacion = "=="; }
partir = condicion.split(signoComparacion);
construccion.add(partir[0]);
construccion.add(signoComparacion);
construccion.add(partir[1]);
construccion.add("?");
for(Integer w = 1; w < separar.length; w++) {
separar[w] = separar[w].replace("||", "#");
partir = separar[w].split("#");
for(Integer i = 0; i < partir.length; i++) {
construccion.add(partir[i]);
}
if(w == 1) { construccion.add("#"); }
}
}
else {
stringConstruccion = stringConstruccion.replace("||", "#");
partir = stringConstruccion.split("#");
for(Integer i = 0; i < partir.length; i++) {
construccion.add(partir[i]);
}
}
this.atributos.add(new Atributo(nombreAtributo, construccion));
}
}
public List<String> construccionAtributo(String nombreAtributo){
for(Atributo atributo : this.atributos) {
if(atributo.nombre().equals(nombreAtributo) == true) {
return atributo.construccion();
}
}
return null;
}
public List<Atributo> atributos(){
return this.atributos;
}
public String noTerminal() {
return this.noTerminal;
}
public List<String> terminales(){
return this.terminales;
}
public String toString() {
return this.noTerminal + " -> " + this.terminales;
}
public Regla clone() {
Regla copia = new Regla(this.noTerminal);
copia.terminales.addAll(this.terminales);
return copia;
}
} | true |
22b189f9833528548df46f6666dda9c881ffe064 | Java | pflanzenmoerder/coffeekitty | /coffeekitty-web/src/main/java/de/caffeine/kitty/web/page/UserWithoutDefaultKittyPage.java | UTF-8 | 1,920 | 1.914063 | 2 | [] | no_license | package de.caffeine.kitty.web.page;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.event.IEvent;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import de.caffeine.kitty.entities.User;
import de.caffeine.kitty.service.repository.kitty.KittySearchResult;
import de.caffeine.kitty.web.UserAuthenticatedWebSession;
import de.caffeine.kitty.web.header.HeaderPanel;
import de.caffeine.kitty.web.kitty.KittySearchResultPanel;
import de.caffeine.kitty.web.kitty.SearchKittyFormPanel;
import de.caffeine.kitty.web.kitty.create.CreateKittyPanel;
@SuppressWarnings("serial")
@AuthorizeInstantiation(Roles.USER)
public class UserWithoutDefaultKittyPage extends BaseCafManPage {
private static final String SEARCH_RESULT = "searchResult";
private static final String SEARCH_KITTY = "searchKitty";
private static final String CREATE_KITTY = "createKitty";
public UserWithoutDefaultKittyPage() {
IModel<User> userModel = UserAuthenticatedWebSession.get().getUserModel();
IModel<KittySearchResult> kittySearchResultModel = new Model<KittySearchResult>();
add(new HeaderPanel("header"));
add(new CreateKittyPanel(CREATE_KITTY, userModel).setOutputMarkupId(true));
add(new SearchKittyFormPanel(SEARCH_KITTY, kittySearchResultModel).setOutputMarkupId(true));
add(new KittySearchResultPanel(SEARCH_RESULT, userModel, kittySearchResultModel).setOutputMarkupId(true));
}
@Override
public void onEvent(IEvent<?> event) {
super.onEvent(event);
if (event.getPayload() instanceof AjaxRequestTarget) {
AjaxRequestTarget target = ((AjaxRequestTarget)event.getPayload());
target.add(get(SEARCH_KITTY));
target.add(get(SEARCH_RESULT));
target.add(get(CREATE_KITTY));
}
}
}
| true |
7da149bf43775039ffe06809e411ef7d0b4210e1 | Java | AliGolgol/trading-price | /src/main/java/com/solactive/codechallenge/tradingprice/model/Statistics.java | UTF-8 | 347 | 1.78125 | 2 | [] | no_license | package com.solactive.codechallenge.tradingprice.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Statistics {
private double avg;
private double max;
private double min;
private long count;
}
| true |
4f9cdc3b0a4d8164d224af63261477e35c81fb15 | Java | Sivaranjini15/SeleniumJavaFramework | /AutomationFramework/src/test/java/testsample/tstsample.java | UTF-8 | 1,032 | 2.25 | 2 | [] | no_license | package testsample;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class tstsample {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user\\eclipse-workspace\\AutomationFramework\\drivers\\chrome driver\\chromedriver.exe");
WebDriver dr = new ChromeDriver();
dr.get("http://www.google.com");
dr.manage().window().maximize();
dr.findElement(By.xpath("//*[@id=\"tsf\"]/div[2]/div/div[1]/div/div[1]/input")).sendKeys("Testing");
List<WebElement> links = dr.findElements(By.tagName("a"));
//for each statement
for (WebElement currlinks : links) {
String strlinks = currlinks.getText();
System.out.println(strlinks);
}
dr.findElement(By.name("btnK")).sendKeys(Keys.ENTER);
dr.close();
}
}
| true |
696020d99ca2698e62bf2e4c3f0af36402af3313 | Java | julioheredia/gerenciaHospitalar | /src/java/entidade/ProfissionalEntidade.java | UTF-8 | 6,780 | 2.0625 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package entidade;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author julio
*/
@Entity
@Table(name = "profissional_i")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
name = "discriminator",
discriminatorType = DiscriminatorType.STRING)
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "ProfissionalEntidade.findAll", query = "SELECT p FROM ProfissionalEntidade p"),
@NamedQuery(name = "ProfissionalEntidade.findById", query = "SELECT p FROM ProfissionalEntidade p WHERE p.id = :id"),
//@NamedQuery(name = "ProfissionalEntidade.findByIdEquipe", query = "SELECT p FROM ProfissionalEntidade p WHERE p.idEquipe = :idEquipe"),
@NamedQuery(name = "ProfissionalEntidade.findByNome", query = "SELECT p FROM ProfissionalEntidade p WHERE p.nome = :nome"),
@NamedQuery(name = "ProfissionalEntidade.findByExperiencia", query = "SELECT p FROM ProfissionalEntidade p WHERE p.experiencia = :experiencia"),
@NamedQuery(name = "ProfissionalEntidade.findByEndereco", query = "SELECT p FROM ProfissionalEntidade p WHERE p.endereco = :endereco"),
@NamedQuery(name = "ProfissionalEntidade.findByHonorario", query = "SELECT p FROM ProfissionalEntidade p WHERE p.honorario = :honorario"),
@NamedQuery(name = "ProfissionalEntidade.findByQualificacao", query = "SELECT p FROM ProfissionalEntidade p WHERE p.qualificacao = :qualificacao"),
@NamedQuery(name = "ProfissionalEntidade.findByDiscriminator", query = "SELECT p FROM ProfissionalEntidade p WHERE p.discriminator = :discriminator"),
@NamedQuery(name = "ProfissionalEntidade.findByDataEntradaEquipe", query = "SELECT p FROM ProfissionalEntidade p WHERE p.dataEntradaEquipe = :dataEntradaEquipe"),
@NamedQuery(name = "ProfissionalEntidade.findByDataSaidaEquipe", query = "SELECT p FROM ProfissionalEntidade p WHERE p.dataSaidaEquipe = :dataSaidaEquipe")})
public abstract class ProfissionalEntidade 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 = "id_equipe")
private int idEquipe;
*/
@Basic(optional = false)
@Column(name = "nome")
private String nome;
@Basic(optional = false)
@Column(name = "experiencia")
private String experiencia;
@Basic(optional = false)
@Column(name = "endereco")
private String endereco;
@Basic(optional = false)
@Column(name = "honorario")
private float honorario;
@Basic(optional = false)
@Column(name = "qualificacao")
private String qualificacao;
@Basic(optional = false)
@Column(name = "discriminator")
private String discriminator;
@Column(name = "data_entrada_equipe")
@Temporal(TemporalType.DATE)
private Date dataEntradaEquipe;
@Column(name = "data_saida_equipe")
@Temporal(TemporalType.DATE)
private Date dataSaidaEquipe;
@ManyToOne
@JoinColumn(name = "id_equipe", referencedColumnName = "id")
private EquipeEntidade equipe;
public ProfissionalEntidade() {
}
public ProfissionalEntidade(Integer id) {
this.id = id;
}
public ProfissionalEntidade(Integer id, String nome, String experiencia, String endereco, float honorario, String qualificacao) {
this.id = id;
this.nome = nome;
this.experiencia = experiencia;
this.endereco = endereco;
this.honorario = honorario;
this.qualificacao = qualificacao;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getExperiencia() {
return experiencia;
}
public void setExperiencia(String experiencia) {
this.experiencia = experiencia;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public float getHonorario() {
return honorario;
}
public void setHonorario(float honorario) {
this.honorario = honorario;
}
public String getQualificacao() {
return qualificacao;
}
public void setQualificacao(String qualificacao) {
this.qualificacao = qualificacao;
}
public String getDiscriminator() {
return discriminator;
}
public void setDiscriminator(String discriminator) {
this.discriminator = discriminator;
}
public EquipeEntidade getEquipe() {
return equipe;
}
public void setEquipe(EquipeEntidade equipe) {
this.equipe = equipe;
}
public Date getDataEntradaEquipe() {
return dataEntradaEquipe;
}
public void setDataEntradaEquipe(Date dataEntradaEquipe) {
this.dataEntradaEquipe = dataEntradaEquipe;
}
public Date getDataSaidaEquipe() {
return dataSaidaEquipe;
}
public void setDataSaidaEquipe(Date dataSaidaEquipe) {
this.dataSaidaEquipe = dataSaidaEquipe;
}
@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 ProfissionalEntidade)) {
return false;
}
ProfissionalEntidade other = (ProfissionalEntidade) 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 "entidade.ProfissionalEntidade[ id=" + id + " ]";
}
}
| true |
6255a9b6fa13166a0df4f91c8554bd18d7c7abce | Java | OSGP/open-smart-grid-platform | /osgp/platform/osgp-throttling-service/src/main/java/org/opensmartgridplatform/throttling/entities/Permit.java | UTF-8 | 3,185 | 2.15625 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // SPDX-FileCopyrightText: Copyright Contributors to the GXF project
//
// SPDX-License-Identifier: Apache-2.0
package org.opensmartgridplatform.throttling.entities;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PrePersist;
@Entity
public class Permit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, updatable = false)
private short throttlingConfigId;
@Column(nullable = false, updatable = false)
private int clientId;
@Column(name = "bts_id", nullable = false, updatable = false)
private int baseTransceiverStationId;
@Column(name = "cell_id", nullable = false, updatable = false)
private int cellId;
@Column(name = "request_id", nullable = false, updatable = false)
private int requestId;
@Column(nullable = false, updatable = false)
private Instant createdAt;
protected Permit() {
// no-arg constructor required by JPA specification
}
public Permit(
final short throttlingConfigId,
final int clientId,
final int baseTransceiverStationId,
final int cellId,
final int requestId) {
this(null, null, throttlingConfigId, clientId, baseTransceiverStationId, cellId, requestId);
}
public Permit(
final Long id,
final Instant createdAt,
final short throttlingConfigId,
final int clientId,
final int baseTransceiverStationId,
final int cellId,
final int requestId) {
this.id = id;
this.createdAt = createdAt;
this.throttlingConfigId = throttlingConfigId;
this.clientId = clientId;
this.baseTransceiverStationId = baseTransceiverStationId;
this.cellId = cellId;
this.requestId = requestId;
}
public Long getId() {
return this.id;
}
public short getThrottlingConfigId() {
return this.throttlingConfigId;
}
public int getClientId() {
return this.clientId;
}
public int getBaseTransceiverStationId() {
return this.baseTransceiverStationId;
}
public int getCellId() {
return this.cellId;
}
public int getRequestId() {
return this.requestId;
}
public Instant getCreatedAt() {
return this.createdAt;
}
@PrePersist
public void prePersist() {
this.createdAt = Instant.now();
}
@Override
public String toString() {
return String.format(
"%s[id=%s, throttlingConfigId=%d, clientId=%d, btsId=%d, cellId=%d, requestId=%s, created=%s]",
Permit.class.getSimpleName(),
this.id,
this.throttlingConfigId,
this.clientId,
this.baseTransceiverStationId,
this.cellId,
this.requestId,
this.createdAt);
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Permit)) {
return false;
}
final Permit other = (Permit) obj;
return this.id != null && this.id.equals(other.getId());
}
@Override
public int hashCode() {
return Permit.class.hashCode();
}
}
| true |
b619d6e875622515d522141f0066f80716ca51ee | Java | dadan-hidyt/fla-design-patterns | /src/ohmypatt/patt/behavioral/chains/apitrack/main/Main.java | UTF-8 | 1,321 | 2.40625 | 2 | [
"MIT"
] | permissive | package ohmypatt.patt.behavioral.chains.apitrack.main;
import ohmypatt.patt.behavioral.chains.apitrack.handler.Handler;
import ohmypatt.patt.behavioral.chains.apitrack.handler.HelloMessage;
import ohmypatt.patt.behavioral.chains.apitrack.handler.VerifyApiKeyHandler;
import ohmypatt.patt.behavioral.chains.apitrack.handler.VerifySessionHandler;
import ohmypatt.patt.behavioral.chains.apitrack.handler.VerifyUserHandler;
import ohmypatt.patt.behavioral.chains.apitrack.model.APIKey;
import ohmypatt.patt.behavioral.chains.apitrack.model.BasicAPIKey;
import ohmypatt.patt.behavioral.chains.apitrack.model.Session;
import ohmypatt.patt.behavioral.chains.apitrack.model.User;
public class Main {
public Main() {
APIKey key = new BasicAPIKey("asademar1a");
User user = new User("Budi Setiawan", "budisetia01_", key);
Session s = new Session(user);
Handler hello = new HelloMessage(s);
Handler middleware = getMiddlewareChains(s, hello);
middleware.handle();
}
private Handler getMiddlewareChains(Session s, Handler targetHandler) {
Handler apiKeyHandler = new VerifyApiKeyHandler(s.getUser().getApiKey(), targetHandler);
Handler userHandler = new VerifyUserHandler(s.getUser(), apiKeyHandler);
return new VerifySessionHandler(s, userHandler);
}
public static void main(String[] args) {
new Main();
}
}
| true |
3d3c7fa7de99b61d7cf1683ef25add195f0a961e | Java | howdie/robert | /app/src/main/java/com/example/haowei/twitter/DetialActivity.java | UTF-8 | 1,565 | 2.15625 | 2 | [] | no_license | package com.example.haowei.twitter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.haowei.twitter.model.Tweet;
import com.example.haowei.twitter.model.User;
import com.squareup.picasso.Picasso;
import java.util.List;
public class DetialActivity extends AppCompatActivity {
private List<Tweet> tweets = MainActivity.tweetList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_main);
Intent launch = getIntent();
if(launch != null){
int position = launch.getIntExtra(MainActivity.TWEET,-1);
if(position >= 0 && position < tweets.size()) {
Tweet tweet = tweets.get(position);
ImageView profilepic = findViewById(R.id.profileImg);
String imageUri = "https://i.imgur.com/tGbaZCY.jpg";
Picasso.with(getBaseContext()).load(imageUri).into(profilepic);
TextView name = findViewById(R.id.name_d);
String full_name = tweet.getUser().getScreen_name() + " @" + tweet.getUser().getName();
name.setText(full_name);
TextView date = findViewById(R.id.date_d);
date.setText(tweet.getDate());
TextView text = findViewById(R.id.tweet_d);
text.setText(tweet.getTweet());
}
}
}
}
| true |
81ca89faed0fd7d4a10702f0999faeb2e5e5d08c | Java | liumingmusic/springboot-cloud-tutorial | /msa-weather-city-eureka/src/main/java/com/liumm/msa/weather/util/XmlBuilder.java | UTF-8 | 1,122 | 2.78125 | 3 | [] | no_license | /**
* @Title: XmlBuilder.java
* @Package com.liumm.micro.weather.util
* @Description: TODO(用一句话描述该文件做什么)
* @author liumm
* @date 2018年3月17日 下午10:45:07
* @version V1.0
*/
package com.liumm.msa.weather.util;
import java.io.Reader;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
/**
* @ClassName: XmlBuilder
* @Description: xml文件转实体类
* @author liumm
* @date 2018年3月17日 下午10:45:07
*
*/
public class XmlBuilder {
/**
*
* @Description: 将xml文件转换为pojo
* @param clazz
* @param strXml
* @return
* @throws Exception:
*/
public static Object xmlStrToObject(Class<?> clazz, String strXml) throws Exception {
Object xmlObject = null;
Reader reader = null;
JAXBContext context = JAXBContext.newInstance(clazz);
// 转换对象
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(strXml);
xmlObject = unmarshaller.unmarshal(reader);
// 关闭
if (null != reader) {
reader.close();
}
return xmlObject;
}
}
| true |
5811562d2df2157aa17b8dc4b96bdb4550f7aa88 | Java | jeaha1217/minorRevision | /summary/src/main/java/summary/java/cms/control/student/StudentDeleteController.java | UTF-8 | 834 | 2.515625 | 3 | [] | no_license | package summary.java.cms.control.student;
import java.util.Scanner;
import summary.java.cms.Dao.StudentDao;
import summary.java.cms.annotation.Autowired;
import summary.java.cms.annotation.Component;
import summary.java.cms.annotation.RequestMapping;
@Component
public class StudentDeleteController {
StudentDao studentDao;
@Autowired
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
@RequestMapping("student/delete")
public void delete(Scanner keyIn) {
System.out.print("email for delete : ");
String email = keyIn.nextLine();
if (studentDao.delete(email) > 0) {
System.out.println("Delete " + email + " is complete.");
} else {
System.out.println("Invalid Email.");
}
}
} | true |
18bbe106aa86ab961bd23831d4df7d1d89e9aea7 | Java | sparkaochong/java-basic | /src/main/java/com/ac/day20190209/Person1.java | UTF-8 | 963 | 3.21875 | 3 | [] | no_license | package com.ac.day20190209;
/**
* Created by Chong Ao on 2019/2/1.
*/
public class Person1 {
private String name;
private int age;
private static String country = "中华人民共和国";
public Person1(String name, int age) {
this.name = name;
this.age = age;
}
public static void setCountry(String c){
country = c;
}
public static String getCountry(){
// name = "张三";
// getInfo();
return country;
}
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 String getInfo(){
System.out.println(this.country);
System.out.println(this.getCountry());
return "姓名:" + this.name + " 年龄:" + this.age + " 国家:" + this.country;
}
}
| true |
7c8701cdef51ab7de07e5c6683d2aa9baadf94b9 | Java | PimB93/Server-en-Clients | /weact_db/src/main/java/model/Tag.java | UTF-8 | 998 | 3.34375 | 3 | [] | no_license | package model;
public class Tag {
private int tagID;
private String description;
private TagCategory category;
/**
* Alle mogelijke categorieen voor een tag, te weten:
* <ul><li>KNOWS: heeft kennis van</li>
* <li>WANTS_TO_LEARN: wil leren</li>
* <li>GROUP: groep</li>
* <li>OTHER: overig</li></ul>
* @author roysten
*
*/
public enum TagCategory{
KNOWS, WANTS_TO_LEARN, GROUP, OTHER;
}
/**
* Constructor voor een tag.
* @param tagID
* @param description de beschrijving van de tag
*/
public Tag(int tagID, String beschrijving, TagCategory category){
this.tagID = tagID;
this.description = beschrijving;
this.category = category;
}
public int getTagID() {
return tagID;
}
public void setTagID(int tagID) {
this.tagID = tagID;
}
public String getBeschrijving() {
return description;
}
public void setBeschrijving(String beschrijving) {
this.description = beschrijving;
}
public TagCategory getCategory(){
return category;
}
}
| true |
88f2fcd247f3772fcd461b6d3a06f0cbf2cf33cf | Java | martinschneider/bbstats | /bbstats-web/src/main/java/at/basketballsalzburg/bbstats/pages/Accounting.java | UTF-8 | 5,722 | 1.671875 | 2 | [] | no_license | package at.basketballsalzburg.bbstats.pages;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.Cached;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectComponent;
import org.apache.tapestry5.annotations.MixinClasses;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.corelib.components.Grid;
import org.apache.tapestry5.corelib.components.LinkSubmit;
import org.apache.tapestry5.corelib.components.TextField;
import org.apache.tapestry5.corelib.components.Zone;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;
import org.apache.tapestry5.services.SelectModelFactory;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.joda.time.DateTime;
import at.basketballsalzburg.bbstats.commons.CssConstants;
import at.basketballsalzburg.bbstats.components.Box;
import at.basketballsalzburg.bbstats.components.DateTimeField;
import at.basketballsalzburg.bbstats.components.PageLayout;
import at.basketballsalzburg.bbstats.components.Select2;
import at.basketballsalzburg.bbstats.dto.AgeGroupDTO;
import at.basketballsalzburg.bbstats.dto.CoachDTO;
import at.basketballsalzburg.bbstats.dto.PlayerDTO;
import at.basketballsalzburg.bbstats.dto.PracticeDTO;
import at.basketballsalzburg.bbstats.mixins.GridColumnDecorator;
import at.basketballsalzburg.bbstats.security.Permissions;
import at.basketballsalzburg.bbstats.select2.ChoiceProvider;
import at.basketballsalzburg.bbstats.select2.Settings;
import at.basketballsalzburg.bbstats.select2.provider.CoachProvider;
import at.basketballsalzburg.bbstats.services.CoachService;
import at.basketballsalzburg.bbstats.services.PracticeService;
@RequiresPermissions(Permissions.accountingPage)
public class Accounting {
@Component
private PageLayout pageLayout;
@Component(parameters = { "title=prop:resultsBoxTitle", "type=tablebox" })
private Box resultsBox;
@Component(parameters = { "title=message:selectBoxTitle" })
private Box selectBox;
@Component(parameters = { "value=dateFrom", "datePattern=dd.MM.yyyy" })
private DateTimeField dateFromField;
@Component(parameters = { "value=dateTo", "datePattern=dd.MM.yyyy" })
private DateTimeField dateToField;
@Component(parameters = { "value=salaryPerPractice" })
private TextField salaryPerPracticeField;
@Component
private LinkSubmit submit;
@Component
private Zone resultsZone;
@MixinClasses(GridColumnDecorator.class)
@Component(parameters = { "source=practices",
"empty=message:noPracticeData", "row=practice",
"model=practiceModel", "rowsPerPage=30",
"include=dateTime,duration,gym", "inplace=true", "add=ageGroups",
"reorder=dateTime,gym,duration,ageGroups",
"class=table table-striped table-condensed",
"gridColumnDecorator.cssClassMap=cssClassMap" })
private Grid practiceGrid;
@Component(parameters = { "settings=settings", "type=literal:hidden",
"provider=coachProvider", "singleValue=coach" })
private Select2 coachSelect;
@Property
private Settings settings;
@InjectComponent
private Form form;
@Inject
private CoachService coachService;
@Inject
private PracticeService practiceService;
@Inject
private SelectModelFactory selectModelFactory;
@Inject
private BeanModelSource beanModelSource;
@Inject
private ComponentResources componentResources;
@Inject
private Messages messages;
@Inject
private JavaScriptSupport javaScriptSupport;
@Property
@Persist
private DateTime dateFrom;
@Property
@Persist
private DateTime dateTo;
@Property
@Persist
private CoachDTO coach;
@Property
@Persist
private int numberOfPractices;
@Property
@Persist
private BigDecimal salary;
@Property
@Persist
private BigDecimal salaryPerPractice;
@Property
@Persist
private List<PracticeDTO> practices;
@Property
private PracticeDTO practice;
@Property
private PlayerDTO player;
@Property
private AgeGroupDTO ageGroup;
@SetupRender
void onSetup() {
if (dateTo == null) {
dateTo = new DateTime();
}
if (dateFrom == null) {
dateFrom = dateTo.minusMonths(1);
}
if (salaryPerPractice == null) {
salaryPerPractice = BigDecimal.ZERO;
}
if (coach != null) {
practices = practiceService.findPracticesForCoachBetweenDates(
coach.getId(), dateFrom.toDate(), dateTo.toDate());
numberOfPractices = practices.size();
salary = new BigDecimal(numberOfPractices)
.multiply(salaryPerPractice);
}
settings = new Settings();
settings.setWidth("100%");
}
@Cached
public ChoiceProvider<CoachDTO> getCoachProvider() {
return new CoachProvider(coachService);
}
public BeanModel<PracticeDTO> getPracticeModel() {
BeanModel<PracticeDTO> beanModel = beanModelSource.createDisplayModel(
PracticeDTO.class, componentResources.getMessages());
beanModel.add("gym", null).sortable(true);
return beanModel;
}
public String getResultsBoxTitle() {
return messages.get("sum") + ": " + numberOfPractices + ", "
+ messages.get("salary") + ": " + salary;
}
public Map<String, String> getCssClassMap() {
Map<String, String> values = new HashMap<String, String>();
values.put("gym", CssConstants.HIDDEN_XS);
return values;
}
Object onSuccessFromForm() {
return resultsZone;
}
}
| true |
35b34773b3ec3491e5ee4ee8e084cd5c1bcfceb8 | Java | zalramli/scc | /ANDROID/SCC/app/src/main/java/com/its/scc/Activities/Eksternal/ListProve/EksternalListProveActivity.java | UTF-8 | 5,641 | 1.90625 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.its.scc.Activities.Eksternal.ListProve;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.its.scc.Activities.Eksternal.DetailProve.EksternalDetailProveActivity;
import com.its.scc.Activities.Eksternal.ListProve.presenter.EksternalListProvePresenter;
import com.its.scc.Activities.Eksternal.ListProve.presenter.IEksternalListProvePresenter;
import com.its.scc.Activities.Eksternal.ListProve.view.IEksternalListProveView;
import com.its.scc.Adapters.AdapterListProve;
import com.its.scc.Controllers.SessionManager;
import com.its.scc.Models.Prove;
import com.its.scc.R;
import java.util.ArrayList;
import java.util.HashMap;
import es.dmoral.toasty.Toasty;
public class EksternalListProveActivity extends AppCompatActivity implements View.OnClickListener, IEksternalListProveView {
public static final String EXTRA_TUJUAN = "EXTRA_TUJUAN";
String tujuan = "";
IEksternalListProvePresenter eksternalListProvePresenter;
private AdapterListProve adapterListProve;
private RecyclerView recyclerView;
Toolbar toolbar;
private SwipeRefreshLayout swipeRefreshLayout;
SessionManager sessionManager;
String id = "";
String hakAkses = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eksternal_list_prove);
tujuan = getIntent().getStringExtra(EXTRA_TUJUAN);
sessionManager = new SessionManager(this);
HashMap<String, String> user = sessionManager.getDataUser();
id = user.get(sessionManager.ID_USER);
hakAkses = user.get(sessionManager.HAK_AKSES);
eksternalListProvePresenter = new EksternalListProvePresenter(this, this);
eksternalListProvePresenter.inisiasiAwal(id, hakAkses, tujuan);
recyclerView = findViewById(R.id.recycle_view);
toolbar = findViewById(R.id.toolbar);
initActionBar();
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Your code to make your refresh action
eksternalListProvePresenter.inisiasiAwal(id, hakAkses, tujuan);
// CallYourRefreshingMethod();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (swipeRefreshLayout.isRefreshing()) {
swipeRefreshLayout.setRefreshing(false);
}
}
}, 1000);
}
});
}
@Override
public void onClick(View v) {
}
@Override
public void initActionBar() {
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public void onSetupListView(ArrayList<Prove> dataModelArrayList) {
adapterListProve = new AdapterListProve(this, dataModelArrayList);
GridLayoutManager layoutManager = new GridLayoutManager(this, 1, GridLayoutManager.VERTICAL, false);
recyclerView.setAdapter(adapterListProve);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setNestedScrollingEnabled(true);
adapterListProve.notifyDataSetChanged();
adapterListProve.setOnItemClickListener(new AdapterListProve.ClickListener() {
@Override
public void onClick(View view, int position) {
Intent intent = new Intent(getApplicationContext(), EksternalDetailProveActivity.class);
intent.putExtra(EksternalDetailProveActivity.EXTRA_ID_PROVE, dataModelArrayList.get(position).getId_prove());
intent.putExtra(EksternalDetailProveActivity.EXTRA_ID_JADWAL_PROVE, dataModelArrayList.get(position).getId_jadwal_prove());
intent.putExtra(EksternalDetailProveActivity.EXTRA_NAMA_MATERI_PROVE, dataModelArrayList.get(position).getNama_materi_prove());
intent.putExtra(EksternalDetailProveActivity.EXTRA_HARI, dataModelArrayList.get(position).getHari());
intent.putExtra(EksternalDetailProveActivity.EXTRA_JAM_MULAI, dataModelArrayList.get(position).getJam_mulai());
intent.putExtra(EksternalDetailProveActivity.EXTRA_JAM_SELESAI, dataModelArrayList.get(position).getJam_selesai());
intent.putExtra(EksternalDetailProveActivity.EXTRA_TANGGAL_PROVE, dataModelArrayList.get(position).getTanggal_prove());
intent.putExtra(EksternalDetailProveActivity.EXTRA_KODE_PROVE, dataModelArrayList.get(position).getKode_prove());
intent.putExtra(EksternalDetailProveActivity.EXTRA_KATA_SANDI, dataModelArrayList.get(position).getKata_sandi());
intent.putExtra(EksternalDetailProveActivity.EXTRA_NAMA_INTERNAL, dataModelArrayList.get(position).getNama_internal());
intent.putExtra(EksternalDetailProveActivity.EXTRA_STATUS_PROVE, dataModelArrayList.get(position).getStatus_prove());
startActivity(intent);
}
});
}
@Override
public void onSuccessMessage(String message) {
Toasty.success(this, message, Toast.LENGTH_SHORT).show();
}
@Override
public void onErrorMessage(String message) {
Toasty.error(this, message, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
@Override
protected void onResume() {
super.onResume();
eksternalListProvePresenter.inisiasiAwal(id, hakAkses, tujuan);
}
}
| true |
be4dc7f242ca662c5e66c2026191cf2611f88790 | Java | lazyparty/helloworld | /src/main/java/cn/daryu/shop/entity/Navigation.java | UTF-8 | 1,142 | 1.65625 | 2 | [] | no_license | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package net.shopxx.entity;
// Referenced classes of package net.shopxx.entity:
// OrderEntity
public class Navigation extends OrderEntity
{
public Navigation()
{
}
public String getName()
{
return IIIllIlI;
}
public void setName(String name)
{
IIIllIlI = name;
}
public Position getPosition()
{
return IIIllIll;
}
public void setPosition(Position position)
{
IIIllIll = position;
}
public String getUrl()
{
return IIIlllII;
}
public void setUrl(String url)
{
IIIlllII = url;
}
public Boolean getIsBlankTarget()
{
return IIIlllIl;
}
public void setIsBlankTarget(Boolean isBlankTarget)
{
IIIlllIl = isBlankTarget;
}
private static final long serialVersionUID = 0x960856e00eaf3fb5L;
private String IIIllIlI;
private Position IIIllIll;
private String IIIlllII;
private Boolean IIIlllIl;
}
| true |
31be7487d3183b601dbf4766101f958cce419c77 | Java | RyanTech/yoyou | /src/com/kuaiyou/yoyou/bean/DayList.java | UTF-8 | 533 | 2.0625 | 2 | [] | no_license | package com.kuaiyou.yoyou.bean;
import java.util.List;
public class DayList {
private String day;
private String weekday;
private List<JiLuList> jilulist;
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getWeekday() {
return weekday;
}
public void setWeekday(String weekday) {
this.weekday = weekday;
}
public List<JiLuList> getJilulist() {
return jilulist;
}
public void setJilulist(List<JiLuList> jilulist) {
this.jilulist = jilulist;
}
}
| true |
873a33ffac6cb6c3ced5593c9d8b01ab02bd092f | Java | bellmit/oa-parent | /oaCommon/src/main/java/com/ule/oa/common/spring/config/CustomPropertyPlaceholderConfigurer.java | UTF-8 | 1,054 | 2.453125 | 2 | [] | no_license | package com.ule.oa.common.spring.config;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* 解析properties
*
* @author zhangwei@tomstaff.com
*/
public class CustomPropertyPlaceholderConfigurer extends
PropertyPlaceholderConfigurer {
private static Map<String, Object> propertiesMap = new HashMap<String, Object>();
@Override
protected void processProperties(
ConfigurableListableBeanFactory beanFactoryToProcess,
Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
propertiesMap.put(keyStr, value);
}
}
public static Object getProperty(String name) {
return propertiesMap.get(name);
}
}
| true |
a39d4b15bb91e3969102961b540a838ae2b695f8 | Java | Suhejl/LernendeVerwaltung | /app/src/main/java/ch/noseryoung/lernendeverwaltung/activity/MainActivity.java | UTF-8 | 1,715 | 2.5625 | 3 | [] | no_license | package ch.noseryoung.lernendeverwaltung.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import ch.noseryoung.lernendeverwaltung.R;
import ch.noseryoung.lernendeverwaltung.repository.ApprenticeDao;
import ch.noseryoung.lernendeverwaltung.repository.ApprenticeDatabase;
/**
* Class that opens up the very first page of our application, the welcome page.
*/
public class MainActivity extends AppCompatActivity {
// Database connection
private static ApprenticeDao apprenticeDao;
/**
* Creates the view and displays it to the apprentice.
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apprenticeDao = ApprenticeDatabase.getApprenticeDb(this).getApprenticeDao();
Button seeApprenticeButton = findViewById(R.id.home_seeApprenticesButton);
seeApprenticeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openApprenticelist();
}
});
}
/**
* Gives the datase connection to all other classes, which are in need of data.
*
* @return
*/
public static ApprenticeDao getApprenticeDao() {
return apprenticeDao;
}
/**
* Opens new activity which displays the apprentice list
*/
private void openApprenticelist() {
Intent intend = new Intent(this, ApprenticelistActivity.class);
startActivity(intend);
}
}
| true |
dc4683cd428f78e45f16045d2417d0ae63bc5a95 | Java | Ahmad-AZ/INLOOP | /12 Pricing/src/BestForCustomerPricing.java | UTF-8 | 860 | 2.859375 | 3 | [] | no_license | import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
public class BestForCustomerPricing extends ComplexPricing {
public BestForCustomerPricing(ISalePricing pricing) {
Objects.requireNonNull(pricing);
this.add(pricing);
}
@Override
public long getTotal(Sale sale) {
AtomicLong currentTotal = new AtomicLong();
currentTotal.set(sale.getPreDiscountTotal());
System.out.println(currentTotal.get());
this.getPricings().forEach(
pricing -> {
if (pricing.getTotal(sale) < currentTotal.get()) {
System.out.println(pricing.getTotal(sale));
currentTotal.set(pricing.getTotal(sale));
}});
System.out.println(currentTotal.get());
return currentTotal.get();
}
}
| true |
317eca200948341428796281661e2019c25064d4 | Java | NolanJos/vespa | /jdisc_http_service/src/main/java/com/yahoo/jdisc/http/server/jetty/HealthCheckProxyHandler.java | UTF-8 | 10,412 | 1.96875 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http.server.jetty;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.ConnectorConfig;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContexts;
import org.eclipse.jetty.server.DetectorConnectionFactory;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import javax.net.ssl.SSLContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.yahoo.jdisc.Response.Status.NOT_FOUND;
import static com.yahoo.jdisc.http.core.HttpServletRequestUtils.getConnectorLocalPort;
/**
* A handler that proxies status.html health checks
*
* @author bjorncs
*/
class HealthCheckProxyHandler extends HandlerWrapper {
private static final Logger log = Logger.getLogger(HealthCheckProxyHandler.class.getName());
private static final String HEALTH_CHECK_PATH = "/status.html";
private final Map<Integer, ProxyTarget> portToProxyTargetMapping;
HealthCheckProxyHandler(List<JDiscServerConnector> connectors) {
this.portToProxyTargetMapping = createPortToProxyTargetMapping(connectors);
}
private static Map<Integer, ProxyTarget> createPortToProxyTargetMapping(List<JDiscServerConnector> connectors) {
var mapping = new HashMap<Integer, ProxyTarget>();
for (JDiscServerConnector connector : connectors) {
ConnectorConfig.HealthCheckProxy proxyConfig = connector.connectorConfig().healthCheckProxy();
if (proxyConfig.enable()) {
Duration targetTimeout = Duration.ofMillis((int) (proxyConfig.clientTimeout() * 1000));
mapping.put(connector.listenPort(), createProxyTarget(proxyConfig.port(), targetTimeout, connectors));
log.info(String.format("Port %1$d is configured as a health check proxy for port %2$d. " +
"HTTP requests to '%3$s' on %1$d are proxied as HTTPS to %2$d.",
connector.listenPort(), proxyConfig.port(), HEALTH_CHECK_PATH));
}
}
return mapping;
}
private static ProxyTarget createProxyTarget(int targetPort, Duration targetTimeout, List<JDiscServerConnector> connectors) {
JDiscServerConnector targetConnector = connectors.stream()
.filter(connector -> connector.listenPort() == targetPort)
.findAny()
.orElseThrow(() -> new IllegalArgumentException("Could not find any connector with listen port " + targetPort));
SslContextFactory.Server sslContextFactory =
Optional.ofNullable(targetConnector.getConnectionFactory(SslConnectionFactory.class))
.or(() -> Optional.ofNullable(targetConnector.getConnectionFactory(DetectorConnectionFactory.class))
.map(detectorConnFactory -> detectorConnFactory.getBean(SslConnectionFactory.class)))
.map(connFactory -> (SslContextFactory.Server) connFactory.getSslContextFactory())
.orElseThrow(() -> new IllegalArgumentException("Health check proxy can only target https port"));
return new ProxyTarget(targetPort, targetTimeout, sslContextFactory);
}
@Override
public void handle(String target, Request request, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException {
int localPort = getConnectorLocalPort(servletRequest);
ProxyTarget proxyTarget = portToProxyTargetMapping.get(localPort);
if (proxyTarget != null) {
if (servletRequest.getRequestURI().equals(HEALTH_CHECK_PATH)) {
try (CloseableHttpResponse proxyResponse = proxyTarget.requestStatusHtml()) {
servletResponse.setStatus(proxyResponse.getStatusLine().getStatusCode());
servletResponse.setHeader("Vespa-Health-Check-Proxy-Target", Integer.toString(proxyTarget.port));
HttpEntity entity = proxyResponse.getEntity();
if (entity != null) {
Header contentType = entity.getContentType();
if (contentType != null) {
servletResponse.addHeader("Content-Type", contentType.getValue());
}
try (ServletOutputStream output = servletResponse.getOutputStream()) {
entity.getContent().transferTo(output);
}
}
} catch (Exception e) { // Typically timeouts which are reported as SSLHandshakeException
String message = String.format("Health check request from port %d to %d failed: %s", localPort, proxyTarget.port, e.getMessage());
log.log(Level.WARNING, message);
log.log(Level.FINE, e.toString(), e);
servletResponse.sendError(Response.Status.INTERNAL_SERVER_ERROR, message);
if (Duration.ofSeconds(1).compareTo(proxyTarget.timeout) >= 0) { // TODO bjorncs: remove call to close() if client is correctly pruning bad connections (VESPA-17628)
proxyTarget.close();
}
}
} else {
servletResponse.sendError(NOT_FOUND);
}
} else {
_handler.handle(target, request, servletRequest, servletResponse);
}
}
@Override
protected void doStop() throws Exception {
for (ProxyTarget target : portToProxyTargetMapping.values()) {
target.close();
}
super.doStop();
}
private static class ProxyTarget implements AutoCloseable {
final int port;
final Duration timeout;
final SslContextFactory.Server sslContextFactory;
volatile CloseableHttpClient client;
ProxyTarget(int port, Duration timeout, SslContextFactory.Server sslContextFactory) {
this.port = port;
this.timeout = timeout;
this.sslContextFactory = sslContextFactory;
}
CloseableHttpResponse requestStatusHtml() throws IOException {
return client()
.execute(new HttpGet("https://localhost:" + port + HEALTH_CHECK_PATH));
}
// Client construction must be delayed to ensure that the SslContextFactory is started before calling getSslContext().
private CloseableHttpClient client() {
if (client == null) {
synchronized (this) {
if (client == null) {
int timeoutMillis = (int) timeout.toMillis();
client = HttpClientBuilder.create()
.disableAutomaticRetries()
.setMaxConnPerRoute(4)
.setSSLContext(getSslContext(sslContextFactory))
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) // Certificate may not match "localhost"
.setUserTokenHandler(context -> null) // https://stackoverflow.com/a/42112034/1615280
.setUserAgent("health-check-proxy-client")
.setDefaultRequestConfig(
RequestConfig.custom()
.setConnectTimeout(timeoutMillis)
.setConnectionRequestTimeout(timeoutMillis)
.setSocketTimeout(timeoutMillis)
.build())
.build();
}
}
}
return client;
}
private SSLContext getSslContext(SslContextFactory.Server sslContextFactory) {
if (sslContextFactory.getNeedClientAuth()) {
log.info(String.format("Port %d requires client certificate. HTTPS client will use the target server connector's ssl context.", port));
// A client certificate is only required if the server connector's ssl context factory is configured with "need-auth".
// We use the server's ssl context (truststore + keystore) if a client certificate is required.
// This will only work if the server certificate's CA is in the truststore.
return sslContextFactory.getSslContext();
} else {
log.info(String.format(
"Port %d does not require a client certificate. HTTPS client will use a custom ssl context accepting all certificates.", port));
// No client certificate required. The client is configured with a trust manager that accepts all certificates.
try {
return SSLContexts.custom().loadTrustMaterial(new TrustAllStrategy()).build();
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void close() throws IOException {
synchronized (this) {
if (client != null) {
client.close();
client = null;
}
}
}
}
}
| true |
55e43c51c429d5b4426861ae7820c623559a62df | Java | we1zhang/DesignPattern | /DesignPattern/src/main/java/com/zw/designpattern/observer/demo1/Subject.java | UTF-8 | 204 | 2.359375 | 2 | [] | no_license | package com.zw.designpattern.observer.demo1;
public interface Subject {
void registerObserver(Observer observer);
void removeObserver(Observer observer);
void notifyObservers();
}
| true |
d95ec6852f8c979818d9eef37ad66f73cfbb0c78 | Java | ajirea/kuring-app | /app/src/main/java/com/satmaxt/kuring/MusicVideoFragment.java | UTF-8 | 5,253 | 2.078125 | 2 | [] | no_license | package com.satmaxt.kuring;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialog;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager2.widget.ViewPager2;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.satmaxt.kuring.adapter.MusicVideoViewPagerAdapter;
import com.satmaxt.kuring.database.AppDatabase;
import com.satmaxt.kuring.model.MusicModel;
/**
* Tanggal Pengerjaan: 12 Mei 2021
* NIM: 10118068
* Nama: Satria Aji Putra Karma J
* Kelas: IF-2 / AKB-2
*/
public class MusicVideoFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager2 viewPager;
private TabLayoutMediator tabMediator;
private MusicVideoViewPagerAdapter adapter;
private Fragment activeFragment;
private AppCompatDialog dialog;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_music_video, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final FloatingActionButton btnAdd = view.findViewById(R.id.addItem);
adapter = new MusicVideoViewPagerAdapter(this);
tabLayout = view.findViewById(R.id.musicVideoTab);
viewPager = view.findViewById(R.id.musicVideoViewPager);
viewPager.setAdapter(adapter);
tabMediator = new TabLayoutMediator(tabLayout, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
final String[] pages = {
"Musik", "Video"
};
tab.setText(pages[position]);
}
});
tabMediator.attach();
dialog = new AppCompatDialog(getContext());
dialog.setContentView(R.layout.dialog_form_music);
dialog.getWindow()
.setBackgroundDrawable(
new ColorDrawable(Color.TRANSPARENT)
);
dialog.getWindow()
.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Button btnClose = dialog.findViewById(R.id.btnCloseDialog);
btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.hide();
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int current = viewPager.getCurrentItem();
Log.d("CURIT", String.valueOf(current));
// on music tab
if(current == 0) {
showCreateForm("Tambah Music", current);
}
// on video tab
else if(current == 1) {
}
}
});
}
private boolean validateForm() {
final EditText fTitle = dialog.findViewById(R.id.formTitle);
final EditText fArtist = dialog.findViewById(R.id.formArtist);
if(fTitle.length() < 1) {
fTitle.setError("Judul musik tidak boleh kosong.");
return false;
} else if(fArtist.length() < 1) {
fArtist.setError("Penyanyi/Artis tidak boleh kosong.");
return false;
}
return true;
}
private void showCreateForm(String dialogTitle, int viewPagerPosition) {
final TextView title = dialog.findViewById(R.id.dialogTitle);
final Button btnSubmit = dialog.findViewById(R.id.btnSubmit);
final EditText fTitle = dialog.findViewById(R.id.formTitle);
final EditText fArtist = dialog.findViewById(R.id.formArtist);
final MusicFragment fragment = (MusicFragment) adapter.getPages().get(viewPagerPosition);
title.setText(dialogTitle);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(validateForm()) {
MusicModel music = new MusicModel();
music.setTitle(fTitle.getText().toString());
music.setArtist(fArtist.getText().toString());
fragment.presenter.store(music);
fTitle.setText("");
fArtist.setText("");
dialog.dismiss();
}
}
});
dialog.show();
}
} | true |
378a92323c1ea41117fa9f8e7f389342d154c86c | Java | yduchesne/sapia | /corus/modules/client/src/main/java/org/sapia/corus/client/services/deployer/ShellScriptManager.java | UTF-8 | 1,364 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package org.sapia.corus.client.services.deployer;
import java.io.IOException;
import java.rmi.Remote;
import java.util.List;
import org.sapia.corus.client.Module;
import org.sapia.corus.client.common.ProgressQueue;
/**
* Specifies the interface of the module managing shell scripts.
*
* @author yduchesne
*
*/
public interface ShellScriptManager extends Remote, Module {
String ROLE = ShellScriptManager.class.getName();
/**
* @param criteria
* the {@link ShellScriptCriteria} to use.
* @param a
* {@link ProgressQueue}.
*/
public ProgressQueue removeScripts(ShellScriptCriteria criteria);
/**
* @return all the {@link ShellScript}s that this instance holds.
*/
public List<ShellScript> getScripts();
/**
* @param criteria
* the {@link ShellScriptCriteria} to use.
* @return the {@link List} of {@link ShellScript}s matching the given
* criteria.
*/
public List<ShellScript> getScripts(ShellScriptCriteria criteria);
/**
* @param alias
* the alias of the script to execute.
* @throws ScriptNotFoundException
* if no such script is found.
* @throws IOException
* if an error occurs trying to invoke the script.
*/
public ProgressQueue executeScript(String alias) throws ScriptNotFoundException, IOException;
}
| true |
e34ce107adaeea5c4568103dbe17528196498c2b | Java | mohit-kapadiya/SpringProgramming | /src/main/java/com/springcore/lifecycle/usingannotations/User.java | UTF-8 | 806 | 2.734375 | 3 | [] | no_license | package com.springcore.lifecycle.usingannotations;
import org.apache.log4j.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class User {
public static final Logger logger = Logger.getLogger(User.class);
private String city;
public static Logger getLogger() {
return logger;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "User{" +
"city='" + city + '\'' +
'}';
}
@PostConstruct
public void start(){
logger.info("this is a start method");
}
@PreDestroy
public void end(){
logger.info("this is a end method");
}
}
| true |
2dc45ae9a4654030e3e3d76e74c6fe650dae504a | Java | p4535992/sinekarta | /sinekarta-ds-patched-repo/src/main/java/org/sinekartads/alfresco/webscripts/document/SkdsFindRefByNameWS.java | UTF-8 | 1,646 | 2.09375 | 2 | [] | no_license | package org.sinekartads.alfresco.webscripts.document;
import org.alfresco.opencmis.search.CMISQueryService;
import org.alfresco.opencmis.search.CMISResultSet;
import org.alfresco.repo.model.Repository;
import org.alfresco.service.cmr.repository.StoreRef;
import org.sinekartads.alfresco.webscripts.BaseAlfrescoWS;
import org.sinekartads.dto.request.SkdsFindRefByNameRequest;
import org.sinekartads.dto.response.SkdsFindRefByNameResponse;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.Status;
public class SkdsFindRefByNameWS
extends BaseAlfrescoWS<SkdsFindRefByNameRequest, SkdsFindRefByNameResponse> {
private Repository repository;
private CMISQueryService cmisQueryService;
@Override
protected SkdsFindRefByNameResponse executeImpl(
SkdsFindRefByNameRequest req, Status status, Cache cache) {
SkdsFindRefByNameResponse resp = new SkdsFindRefByNameResponse();
StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
CMISResultSet result = cmisQueryService.query("select cmis:objectId from cmis:document where cmis:name = '" + req.getName() + "'",storeRef);
if ( result.getLength() == 0) {
throw new RuntimeException(String.format("document not found: ", req.getName()));
}
resp.setNodeRef(result.getNodeRef(0).toString());
return resp;
}
@Override
public void afterPropertiesSet() throws Exception {
super.afterPropertiesSet();
if(serviceRegistry != null) {
cmisQueryService = serviceRegistry.getCMISQueryService();
}
}
public void setRepository(Repository repository) {
this.repository = repository;
}
}
| true |
a409523e1a7901201e7567d139d2dd791ea3b40a | Java | S1o3urn/RestoApp | /src/ca/mcgill/ecse223/resto/view/ViewReservationFrame.java | UTF-8 | 4,158 | 2.21875 | 2 | [] | no_license | package ca.mcgill.ecse223.resto.view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import ca.mcgill.ecse223.resto.controller.RestoAppController;
import ca.mcgill.ecse223.resto.model.OrderItem;
import ca.mcgill.ecse223.resto.model.Reservation;
public class ViewReservationFrame extends JPanel {
private Integer selectedReservation;
public ViewReservationFrame(RestoAppPage app) {
JFrame frame = new JFrame("ViewReservationFrame");
frame.setResizable(false);
frame.setAlwaysOnTop(true);
selectedReservation = -1;
JLabel reservationLabel = new JLabel("Select Reservation");
DefaultComboBoxModel reservationModel = new DefaultComboBoxModel<Reservation>();
JComboBox<Reservation> reservationBox = new JComboBox<Reservation>();
MyButton deleteRes = new MyButton("View");
MyButton btnClose = new MyButton("Close");
reservationBox.setModel(reservationModel);
reservationBox.setEditable(true);
reservationBox.setMaximumSize(new Dimension(150,20));
reservationBox.getEditor().getEditorComponent().setBackground(Color.WHITE);
reservationBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
JComboBox<String> cb = (JComboBox<String>) evt.getSource();
selectedReservation = cb.getSelectedIndex();
}
});
for (Reservation res : RestoAppController.getReservations()) {
reservationModel.addElement(res);
}
//END COMPONENTS
//INIT
//END INIT
btnClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
deleteRes.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//RestoAppController.deleteReservation((Reservation) reservationBox.getSelectedItem());
new ReservationFrame((Reservation) reservationBox.getSelectedItem());
frame.dispose();
app.refreshData();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Unknown exception: " + ex.getMessage(), null, JOptionPane.ERROR_MESSAGE);
}
//
}
});
// frame.setDefaultCloseOperation(JFrame.);
java.awt.Container contentPane = frame.getContentPane();
GroupLayout layout = new GroupLayout(contentPane);
contentPane.setLayout(layout);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
layout.setHorizontalGroup(
layout.createParallelGroup()
.addGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(reservationLabel))
.addGroup(layout.createParallelGroup()
.addComponent(reservationBox)
))
.addGroup(
layout.createSequentialGroup()
.addComponent(deleteRes)
.addComponent(btnClose)
)
);
// layout.linkSize(SwingConstants.VERTICAL, new java.awt.Component[] {reservationLabel, reservationBox});
// layout.linkSize(SwingConstants.HORIZONTAL, new java.awt.Component[] {reservationLabel, reservationBox});
layout.setVerticalGroup(
layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(reservationLabel)
.addComponent(reservationBox))
.addGroup(layout.createParallelGroup()
.addComponent(deleteRes)
.addComponent(btnClose)
)
);
// Set the x, y, width and height properties
frame.pack();
frame.setVisible(true);
}
} | true |
918191dfa50eb49fe30e9b0d0a4fb79077608046 | Java | silvano-pessoa/ArquiteturaPrimefaces | /java_src/br/com/silvanopessoa/service/impl/FuncionarioService.java | UTF-8 | 12,692 | 2.15625 | 2 | [] | no_license | /**
*
*/
package br.com.silvanopessoa.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import br.com.silvanopessoa.dao.IFuncionarioDAO;
import br.com.silvanopessoa.exception.java.ApplicationMessageException;
import br.com.silvanopessoa.exception.java.BusinessMessageException;
import br.com.silvanopessoa.model.entity.Funcionario;
import br.com.silvanopessoa.service.IFuncionarioService;
import br.com.silvanopessoa.support.ServiceSupport;
import br.com.silvanopessoa.util.SecurityUtils;
import br.com.silvanopessoa.validator.CpfValidator;
/**
* @author silvano.pessoa
*
*/
@Service
public class FuncionarioService extends ServiceSupport implements IFuncionarioService {
/**************************************************************/
/************************* ATRIBUTOS **************************/
/**************************************************************/
private static final long serialVersionUID = -7676073575849665613L;
@Resource
IFuncionarioDAO dao;
private final int LIMITE_MENSAGEM=3;
/**************************************************************/
/****************** PERSISTÊNCIA DE DADOS *********************/
/**************************************************************/
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#save(br.com.silvanopessoa.model.entity.Funcionario)
*/
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void save(Funcionario entity) throws BusinessMessageException, ApplicationMessageException{
if( entity.getFunId() == 0 ){
this.internalSave(entity);
}else{
this.update(entity);
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#internalSave(br.com.silvanopessoa.model.entity.Funcionario)
*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@CacheEvict(value = "funcionarioCache", allEntries=true)
private void internalSave(Funcionario entity) throws BusinessMessageException, ApplicationMessageException{
try {
// Validação CPF
if ( !CpfValidator.validaCPF( entity.getCpf() ) ) {
throw new BusinessMessageException(this.getMessage("app.error.CPF"));
}
this.validateFuncionario(entity);
entity.setSenha(SecurityUtils.md5(entity.getNovaSenha()));
dao.save(entity);
}catch (BusinessMessageException e) {
throw e;
}catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#update(br.com.silvanopessoa.model.entity.Funcionario)
*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@CachePut(value = "funcionarioCache")
private void update(Funcionario entity) throws BusinessMessageException, ApplicationMessageException{
try {
// Validação CPF
if ( !CpfValidator.validaCPF( entity.getCpf() ) ) {
throw new BusinessMessageException(this.getMessage("app.error.CPF"));
}
this.validateFuncionario(entity);
this.validateAssociar(entity);
Funcionario oldFunc = this.findById(entity.getFunId());
if( oldFunc.getAtivo() != entity.getAtivo() && !entity.getAtivo() ){
this.validateDesativar(entity);
}
if(entity.getNovaSenha() != null && !entity.getNovaSenha().equals("")){
entity.setSenha(SecurityUtils.md5(entity.getNovaSenha()));
}
dao.update(entity);
}catch (BusinessMessageException e) {
throw e;
}catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#delete(br.com.silvanopessoa.model.entity.Funcionario)
*/
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
@CacheEvict(value = "funcionarioCache", allEntries=true)
public void delete(Funcionario entity) throws ApplicationMessageException, BusinessMessageException{
try {
//RN01 - Verificar se existe funcionarios vinculados ao boleto, reembolso ou funcionario superior.
this.validateRemove(entity);
dao.delete(entity);
}catch (BusinessMessageException e) {
throw e;
} catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/**************************************************************/
/************************ CONSULTAS ***************************/
/**************************************************************/
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#findAll()
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
@Cacheable(value="funcionarioCache")
public List<Funcionario> findAll() throws ApplicationMessageException {
try {
return dao.findAll();
}catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#findById(java.lang.Long)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public Funcionario findById(int id) throws ApplicationMessageException{
try {
return dao.findById(id);
}catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#find(br.com.silvanopessoa.model.entity.Funcionario)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public List<Funcionario> find(Funcionario entity) throws ApplicationMessageException{
try {
return dao.find(entity);
}catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#findByRazao(java.lang.String)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public List<Funcionario> findListByNome(String nome) throws ApplicationMessageException{
Funcionario pesquisa = new Funcionario();
pesquisa.setNome(nome);
try {
return this.find(pesquisa);
} catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#findByRazao(java.lang.String)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public Funcionario getByUser(String user) throws ApplicationMessageException{
try {
return dao.getByUser(user);
} catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/**
* Retorna todos os funcionários ativos do sistema
* @return Lista com os funcionários ativos
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public List<Funcionario> findByAtivos() throws ApplicationMessageException{
Funcionario funcionario = new Funcionario();
funcionario.setAtivo(true);
return this.find(funcionario);
}
/**s
* Retorna todos os funcionários que são subordinados ao superior
* @return Lista com os funcionários subordinados
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public List<Funcionario> findBySuperior(Funcionario entity) throws ApplicationMessageException{
try {
return dao.findBySuperior(entity);
} catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#getByNome(java.lang.String)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public Funcionario findByNome(String nome) throws ApplicationMessageException{
try {
return dao.findByNome(nome);
} catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#findBySiteCliente(int)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public List<Funcionario> findBySiteCliente(int cliId) throws ApplicationMessageException {
return dao.findBySiteCliente(cliId);
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#findBySite(int)
*/
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public List<Funcionario> findBySite(int sitId)throws ApplicationMessageException {
try {
return dao.findBySite(sitId);
} catch (Exception e) {
throw new ApplicationMessageException(this.getMessage("app.error.unknown"));
}
}
/**************************************************************/
/************************ VALIDAÇÕES **************************/
/**************************************************************/
/**
* @param entity
* @throws BusinessMessageException
*/
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
private void validateFuncionario(Funcionario entity) throws BusinessMessageException{
if(dao.hasDuplicidade(entity)){
throw new BusinessMessageException(this.getMessage("exception.funcionario.userCPF.cadastrado", new Object [] {entity.getUser(), entity.getCpf()}));
}
}
/* (non-Javadoc)
* @see br.com.silvanopessoa.service.IFuncionarioService#validateFuncionarioRemove(br.com.silvanopessoa.model.entity.Funcionario)
*/
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
private void validateRemove(Funcionario entity) throws BusinessMessageException, ApplicationMessageException{
Funcionario entidade = this.findById(entity.getFunId());
String pendencias = new String();
pendencias +=this.validateFuncionarioSuperior(entidade);
if(pendencias.length()>0){
throw new BusinessMessageException(this.getMessage("exception.generic.com.fk", new Object [] {pendencias}));
}
}
/**
* FUNCIONARIO_EXCLUIR - RN02 -Verifica se existe funcionario superior
*
* @param pendencias
* @param entity
* @return
* @throws BusinessMessageException
*/
private String validateFuncionarioSuperior(Funcionario entity) throws BusinessMessageException, ApplicationMessageException{
String pendencias = "";
int mensagem = 0;
// RN02-Verifica se existe funcionario superior.
List<Funcionario> list = this.findBySuperior(entity);
if(list.size()>0){
pendencias= pendencias+"<br/>Funcionario Supervisor:<br/>";
for (Funcionario funcionario : list) {
pendencias=pendencias+"- "+funcionario.getNome()+"<br/>";
mensagem++;
if(mensagem==LIMITE_MENSAGEM) break;
}
}
return pendencias;
}
/**
* FUNCIONARIO_DESATIVAR - RN01 - Não permitir que um funcionário seja superior de si mesmo
*
* @param entity
* @throws BusinessMessageException
*/
public void validateAssociar(Funcionario entity) throws BusinessMessageException{
if( entity.getSuperior()!=null && entity.getFunId() == entity.getSuperior().getFunId() ){
throw new BusinessMessageException(this.getMessage("exception.funcionario.associar.cadastrado"));
}
}
/**
* FUNCIONARIO_ASSOCIAR - RN01 - Não permitir que um funcionário supervisor seja desativado
* até que não haja mais nenhuma associação a outros funcionários
*
* @param entity
* @throws BusinessMessageException
* @throws ApplicationMessageException
*/
public void validateDesativar(Funcionario entity) throws BusinessMessageException, ApplicationMessageException{
List<Funcionario> listFuncionario = this.findBySuperior(entity);
if( listFuncionario.size() > 0 ){
throw new BusinessMessageException(this.getMessage("exception.funcionario.desativar.cadastrado"));
}
}
}
| true |
a232d1b6332e77122a5126fe90d609ef9d0bb78b | Java | csycxc/Pscm | /PscmPersist/src/main/java/com/banry/pscm/persist/dds/DDLI.java | UTF-8 | 478 | 1.984375 | 2 | [] | no_license | package com.banry.pscm.persist.dds;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
/**
* DDL语句接口 : 数据库定义 接口
* @author Administrator
*
*/
public interface DDLI {
@Update("create database ${dbName} DEFAULT CHARSET utf8 COLLATE utf8_general_ci")
public void createDataBase(@Param("dbName") String dbName);
}
| true |
f95e4a7383de5672bcd046e6dcb529301ae86f8b | Java | Twistfull/TestProject | /BMS/src/main/java/com/bms/reader/model/DisallowInfo.java | UTF-8 | 875 | 2.046875 | 2 | [] | no_license | package com.bms.reader.model;
import java.io.Serializable;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.bms.reader.common.ContextHolder;
public class DisallowInfo implements Serializable{
/**
* @fieldName: serialVersionUID
* @fieldType: long
* @Description: TODO
*/
private static final long serialVersionUID = 1L;
/**
* 未归还数量
*/
private Integer countborrow;
/**
* 逾期数量
*/
private Integer countoverdue;
public Integer getCountborrow() {
return countborrow;
}
public void setCountborrow(Integer countborrow) {
this.countborrow = countborrow;
}
public Integer getCountoverdue() {
return countoverdue;
}
public void setCountoverdue(Integer countoverdue) {
this.countoverdue = countoverdue;
}
public DisallowInfo(){
super();
}
}
| true |
dc3280ad5d852a678c12a196eabbc944c87abfd8 | Java | algos-soft/cinquestelle | /src/it/algos/base/libreria/LibPref.java | UTF-8 | 7,341 | 3.140625 | 3 | [] | no_license | /**
* Copyright: Copyright (c) 2006
* Company: Algos s.r.l.
* Author: gac
* Date: 9-feb-2007
*/
package it.algos.base.libreria;
import it.algos.base.errore.Errore;
import it.algos.base.pref.Pref;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Classe astratta con metodi statici. </p> Questa classe astratta: <ul> <li> </li> <li> </li>
* </ul>
*
* @author Guido Andrea Ceresa, Alessandro Valbonesi
* @author gac
* @version 1.0 / 9-feb-2007 ore 20.27.53
*/
public abstract class LibPref {
/**
* Recupera solo la parte terminale del nome canonico.
* <p/>
* Il nome viene restituito sempre minuscolo <br>
*
* @param nomeCanonico da elaborare/convertire
*
* @return nome elaborato
*/
static String getNome(String nomeCanonico) {
/* variabili e costanti locali di lavoro */
String nomeFinale = "";
String sep = ".";
int pos;
try { // prova ad eseguire il codice
/* sicurezza */
nomeFinale = nomeCanonico;
/* ricerca l'ultimo punto separatore */
pos = nomeCanonico.lastIndexOf(sep);
if (pos != -1) {
nomeFinale = nomeCanonico.substring(++pos);
nomeFinale = nomeFinale.toLowerCase();
nomeFinale = nomeFinale.trim();
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return nomeFinale;
}
/**
* Recupera un oggetto dalla mappa di parametri.
* <p/>
*
* @param parametro nome chiave del parametro
*
* @return oggetto
*/
private static Object getOggetto(String parametro) {
/* variabili e costanti locali di lavoro */
Object oggetto = null;
LinkedHashMap<String, Object> mappa;
boolean continua;
try { // prova ad eseguire il codice
mappa = Pref.getArgomenti();
continua = mappa != null;
if (continua) {
oggetto = mappa.get(parametro);
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return oggetto;
}
/**
* Recupera una preferenza booleana.
* <p/>
*
* @param parametro nome chiave del parametro
*
* @return oggetto booleano
*/
static boolean getBool(String parametro) {
/* variabili e costanti locali di lavoro */
boolean valore = false;
Object oggetto;
boolean continua;
try { // prova ad eseguire il codice
oggetto = LibPref.getOggetto(parametro);
continua = oggetto != null;
if (continua) {
if (oggetto instanceof Boolean) {
valore = (Boolean)oggetto;
}// fine del blocco if
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return valore;
}
/**
* Recupera un parametro intero.
* <p/>
*
* @param parametro nome chiave del parametro
*
* @return oggetto intero
*/
static int getInt(String parametro) {
/* variabili e costanti locali di lavoro */
int valore = 0;
Object oggetto;
boolean continua;
try { // prova ad eseguire il codice
oggetto = LibPref.getOggetto(parametro);
continua = oggetto != null;
if (continua) {
if (oggetto instanceof Integer) {
valore = (Integer)oggetto;
}// fine del blocco if
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return valore;
}
/**
* Recupera un parametro stringa.
* <p/>
*
* @param parametro nome chiave del parametro
*
* @return oggetto stringa
*/
static String getStr(String parametro) {
/* variabili e costanti locali di lavoro */
String valore = "";
Object oggetto;
boolean continua;
try { // prova ad eseguire il codice
oggetto = LibPref.getOggetto(parametro);
continua = oggetto != null;
if (continua) {
if (oggetto instanceof String) {
valore = (String)oggetto;
}// fine del blocco if
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return valore;
}
/**
* Recupera un argomento.
* <p/>
*
* @param argomento nome chiave
*
* @return oggetto
*/
static Object getArg(String argomento) {
/* variabili e costanti locali di lavoro */
Object oggetto = null;
LinkedHashMap<String, Object> mappa;
try { // prova ad eseguire il codice
mappa = Pref.getArgomenti();
if (mappa != null) {
oggetto = mappa.get(argomento);
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return oggetto;
}
/**
* Recupera tutti gli argomenti.
* <p/>
*
* @return testo di tutti gli argomenti nella forma chiave/valore per ogni riga
*/
static String getArg() {
/* variabili e costanti locali di lavoro */
String testo = "";
LinkedHashMap<String, Object> mappa;
try { // prova ad eseguire il codice
mappa = Pref.getArgomenti();
if (mappa != null) {
/* traverso tutta la collezione */
for (Map.Entry map : mappa.entrySet()) {
testo += map.getKey();
testo += " = ";
testo += map.getValue();
testo += "\n";
} // fine del ciclo for-each
}// fine del blocco if
} catch (Exception unErrore) { // intercetta l'errore
new Errore(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return testo;
}
/**
* Controlla l'esistenza di un qrgomento.
* <p/>
*
* @return vero se esiste mnella mappa
*/
static boolean isArg(String argomento) {
/* variabili e costanti locali di lavoro */
boolean esiste = false;
LinkedHashMap<String, Object> mappa;
try { // prova ad eseguire il codice
mappa = Pref.getArgomenti();
esiste = mappa.containsKey(argomento);
} catch (Exception unErrore) { // intercetta l'errore
Errore.crea(unErrore);
}// fine del blocco try-catch
/* valore di ritorno */
return esiste;
}
}// fine della classe
| true |
9e8481aaf86f1b94c5632ec0a86af6b836a7b882 | Java | weiliejun/Product_RuLaiBao | /app/src/main/java/com/rulaibao/bean/UnreadNewsCount2B.java | UTF-8 | 1,160 | 2.078125 | 2 | [] | no_license | package com.rulaibao.bean;
import com.rulaibao.network.types.IMouldType;
// 未读消息
public class UnreadNewsCount2B implements IMouldType {
private String insurance;// 保单消息
private String commission; // 佣金消息
private String comment; // 互动消息
private String circle; // 圈子新成员
private String otherMessage; // 其它消息
public String getInsurance() {
return insurance;
}
public void setInsurance(String insurance) {
this.insurance = insurance;
}
public String getCommission() {
return commission;
}
public void setCommission(String commission) {
this.commission = commission;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCircle() {
return circle;
}
public void setCircle(String circle) {
this.circle = circle;
}
public String getOtherMessage() {
return otherMessage;
}
public void setOtherMessage(String otherMessage) {
this.otherMessage = otherMessage;
}
}
| true |
8e4cf4255016419fac4ea846f2ff1adcf9d8f6c7 | Java | zymagic/Minesweep | /app/src/main/java/game/minesweep/CustomActivity.java | UTF-8 | 2,183 | 2.234375 | 2 | [] | no_license | package game.minesweep;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import tapjoy.test.R;
/**
* Created by j-zhangyang5 on 2017/1/22.
*/
public class CustomActivity extends Activity implements View.OnClickListener {
GameSettings min, max;
private EditText widthEdit, heightEdit, minesEdit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_activity);
GameSettings custom = GameSettings.getCustomSettings(this);
min = GameSettings.getMinSettings();
max = GameSettings.getMaxSettings();
TextView width = (TextView) findViewById(R.id.width);
width.setText(String.format("WIDTH (%d - %d)", min.width, max.width));
TextView height = (TextView) findViewById(R.id.height);
height.setText(String.format("HEIGHT (%d - %d)", min.height, max.height));
TextView mines = (TextView) findViewById(R.id.mines);
mines.setText(String.format("MINES (%d - %d)", min.mines, max.mines));
widthEdit = (EditText) findViewById(R.id.width_edit);
widthEdit.setText(Integer.toString(custom.width));
heightEdit = (EditText) findViewById(R.id.height_edit);
heightEdit.setText(Integer.toString(custom.height));
minesEdit = (EditText) findViewById(R.id.mines_edit);
minesEdit.setText(Integer.toString(custom.mines));
findViewById(R.id.ok).setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.ok) {
try {
int w = Integer.parseInt(widthEdit.getText().toString());
int h = Integer.parseInt(heightEdit.getText().toString());
int m = Integer.parseInt(minesEdit.getText().toString());
GameSettings.saveCustomSettings(this, w, h, m);
} catch (Exception e) {
// ignore
}
GameActivity.launch(this, GameSettings.getCustomSettings(this));
finish();
}
}
}
| true |
83368a391eb9f91397199bf7af8135e887948f65 | Java | MEJIOMAH17/rocketbank-api | /reverse/Rocketbank_All_3.12.4_source_from_JADX/sources/jp/co/cyberagent/android/gpuimage/util/TextureRotationUtil.java | UTF-8 | 1,519 | 2.15625 | 2 | [] | no_license | package jp.co.cyberagent.android.gpuimage.util;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import jp.co.cyberagent.android.gpuimage.Rotation;
public final class TextureRotationUtil {
public static final float[] TEXTURE_NO_ROTATION = new float[]{BitmapDescriptorFactory.HUE_RED, 1.0f, 1.0f, 1.0f, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f, BitmapDescriptorFactory.HUE_RED};
public static final float[] TEXTURE_ROTATED_180 = new float[]{1.0f, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f, 1.0f, BitmapDescriptorFactory.HUE_RED, 1.0f};
public static final float[] TEXTURE_ROTATED_270 = new float[]{BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f, 1.0f, BitmapDescriptorFactory.HUE_RED, 1.0f, 1.0f};
public static final float[] TEXTURE_ROTATED_90 = new float[]{1.0f, 1.0f, 1.0f, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED, 1.0f, BitmapDescriptorFactory.HUE_RED, BitmapDescriptorFactory.HUE_RED};
public static float[] getRotation$44ccd82e() {
Rotation rotation = null;
switch (rotation) {
case ROTATION_90:
return TEXTURE_ROTATED_90;
case ROTATION_180:
return TEXTURE_ROTATED_180;
case ROTATION_270:
return TEXTURE_ROTATED_270;
default:
return TEXTURE_NO_ROTATION;
}
}
}
| true |
68c42147e9045198ff066dfe9c9514b530e023a9 | Java | cypark0531/prj1 | /src/com/minihome/updatemember/UpdatePwdController.java | UTF-8 | 1,213 | 2.203125 | 2 | [] | no_license | package com.minihome.updatemember;
import java.io.IOException;
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 com.minihome.dao.MembersDao;
@WebServlet("/updatemember/updatepwd")
public class UpdatePwdController extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id=(String)req.getSession().getAttribute("gid");
MembersDao dao=MembersDao.getIntstance();
String pwd=dao.getMember(id).getPwd();
req.setAttribute("pwd", pwd);
req.getRequestDispatcher("/updatemember/updatepwd.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id=(String)req.getSession().getAttribute("gid");
String pwd=(String)req.getParameter("changepwd");
MembersDao dao=MembersDao.getIntstance();
int n=dao.updatePwd(id,pwd);
if(n>0)req.getRequestDispatcher("/updatemember/update").forward(req, resp);
}
}
| true |
e2fb6dfea68982fd72c157df3e8dc2485545f8d4 | Java | Islati/Commons | /src/main/java/com/caved_in/commons/exceptions/WorldLoadException.java | UTF-8 | 586 | 2.171875 | 2 | [] | no_license | package com.caved_in.commons.exceptions;
public class WorldLoadException extends WorldException {
public WorldLoadException() {
}
public WorldLoadException(String s) {
super(s);
}
public WorldLoadException(String message, Throwable cause) {
super(message, cause);
}
public WorldLoadException(Throwable cause) {
super(cause);
}
public WorldLoadException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| true |
ade64aa9f8cb295f711844ec414b98f8cf2f7de0 | Java | Dushyant-123/TripManagement | /app/src/main/java/com/example/myapplication/SplashActivity.java | UTF-8 | 882 | 2.140625 | 2 | [] | no_license | package com.example.myapplication;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivity.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
finish();
}
}, SPLASH_TIME_OUT);
}
} | true |
74c675347f3ffa3dd2d5a755076c51caaf047931 | Java | jayc595/CrookedInn | /app/src/main/java/com/example/crookedinn/Model/Cart.java | UTF-8 | 1,499 | 2.390625 | 2 | [] | no_license | package com.example.crookedinn.Model;
public class Cart {
private String pid, iname, price, quantity, discount, category, addon;
public Cart() {
}
public Cart(String pid, String iname, String price, String quantity, String discount, String category, String addon) {
this.pid = pid;
this.iname = iname;
this.price = price;
this.quantity = quantity;
this.discount = discount;
this.category = category;
this.addon = addon;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getIname() {
return iname;
}
public void setIname(String iname) {
this.iname = iname;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAddon() {
return addon;
}
public void setAddon(String addon) {
this.addon = addon;
}
}
| true |
e3572b246e5b867a9401d42c0042fb77db32cd6c | Java | joaorafaelalmeida/distributed-systems | /Second Project - Message Distributed/src/ServerRepository/RepositoryInterface.java | UTF-8 | 8,784 | 2.734375 | 3 | [] | no_license | package ServerRepository;
import ComInf.Message;
import ComInf.MessageException;
import ComInf.Parameters;
import ComInf.States.*;
/**
* General description:
* This type of data define the repository interface
*
* @author 65767 - João Rafael Duarte de Almeida
*/
public class RepositoryInterface
{
/**
* Repository (represent the service)
* @serialField logger
*/
private Repository logger;
/**
* Constructor of repository interface
* @param logger repository
*/
public RepositoryInterface(Repository logger)
{
this.logger = logger;
}
/**
* Method to process and reply the messages
* @param inMessage message received
* @return Message if everything is ok
* @throws ComInf.MessageException Message exception
*/
public Message processAndReply (Message inMessage) throws MessageException
{
Message outMessage = null;
/* validating the received message */
switch (inMessage.getType ())
{
case Message.REQ_UPDATE_REFEREE_STATE:
if(inMessage.getState() != RefereeState.END_OF_THE_GAME.getRefereeStateCode() &&
inMessage.getState() != RefereeState.END_OF_THE_MATCH.getRefereeStateCode() &&
inMessage.getState() != RefereeState.START_OF_THE_GAME.getRefereeStateCode() &&
inMessage.getState() != RefereeState.START_OF_THE_MATCH.getRefereeStateCode() &&
inMessage.getState() != RefereeState.TEAMS_READY.getRefereeStateCode() &&
inMessage.getState() != RefereeState.WAIT_FOR_TRIAL_CONCLUSION.getRefereeStateCode() )
throw new MessageException ("Invalid referee state!", inMessage);
break;
case Message.REQ_UPDATE_COACH_STATE:
if(inMessage.getState() != CoachState.ASSEMBLE_TEAM.getCoachStateCode() &&
inMessage.getState() != CoachState.WAIT_FOR_REFEREE_COMMAND.getCoachStateCode() &&
inMessage.getState() != CoachState.WATCH_TRIAL.getCoachStateCode())
throw new MessageException ("Invalid coach state!", inMessage);
if((inMessage.getId() < 0 || inMessage.getId() > Parameters.numCoaches))
throw new MessageException ("Invalid coach id!", inMessage);
break;
case Message.REQ_UPDATE_CONTESTANT_STATE:
if(inMessage.getState() != ContestantState.DO_YOUR_BEST.getContestantStateCode() &&
inMessage.getState() != ContestantState.SEAT_AT_THE_BENCH.getContestantStateCode() &&
inMessage.getState() != ContestantState.STAND_IN_POSITION.getContestantStateCode())
throw new MessageException ("Invalid contestant state!", inMessage);
if((inMessage.getCoachId() < 0 || inMessage.getCoachId() > Parameters.numCoaches))
throw new MessageException ("Invalid coach id!", inMessage);
if((inMessage.getId() < 0 || inMessage.getId() > Parameters.numContestants))
throw new MessageException ("Invalid contestant id!", inMessage);
if(inMessage.getStrength() < 0)
throw new MessageException ("Invalid strength!", inMessage);
break;
case Message.REQ_END_OF_MATCH:
if(inMessage.getState() != RefereeState.END_OF_THE_GAME.getRefereeStateCode() &&
inMessage.getState() != RefereeState.END_OF_THE_MATCH.getRefereeStateCode() &&
inMessage.getState() != RefereeState.START_OF_THE_GAME.getRefereeStateCode() &&
inMessage.getState() != RefereeState.START_OF_THE_MATCH.getRefereeStateCode() &&
inMessage.getState() != RefereeState.TEAMS_READY.getRefereeStateCode() &&
inMessage.getState() != RefereeState.WAIT_FOR_TRIAL_CONCLUSION.getRefereeStateCode() )
throw new MessageException ("Invalid referee state!", inMessage);
break;
case Message.REQ_GET_TEAM:
if((inMessage.getId() < 0 || inMessage.getId() > Parameters.numCoaches))
throw new MessageException ("Invalid coach id!", inMessage);
break;
case Message.REQ_END_OF_REFEREE:
case Message.REQ_END_OF_COACH:
case Message.REQ_END_OF_CONTESTANT:
case Message.REQ_ASSERT_TRIAL_DECISION_REP:
case Message.REQ_END_OF_GAME:
case Message.REQ_SHUTDOWN_SERVER:
break;
default:
throw new MessageException ("Invalid type!", inMessage);
}
/* processing */
switch (inMessage.getType ())
{
case Message.REQ_UPDATE_REFEREE_STATE:
//Do action
logger.updateRefereeState(RefereeState.getRefereeStateByCode(inMessage.getState()));
//Create out message
outMessage = new Message(Message.ACK_UPDATE_REFEREE_STATE);
break;
case Message.REQ_UPDATE_COACH_STATE:
//Do action
logger.updateCoachState(CoachState.getCoachStateByCode(inMessage.getState()),
inMessage.getId());
//Create out message
outMessage = new Message(Message.ACK_UPDATE_COACH_STATE);
break;
case Message.REQ_UPDATE_CONTESTANT_STATE:
//Do action
logger.updateContestantState(ContestantState.getContestantStateByCode(inMessage.getState()),
inMessage.getId(),
inMessage.getCoachId(),
inMessage.getStrength());
//Create out message
outMessage = new Message(Message.ACK_UPDATE_CONTESTANT_STATE);
break;
case Message.REQ_END_OF_REFEREE:
//Do action and create out message
if(logger.endOfReferee())
outMessage = new Message(Message.ACK_END_OF_REFEREE_TRUE);
else
outMessage = new Message(Message.ACK_END_OF_REFEREE_FALSE);
break;
case Message.REQ_END_OF_COACH:
//Do action and create out message
if(logger.endOfCoach())
outMessage = new Message(Message.ACK_END_OF_COACH_TRUE);
else
outMessage = new Message(Message.ACK_END_OF_COACH_FALSE);
break;
case Message.REQ_END_OF_CONTESTANT:
//Do action and create out message
if(logger.endOfContestant())
outMessage = new Message(Message.ACK_END_OF_CONTESTANT_TRUE);
else
outMessage = new Message(Message.ACK_END_OF_CONTESTANT_FALSE);
break;
case Message.REQ_ASSERT_TRIAL_DECISION_REP:
//Do action and create out message
if(logger.assertTrialDecision())
outMessage = new Message(Message.ACK_ASSERT_TRIAL_DECISION_REP_TRUE);
else
outMessage = new Message(Message.ACK_ASSERT_TRIAL_DECISION_REP_FALSE);
break;
case Message.REQ_END_OF_MATCH:
//Do action
logger.endOfMatch(RefereeState.getRefereeStateByCode(inMessage.getState()));
//Create out message
outMessage = new Message(Message.ACK_END_OF_MATCH);
break;
case Message.REQ_GET_TEAM:
//Do action
int [] team = logger.getTeam(inMessage.getId());
//Create out message
outMessage = new Message(Message.ACK_GET_TEAM, inMessage.getId(), team);
break;
case Message.REQ_END_OF_GAME:
//Do action and create out message
if(logger.endOfGame())
outMessage = new Message(Message.ACK_END_OF_GAME_TRUE);
else
outMessage = new Message(Message.ACK_END_OF_GAME_FALSE);
break;
}
return (outMessage);
}
}
| true |
3ebfb7b39208506c8032910a6d8e4885af7adf31 | Java | banyanandroid/Mss | /app/src/main/java/com/banyan/mss/Select_Boarding_point_Activity.java | UTF-8 | 12,572 | 1.867188 | 2 | [] | no_license | package com.banyan.mss;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import Adapter.Trip_List_Adapter;
public class Select_Boarding_point_Activity extends ListActivity {
final String TAG = "Select_Boarding_point.java";
private static final int MY_SOCKET_TIMEOUT_MS = 0;
ListAdapter adapter;
int fromid,toid;
String day,month,year;
int scheduleId;
ArrayList<String> seats=new ArrayList<String>();
ArrayList<String> ladies=new ArrayList<String>();
JSONArray stationpointlist;
String address;
/*queue*/
public static RequestQueue queue;
/*progress bar*/
private ProgressDialog pDialog;
int boarding_id;
ArrayList<HashMap<String, String>>Boarindglist=new ArrayList<HashMap<String,String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_boarding_point);
/*String from=((GlobalValues)this.getApplication()).getfrom();
String to=((GlobalValues)this.getApplication()).getto();
String traveldate=((GlobalValues)this.getApplication()).getdate();*/
/*ActionBar actionBar = getActionBar();
actionBar.setTitle(from+" to "+to);
actionBar.setSubtitle(traveldate);*/
TextView dates = (TextView) findViewById(R.id.triplistA_txt_date);
TextView from = (TextView) findViewById(R.id.triplistA_txt_from);
TextView to = (TextView) findViewById(R.id.triplistA_txt_to);
dates.setText(AppConfig.date);
from.setText(AppConfig.from);
to.setText(AppConfig.to);
seats= getIntent().getStringArrayListExtra("seats");
Log.e(TAG, "seats from boarding point"+seats);
ladies= getIntent().getStringArrayListExtra("ladies");
try {
pDialog = new ProgressDialog(Select_Boarding_point_Activity.this);
pDialog.setMessage("Please wait...");
pDialog.show();
pDialog.setCancelable(false);
queue = Volley.newRequestQueue(Select_Boarding_point_Activity.this);
makeJsonObjectRequest();
} catch (Exception e) {
// TODO: handle exception
}
@SuppressWarnings("unchecked")
ListView lv=getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parnet, android.view.View view,
int position, long id) {
boarding_id=Integer.parseInt(Boarindglist.get(position).get("stationPointId"));
address=Boarindglist.get(position).get("address");
String boardingname=Boarindglist.get(position).get("boardingpointname");
((GlobalValues)Select_Boarding_point_Activity.this.getApplication()).setaddress(address);
((GlobalValues)Select_Boarding_point_Activity.this.getApplication()).setboardingname(boardingname);
Log.e(TAG, "address--------------)"+address);
if(seats.size()==1)
{
Intent in=new Intent(Select_Boarding_point_Activity.this,Passenger_details_Activity.class);
in.putExtra("s_id", scheduleId);
in.putExtra("boarding_id",boarding_id);
in.putExtra("month",month);
in.putExtra("day",day);
in.putExtra("year",year);
in.putExtra("fid", fromid);
in.putExtra("tid",toid);
in.putStringArrayListExtra("seats",seats);
in.putStringArrayListExtra("ladies",ladies);
startActivity(in);
}
else if(seats.size()==2)
{
Intent in=new Intent(Select_Boarding_point_Activity.this,DoubleContact_Activity.class);
in.putExtra("s_id", scheduleId);
in.putExtra("boarding_id",boarding_id);
in.putExtra("month",month);
in.putExtra("day",day);
in.putExtra("year",year);
in.putExtra("fid", fromid);
in.putExtra("tid",toid);
in.putStringArrayListExtra("seats",seats);
in.putStringArrayListExtra("ladies",ladies);
startActivity(in);
}
else if(seats.size()==3)
{
Intent in=new Intent(Select_Boarding_point_Activity.this,ThreeContact_Activity.class);
in.putExtra("s_id", scheduleId);
in.putExtra("boarding_id",boarding_id);
in.putExtra("month",month);
in.putExtra("day",day);
in.putExtra("year",year);
in.putExtra("fid", fromid);
in.putExtra("tid",toid);
in.putStringArrayListExtra("seats",seats);
in.putStringArrayListExtra("ladies",ladies);
startActivity(in);
}
else if(seats.size()==4)
{
Intent in=new Intent(Select_Boarding_point_Activity.this,FourContact_Activity.class);
in.putExtra("s_id", scheduleId);
in.putExtra("boarding_id",boarding_id);
in.putExtra("month",month);
in.putExtra("day",day);
in.putExtra("year",year);
in.putExtra("fid", fromid);
in.putExtra("tid",toid);
in.putStringArrayListExtra("seats",seats);
in.putStringArrayListExtra("ladies",ladies);
startActivity(in);
}
else if(seats.size()==5)
{
Intent in=new Intent(Select_Boarding_point_Activity.this,FifthContact_Activity.class);
in.putExtra("s_id", scheduleId);
in.putExtra("boarding_id",boarding_id);
in.putExtra("month",month);
in.putExtra("day",day);
in.putExtra("year",year);
in.putExtra("fid", fromid);
in.putExtra("tid",toid);
in.putStringArrayListExtra("seats",seats);
in.putStringArrayListExtra("ladies",ladies);
startActivity(in);
}
else if(seats.size()==6)
{
Intent in=new Intent(Select_Boarding_point_Activity.this,SixContact_Activity.class);
in.putExtra("s_id", scheduleId);
in.putExtra("boarding_id",boarding_id);
in.putExtra("month",month);
in.putExtra("day",day);
in.putExtra("year",year);
in.putExtra("fid", fromid);
in.putExtra("tid",toid);
in.putStringArrayListExtra("seats",seats);
in.putStringArrayListExtra("ladies",ladies);
startActivity(in);
}
}
});
fromid=getIntent().getExtras().getInt("fid");
toid=getIntent().getExtras().getInt("tid");
scheduleId=getIntent().getExtras().getInt("sid");
day=getIntent().getExtras().getString("day");
month=getIntent().getExtras().getString("month");
year=getIntent().getExtras().getString("year");
Log.e(TAG, fromid+ ""+ toid +""+scheduleId);
//new AsyncTaskParseJson_boarding().execute();
}
private void makeJsonObjectRequest() {
System.out.println("method inside");
StringRequest request = new StringRequest(Request.Method.GET,
AppConfig.url_boarding_list, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println("inside res method");
Log.d(TAG, response.toString());
System.out.println("response final " + " : " + response.toString());
try {
JSONObject json = new JSONObject(response);
System.out.println("OBJECT" + " : " + json);
// get the array of users
stationpointlist = json.getJSONArray("stationPointList");
for (int i = 0; i < stationpointlist.length(); i++)
{
JSONObject stationpointlist_object=stationpointlist.getJSONObject(i);
JSONObject StationsPointDetails=stationpointlist_object.getJSONObject("StationsPointDetails");
//Log.e(TAG,StationsPointDetails.getString("stationPointType"));
if(StationsPointDetails.getString("stationPointType").equalsIgnoreCase("B"))
{
HashMap<String, String> b = new HashMap<String, String>();
b.put("boardingpointname", StationsPointDetails.getString("stationPointName"));
b.put("address", StationsPointDetails.getString("address"));
Log.e(TAG,"address"+StationsPointDetails.getString("address"));//print logcat
b.put("contactNo", StationsPointDetails.getString("contactNo"));
Log.e(TAG,"contactNo"+StationsPointDetails.getString("contactNo"));//print logcat
b.put("stationPointId",StationsPointDetails.getString("stationPointId"));
Log.e(TAG, "StationId"+StationsPointDetails.get("stationPointId"));//print logcat
b.put("time",StationsPointDetails.getString("time"));
Boarindglist.add(b);
}
}
System.out.println("Boarindglist"+ Boarindglist);
Toast.makeText(getApplicationContext(),"select your boarding point",Toast.LENGTH_SHORT).show();
pDialog.dismiss();
adapter = new SimpleAdapter(
Select_Boarding_point_Activity.this, Boarindglist,
R.layout.boarding_list, new String[] {"boardingpointname","time"},new int[]{
R.id.boardingname,R.id.time});
setListAdapter(adapter);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("inside catch" + e);
e.printStackTrace();
}
pDialog.hide();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("error" + error.toString());
Toast.makeText(Select_Boarding_point_Activity.this, "no internet connection...!", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
MY_SOCKET_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
queue.add(request);
}
}
| true |
89f2a35df2dbc57a591df7c52b98b96af3960b25 | Java | davideC00/lesson-scheduler | /src/main/java/it/uniba/di/sms/orariolezioni/ui/login/LoginActivity.java | UTF-8 | 5,905 | 1.953125 | 2 | [] | no_license | package it.uniba.di.sms.orariolezioni.ui.login;
import android.app.Activity;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import it.uniba.di.sms.orariolezioni.OrarioLezioniApplication;
import it.uniba.di.sms.orariolezioni.R;
import it.uniba.di.sms.orariolezioni.data.DbHandler;
import it.uniba.di.sms.orariolezioni.data.model.User;
import it.uniba.di.sms.orariolezioni.ui.SchedulerActivity;
import it.uniba.di.sms.orariolezioni.ui.TeacherActivity;
public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginViewModel = ViewModelProviders
.of(this, new LoginViewModelFactory(new DbHandler(getBaseContext()), getPreferences(Context.MODE_PRIVATE)))
.get(LoginViewModel.class);
final EditText usernameEditText = findViewById(R.id.username);
final EditText passwordEditText = findViewById(R.id.password);
final Button loginButton = findViewById(R.id.login);
final ProgressBar loadingProgressBar = findViewById(R.id.loading);
loginViewModel.getLoginFormState().observe(this, new Observer<LoginFormState>() {
@Override
public void onChanged(@Nullable LoginFormState loginFormState) {
if (loginFormState == null) {
return;
}
loginButton.setEnabled(loginFormState.isDataValid());
if (loginFormState.getUsernameError() != null) {
usernameEditText.setError(getString(loginFormState.getUsernameError()));
}
if (loginFormState.getPasswordError() != null) {
passwordEditText.setError(getString(loginFormState.getPasswordError()));
}
}
});
loginViewModel.getLoginResult().observe(this, new Observer<LoginResult>() {
@Override
public void onChanged(@Nullable LoginResult loginResult) {
if (loginResult == null) {
return;
}
loadingProgressBar.setVisibility(View.GONE);
if (loginResult.getError() != null) {
showLoginFailed(loginResult.getError());
}
if (loginResult.getSuccess() != null) {
updateUiWithUser(loginResult.getSuccess());
}
setResult(Activity.RESULT_OK);
//Complete and destroy login activity once successful
finish();
}
});
TextWatcher afterTextChangedListener = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// ignore
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// ignore
}
@Override
public void afterTextChanged(Editable s) {
loginViewModel.loginDataChanged(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
};
usernameEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.addTextChangedListener(afterTextChangedListener);
passwordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE ) {
// The sign button is pressed_lesson
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
return false;
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadingProgressBar.setVisibility(View.VISIBLE);
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
}
});
if(loginViewModel.isLoggedIn()){
User user = loginViewModel.getCachedUser();
loginViewModel.login(user.username, "password");
}
}
private void updateUiWithUser(LoggedInUserView model) {
String welcome = getString(R.string.welcome) + model.getUsername();
Intent intent;
Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
if(model.getType().equals("scheduler")){
intent = new Intent(this, SchedulerActivity.class);
}else {
intent = new Intent(this, TeacherActivity.class);
}
((OrarioLezioniApplication) this.getApplication()).setTeacher(model.getUsername());
startActivity(intent);
}
private void showLoginFailed(@StringRes Integer errorString) {
Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
}
}
| true |
ea0d6d65bed8ed8d181e36d6a1a54ef185e553ec | Java | SeelabFhdo/mde4sa-2021-proc | /generated_code/de/fhdo/puls/environmentaldataanalysisquery/src/main/java/de/fhdo/puls/environmentaldataanalysisquery/domain/EnvironmentalDataAnalysis/EnvironmentDataReceived.java | UTF-8 | 1,052 | 2.3125 | 2 | [] | no_license | package de.fhdo.puls.environmentaldataanalysisquery.domain.EnvironmentalDataAnalysis;
import de.fhdo.puls.environmentaldataanalysisquery.domain.EnvironmentalDataAnalysis.SensorValue;
import de.fhdo.puls.environmentaldataanalysisquery.domain.EnvironmentalDataAnalysis.gen.EnvironmentDataReceivedGenImpl;
/* This class might comprise custom code. It will not be overwritten by the code generator as long as it
extends EnvironmentDataReceivedGenImpl. As soon as this is not the case anymore, this file will be
overwritten, when the code generator is not explicitly invoked with the --preserve_existing_files
command line option! */
public class EnvironmentDataReceived extends EnvironmentDataReceivedGenImpl {
public EnvironmentDataReceived() {
super();
}
public EnvironmentDataReceived(String sensorUnitId, SensorValue particulates2, SensorValue particulates10, SensorValue light, SensorValue temperature, SensorValue humidity) {
super(sensorUnitId, particulates2, particulates10, light, temperature, humidity);
}
}
| true |
eaae842714b3b249fbe807cda3ea92c725a98401 | Java | Samuelmv13/srs_codigo_font | /Backend/src/test/java/com/src/web/rest/ReservaRecursoIT.java | UTF-8 | 3,261 | 1.921875 | 2 | [] | no_license | package com.src.web.rest;
import com.src.builder.ReservaBuilder;
import com.src.dominio.Reserva;
import com.src.repositorio.ReservaRepositorio;
import com.src.servico.dto.ReservaDTO;
import com.src.util.IntTestComum;
import com.src.util.TestUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import javax.transaction.Transactional;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
//paulo.teotonio
@Transactional
@RunWith(SpringRunner.class)
public class ReservaRecursoIT extends IntTestComum {
@Autowired
private ReservaBuilder reservaBuilder;
@Autowired
private ReservaRepositorio reservaRepositorio;
@BeforeEach
public void limparBanco(){
reservaRepositorio.deleteAll();
}
//get
@Test
public void listar() throws Exception {
reservaBuilder.construir();
getMockMvc().perform(get("/api/reservas"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[*].id", hasSize(1)));
}
@Test
public void salvar() throws Exception {
Reserva reserva = reservaBuilder.construirEntidade();
ReservaDTO reservaDTO = reservaBuilder.converterToDto(reserva);
getMockMvc().perform(post("/api/reservas/")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(reservaBuilder.converterToDto(reserva)))
)
.andExpect(status().isCreated());
}
@Test
public void atualizar()throws Exception{
Reserva reserva = reservaBuilder.construir();
getMockMvc().perform(put("/api/reservas")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(reservaBuilder.converterToDto(reserva)))
)
.andExpect(status().isOk());
}
//buscarPorId
@Test
public void obterPorId()throws Exception{
Reserva reserva = reservaBuilder.construir();
getMockMvc().perform(get("/api/reservas/" + reserva.getId()))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(reserva.getId()));
}
//delete
@Test
public void deletar() throws Exception{
Reserva reserva = reservaBuilder.construir();
getMockMvc().perform(delete("/api/reservas/" + reserva.getId()))
.andExpect(status().isOk());
}
}
| true |
c75eccbdf5645fa2b514e20d83a672e1da385959 | Java | 2p-offer/dynamicDataSource-JPA | /src/main/java/com/erp/dynamicdatasource/entity/mai/ClientAnnounce.java | UTF-8 | 2,048 | 2.03125 | 2 | [] | no_license | package com.erp.dynamicdatasource.entity.mai;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Setter
@Getter
@ToString
@Entity
@Table(name = "client_announce")
public class ClientAnnounce implements Serializable {
private static final long serialVersionUID = 4686456629970025399L;
/**
* 自增id
*/
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
/**
* 平台ID 0=全平台
*/
@Column(name = "plat_id")
private Integer platId;
/**
* 公告图片允许为空(,可能是url或图片名字)
*/
@Column(name = "img_url")
private String imgUrl;
/**
* 公告标题 可选
*/
@Column(name = "title")
private String title;
/**
* 内容标题 可选
*/
@Column(name = "content_title")
private String contentTitle;
/**
* 公告内容 必填
*/
@Column(name = "content")
private String content;
/**
* 公告开始时间戳
*/
@Column(name = "start_time")
private Long startTime;
/**
* 公告结束时间戳
*/
@Column(name = "end_time")
private Long endTime;
/**
* 通告类型 1=系统公告,2=活动公告
*/
@Column(name = "type")
private Integer type;
/**
* 是否置顶 1=置顶
*/
@Column(name = "top")
private Integer top;
/**
* 是否显示红点1=显示
*/
@Column(name = "red_dot")
private Integer redDot;
/**
* 链接类型 1=http链接2=游戏内链接
*/
@Column(name = "img_link_type")
private Integer imgLinkType;
/**
* 图片链接
*/
@Column(name = "img_link")
private String imgLink;
@Column(name = "version")
@Transient
private Date version = new Date();
@Transient
private String startTimeData;
@Transient
private String endTimeData;
}
| true |
350bfa4b9b2dac65924805636fbffd11609f6a01 | Java | Oshi41/Dash-core | /src/main/java/dashcore/structure/NbtLargeStructure.java | UTF-8 | 3,785 | 2.40625 | 2 | [] | no_license | package dashcore.structure;
import dashcore.DashCore;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.structure.MapGenStructure;
import net.minecraft.world.gen.structure.StructureStart;
import net.minecraft.world.gen.structure.template.TemplateManager;
import javax.annotation.Nullable;
import java.util.Random;
import java.util.function.Function;
public class NbtLargeStructure extends MapGenStructure {
private final ResourceLocation folder;
private final ChunkPos size;
private final Function<ChunkPos, BlockPos> posFunc;
private final int chunkDistance;
private final TemplateManager manager;
private Function<ChunkPos, Rotation> rotationFunction;
/**
* @param world - current world
* @param folder - folder with nbt files
* @param chunkDistance - chunk distance between structure
* @param size - size of structure
* @param posFunc - get structure start position from chunk coords. Will use that Y level
* @param rotationFunction - get rotation from chunk coords
*/
public NbtLargeStructure(World world,
ResourceLocation folder,
int chunkDistance,
ChunkPos size,
Function<ChunkPos, BlockPos> posFunc,
Function<ChunkPos, Rotation> rotationFunction) {
this.folder = folder;
this.size = size;
this.posFunc = posFunc;
manager = world.getSaveHandler().getStructureTemplateManager();
this.rotationFunction = rotationFunction;
int minSize = Math.max(2, Math.max(size.x, size.z));
if (chunkDistance < minSize) {
DashCore.log.warn(String.format("Chunk distance of structure (%s) is too small (%s), change it to %s", folder.toString(), chunkDistance, minSize));
chunkDistance = minSize;
}
this.chunkDistance = chunkDistance;
}
@Override
public String getStructureName() {
return folder.getResourcePath();
}
@Nullable
@Override
public BlockPos getNearestStructurePos(World worldIn, BlockPos pos, boolean findUnexplored) {
this.world = worldIn;
// todo think about step by structure size
return findNearestStructurePosBySpacing(world, this, pos, this.chunkDistance, 8, 10387312, false, 100, findUnexplored);
}
@Override
protected boolean canSpawnStructureAtCoords(int chunkX, int chunkZ) {
int i = chunkX;
int j = chunkZ;
if (chunkX < 0) {
i = chunkX - chunkDistance - 1;
}
if (chunkZ < 0) {
j = chunkZ - chunkDistance - 1;
}
int k = i / chunkDistance;
int l = j / chunkDistance;
int folderHash = folder.hashCode();
Random random = this.world.setRandomSeed(k, l, folderHash);
k *= chunkDistance;
l *= chunkDistance;
int smallerParameter = (int) (chunkDistance * 0.75);
k += (random.nextInt(smallerParameter) + random.nextInt(smallerParameter)) / 2;
l += (random.nextInt(smallerParameter) + random.nextInt(smallerParameter)) / 2;
return chunkX == k && chunkZ == l;
}
@Override
protected StructureStart getStructureStart(int chunkX, int chunkZ) {
ChunkPos chunkPos = new ChunkPos(chunkX, chunkZ);
BlockPos position = posFunc.apply(chunkPos);
Rotation rotation = rotationFunction.apply(chunkPos);
return new NbtStructureStart(folder, manager, position, rotation, size);
}
}
| true |
f7e528a64e60eed42e00edbadcfbee5c9d50d958 | Java | solariq/sensearch | /src/main/java/com/expleague/sensearch/web/suggest/SuggestInformationLoader.java | UTF-8 | 1,855 | 2.125 | 2 | [] | no_license | package com.expleague.sensearch.web.suggest;
import com.expleague.sensearch.core.Term;
import com.expleague.sensearch.protobuf.index.IndexUnits;
import com.expleague.sensearch.term.TermBase;
import com.google.common.primitives.Longs;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;
import org.iq80.leveldb.DB;
import org.iq80.leveldb.DBIterator;
public class SuggestInformationLoader {
private static final Logger LOG = Logger.getLogger(SuggestInformationLoader.class);
public final Collection<MultigramWrapper> multigramFreqNorm = new ArrayList<>();
private final DB multigramFreqNormDB;
private final TermBase termBase;
public SuggestInformationLoader(
DB unigramCoeffDB, DB multigramDB, TermBase termBase) {
this.multigramFreqNormDB = multigramDB;
this.termBase = termBase;
tryLoad();
}
private void tryLoad() {
LOG.info("Loading suggest...");
long startTime = System.nanoTime();
{
DBIterator iter = multigramFreqNormDB.iterator();
iter.seekToFirst();
iter.forEachRemaining(
item -> {
Term[] terms = null;
try {
terms =
IndexUnits.TermList.parseFrom(item.getKey())
.getTermListList()
.stream()
.map(termBase::term)
.toArray(Term[]::new);
} catch (InvalidProtocolBufferException e) {
throw new RuntimeException(e);
}
multigramFreqNorm.add(
new MultigramWrapper(terms, Double.longBitsToDouble(Longs.fromByteArray(item.getValue()))));
});
}
LOG.info("Suggest loading finished in " + (System.nanoTime() - startTime) / 1e9 + " seconds");
}
}
| true |
acf07c7bf6c9bb89cf8f6cf42dae3882f636c6b8 | Java | seoj/herd | /herd-code/herd-service/src/main/java/org/finra/herd/service/impl/NotificationRegistrationStatusServiceImpl.java | UTF-8 | 3,609 | 1.898438 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2015 herd contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.finra.herd.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.finra.herd.dao.config.DaoSpringModuleConfig;
import org.finra.herd.model.api.xml.NotificationRegistrationKey;
import org.finra.herd.model.api.xml.NotificationRegistrationStatusUpdateRequest;
import org.finra.herd.model.api.xml.NotificationRegistrationStatusUpdateResponse;
import org.finra.herd.model.jpa.NotificationRegistrationEntity;
import org.finra.herd.model.jpa.NotificationRegistrationStatusEntity;
import org.finra.herd.service.NotificationRegistrationStatusService;
import org.finra.herd.service.helper.NotificationRegistrationDaoHelper;
import org.finra.herd.service.helper.NotificationRegistrationStatusDaoHelper;
@Service
@Transactional(value = DaoSpringModuleConfig.HERD_TRANSACTION_MANAGER_BEAN_NAME)
public class NotificationRegistrationStatusServiceImpl implements NotificationRegistrationStatusService
{
@Autowired
private NotificationRegistrationDaoHelper notificationRegistrationDaoHelper;
@Autowired
private NotificationRegistrationStatusDaoHelper notificationRegistrationStatusDaoHelper;
@Override
public NotificationRegistrationStatusUpdateResponse updateNotificationRegistrationStatus(String namespace, String notificationName,
NotificationRegistrationStatusUpdateRequest notificationRegistrationStatusUpdateRequest)
{
Assert.hasText(namespace, "The namespace must be specified");
Assert.hasText(notificationName, "The notification name must be specified");
String notificationRegistrationStatus = notificationRegistrationStatusUpdateRequest.getNotificationRegistrationStatus();
Assert.hasText(notificationRegistrationStatus, "The notification registration status must be specified");
NotificationRegistrationEntity notificationRegistration = notificationRegistrationDaoHelper.getNotificationRegistration(namespace.trim(),
notificationName.trim());
NotificationRegistrationStatusEntity notificationRegistrationStatusEntity = notificationRegistrationStatusDaoHelper.getNotificationRegistrationStatus(
notificationRegistrationStatus.trim());
notificationRegistration.setNotificationRegistrationStatus(notificationRegistrationStatusEntity);
NotificationRegistrationStatusUpdateResponse notificationRegistrationStatusUpdateResponse = new NotificationRegistrationStatusUpdateResponse();
notificationRegistrationStatusUpdateResponse.setNotificationRegistrationKey(new NotificationRegistrationKey(notificationRegistration
.getNamespace().getCode(), notificationRegistration.getName()));
notificationRegistrationStatusUpdateResponse.setNotificationRegistrationStatus(notificationRegistrationStatusEntity.getCode());
return notificationRegistrationStatusUpdateResponse;
}
}
| true |
86973c16aea8dd179bfdfb6a3aba32b94d680424 | Java | zhwanwan/my8kdj | /src/main/java/com/xxx/jdk8/stream2/ConsumerTest.java | UTF-8 | 1,169 | 3.453125 | 3 | [] | no_license | package com.xxx.jdk8.stream2;
import java.util.function.Consumer;
import java.util.function.IntConsumer;
/**
* @author zhwanwan
* @create 2019-05-30 10:09 PM
*/
public class ConsumerTest {
public static void main(String[] args) {
ConsumerTest consumerTest = new ConsumerTest();
Consumer<Integer> consumer = i -> System.out.println(i);
IntConsumer intConsumer = System.out::println;
consumerTest.test(consumer); //面向对象方式
consumerTest.test(consumer::accept); //函数式方式
consumerTest.test(intConsumer::accept); //函数式方式
System.out.println("---------------------------------");
int a = 0x00000004;
int b = 2;
/*System.out.println(Integer.toBinaryString(a));
System.out.println(Integer.toBinaryString(b));*/
System.out.println(Integer.toHexString(a));
System.out.println(Integer.toHexString(b));
System.out.println(a == b);
System.out.println(Integer.toHexString(a&b));
System.out.println((b & a) == 0);
}
public void test(Consumer<Integer> consumer) {
consumer.accept(100);
}
}
| true |
65a19d19fbbe9650d41ee3ac008c060c199cb3fa | Java | seafield1979/AndroidTest | /TestEvent/app/src/main/java/com/sunsunsoft/shutaro/testevent/MyFragment3.java | UTF-8 | 4,741 | 2.4375 | 2 | [] | no_license | package com.sunsunsoft.shutaro.testevent;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.view.View.OnClickListener;
import android.view.View.OnDragListener;
import android.view.View.OnTouchListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* ドラッグイベント
* ImageViewをドラッグして移動
*/
public class MyFragment3 extends Fragment implements OnClickListener, OnTouchListener, OnDragListener{
private final static String BACKGROUND_COLOR = "background_color";
private Button mButton;
private TextView mTextView;
private ImageView mImageView;
private View mDragView;
private RelativeLayout mContainer;
public static MyFragment3 newInstance(@ColorRes int IdRes) {
MyFragment3 frag = new MyFragment3();
Bundle b = new Bundle();
b.putInt(BACKGROUND_COLOR, IdRes);
frag.setArguments(b);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page3, null);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.fragment_page3_linearlayout);
linearLayout.setBackgroundResource(getArguments().getInt(BACKGROUND_COLOR));
mContainer = (RelativeLayout)view.findViewById(R.id.container1);
mButton = (Button)view.findViewById(R.id.button);
mTextView = (TextView)view.findViewById(R.id.textView3);
mImageView = (ImageView)view.findViewById(R.id.imageView2);
// イベントリスナを設定
mContainer.setOnDragListener(this);
mButton.setOnClickListener(this);
mImageView.setOnTouchListener(this);
return view;
}
@Override
public void onClick(View v) {
ViewGroup.MarginLayoutParams layout = (ViewGroup.MarginLayoutParams)mImageView.getLayoutParams();
layout.leftMargin = 50;
layout.topMargin = 50;
mImageView.setLayoutParams(layout);
}
@Override
public boolean onTouch(View v, MotionEvent e){
switch(e.getAction()) {
case MotionEvent.ACTION_DOWN:
{
// ドラッグ開始
mDragView = v;
mDragView.startDrag(null, new View.DragShadowBuilder(v), null, 0);
}
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
{
Log.v("mylog", "x:" + e.getX() + " y:" + e.getY());
}
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
}
return true;
}
public boolean onDrag(View v, DragEvent e) {
String action = "";
switch(e.getAction()) {
case DragEvent.ACTION_DROP: // ドロップ時
action = "ACTION_DROP";
{
// ImageViewをドロップ先に移動
ViewGroup.MarginLayoutParams layout = (ViewGroup.MarginLayoutParams)mDragView.getLayoutParams();
layout.leftMargin = (int)e.getX() - mDragView.getWidth()/2;
layout.topMargin = (int)e.getY() - mDragView.getHeight()/2;
mDragView.setLayoutParams(layout);
} break;
case DragEvent.ACTION_DRAG_ENDED: //ドラッグ終了
action = "ACTION_DRAG_ENDED";
break;
case DragEvent.ACTION_DRAG_LOCATION: //ドラッグ中
action = "ACTION_DRAG_LOCATION";
Log.v("mylog", "x:" + e.getX() + " y:" + e.getY());
break;
case DragEvent.ACTION_DRAG_STARTED: //ドラッグ開始時
action = "ACTION_DRAG_STARTED";
break;
case DragEvent.ACTION_DRAG_ENTERED: //ドラッグ開始直後
action = "ACTION_DRAG_ENTERED";
break;
case DragEvent.ACTION_DRAG_EXITED: //ドラッグ終了直前
action = "ACTION_DRAG_EXITED";
break;
default:
}
mTextView.setText(action);
return true;
}
}
| true |
51bb746a4c165b2609b6b726e9669bb5293a9eb8 | Java | wjy060708/DubboDemo | /order-service-consumer/src/main/java/com/nanhua/wangjinyin/gmall/service/impl/UserServiceSub.java | UTF-8 | 792 | 2.15625 | 2 | [] | no_license | package com.nanhua.wangjinyin.gmall.service.impl;
import java.util.List;
import org.jboss.netty.util.internal.StringUtil;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.nanhau.wangjinyin.gmall.bean.UserAddress;
import com.nanhau.wangjinyin.gmall.service.UserService;
public class UserServiceSub implements UserService {
private final UserService userService;
//传入的是userService的远程代理对象
public UserServiceSub(UserService userService) {
this.userService = userService;
}
@Override
public List<UserAddress> getUserAddressList(String userId) {
if(StringUtils.isEmpty(userId)) {
System.out.println("本地从根被调用");
return userService.getUserAddressList(userId);
}
return null;
}
}
| true |
d2199734835374d79d8fcfc29948c8e2cef47cc4 | Java | DavideGioiosa/ing-sw-2018-franzini-giannetti-gioiosa | /src/main/java/it/polimi/se2018/connection/server/rmi/RMITypeServer.java | UTF-8 | 2,557 | 3.0625 | 3 | [] | no_license | package it.polimi.se2018.connection.server.rmi;
import static it.polimi.se2018.view.graphic.cli.CommandLinePrint.*;
import it.polimi.se2018.model.PlayerMessage;
import it.polimi.se2018.utils.Observable;
import it.polimi.se2018.utils.Observer;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
/**
* RMI server's class
* @author Silvia Franzini
*/
public class RMITypeServer implements Observer<PlayerMessage> {
//private static int port=1099 verrà presa da file
/**
* Reference to object that implements RMI server's remote methods
*/
private ServerImplementation serverImplementation;
/**
* Observable object to implement callbacks in connection's operations
*/
private Observable<PlayerMessage> obs;
/**
* Builder method of the class
* @param port chosen port to start the server
*/
public RMITypeServer(int port){
obs = new Observable<>();
try {
//System.setProperty("java.rmi.server.hostname", "192.168.139.100");
LocateRegistry.createRegistry(port);
this.serverImplementation = new ServerImplementation(port);
serverImplementation.addObserver(this);
Naming.rebind("//localhost/RMIServer", serverImplementation);
//Naming.rebind("//192.168.139.101:1099/MyServer", serverImplementation);
println("ServerRMI acceso");
} catch (RemoteException | MalformedURLException e) {
println("Non riesco ad aprire il server");
}
}
/**
* Sender method of RMI server
* @param playerMessage message that has to be send
*/
public void send(PlayerMessage playerMessage){
serverImplementation.sendToClient(playerMessage);
}
/**
* Method invoked to add observer's to the class
* @param observer observer that has to be added
*/
public void addObserver(Observer<PlayerMessage> observer){
obs.addObserver(observer);
}
/**
* Getter method for observable object
* @return
*/
public Observable<PlayerMessage> getObs() {
return obs;
}
/**
* Method used to send message received to upper classes
* @param message message received
*/
@Override
public void update(PlayerMessage message) {
obs.notify(message);
}
/**
* Shutdown method to close connection
*/
public void shutdown(){
serverImplementation.close();
}
}
| true |
adf73f77d571420bbaf1d5ac70335a6c287d8ef2 | Java | LunarBaseEngin/lunar-node | /src/main/java/lunarion/cluster/coordinator/Coordinator.java | UTF-8 | 9,276 | 1.828125 | 2 | [
"Apache-2.0"
] | permissive |
/** LCG(Lunarion Consultant Group) Confidential
* LCG LunarBase team is funded by LCG.
*
* @author LunarBase team, contacts:
* feiben@lunarion.com
* neo.carmack@lunarion.com
*
* The contents of this file are subject to the Lunarion Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License.
* The Original Code is: LunarBase source code
* The LunarBase source code is managed by the development team at Lunarion.com.
* The Initial Developer of the Original Code is the development team at Lunarion.com.
* Portions created by lunarion are Copyright (C) lunarion.
* All Rights Reserved.
*******************************************************************************
*
*/
package lunarion.cluster.coordinator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import org.I0Itec.zkclient.IDefaultNameSpace;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkServer;
import org.apache.helix.HelixAdmin;
import org.apache.helix.controller.HelixControllerMain;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.StateModelDefinition;
import lunarion.cluster.resource.Resource;
import lunarion.cluster.resource.ResourceDistributed;
import lunarion.node.utile.ControllerConstants;
import lunarion.node.utile.Screen;
/*
* CLUSTER STATE: for one resource, if we have 3 nodes,
* and 6 partitions:
localhost_12000 localhost_12001 localhost_12002
DataPartition_0 S M S
DataPartition_1 S S M
DataPartition_2 M S S
DataPartition_3 S S M
DataPartition_4 M S S
DataPartition_5 S M S
*
* All the partitions together calls a resource.
*/
public class Coordinator {
/*
* by default.
*/
private static String ZK_ADDRESS = "localhost:2199";
private static String CLUSTER_NAME = "LunarDB_RTSeventhDB";
/* actually it is a master-slave model */
private static final String STATE_MODEL_NAME = ControllerConstants.STATE_MODEL_NAME;
// states
private static final String SLAVE = "SLAVE";
private static final String OFFLINE = "OFFLINE";
private static final String MASTER = "MASTER";
private static final String DROPPED = "DROPPED";
//private ResourceManager resource_manager = new ResourceManager();
/*
* <resource_name, Resource>
*/
//private HashMap<String, Resource> resource_list = new HashMap<String, Resource>();
private HashMap<String, ResourceDistributed> resource_list = new HashMap<String, ResourceDistributed>();
//private static List<LunarNode> NODE_LIST;
private HelixAdmin admin;
private ControllerConstants controller;
private AtomicBoolean started = new AtomicBoolean(false);
private static class CoordinatorInstatance {
private static final Coordinator g_coordinator = new Coordinator();
}
public static Coordinator getInstance() {
return CoordinatorInstatance.g_coordinator ;
}
public Coordinator()
{
}
public void init(String _zookeeper_addr, String _cluster_name, ControllerConstants _c_p)
{
ZK_ADDRESS = _zookeeper_addr;
CLUSTER_NAME = _cluster_name;
controller = _c_p;
}
public void shutdown()
{
Iterator<String> resources = resource_list.keySet().iterator();
while(resources.hasNext())
{
Resource res = resource_list.get(resources.next());
res.close();
}
}
public void startZookeeper( )
{
Screen.echo("STARTING Zookeeper at: " + ZK_ADDRESS);
IDefaultNameSpace defaultNameSpace = new IDefaultNameSpace() {
@Override
public void createDefaultNameSpace(ZkClient zkClient) {
}
};
new File("/tmp/lunar-coordinator-start").mkdirs();
// start zookeeper
ZkServer server =
new ZkServer("/tmp/lunar-coordinator-start/dataDir",
"/tmp/lunar-coordinator-start/logDir",
defaultNameSpace, 2199);
server.start();
}
public void setup()
{
admin = new ZKHelixAdmin(ZK_ADDRESS);
// create cluster
Screen.echo("Creating cluster: " + CLUSTER_NAME);
admin.addCluster(CLUSTER_NAME, true);
// Add nodes to the cluster
/*
Screen.echo("Adding " + NUM_NODES + " participants to the cluster");
for (int i = 0; i < NUM_NODES; i++) {
admin.addInstance(CLUSTER_NAME, INSTANCE_CONFIG_LIST.get(i));
Screen.echo("\t Added participant: " + INSTANCE_CONFIG_LIST.get(i).getInstanceName());
}
*/
// Add a state model
StateModelDefinition myStateModel = defineStateModel();
Screen.echo("Configuring StateModel: " + STATE_MODEL_NAME +" with 1 Master and 1 Slave");
admin.addStateModelDef(CLUSTER_NAME, STATE_MODEL_NAME, myStateModel);
}
public void addResource( String _resource_name, int _num_partitions, int _num_replicas, int _max_rec_per_partition,
String _meta_file, String _model_file) throws IOException
{
ResourceDistributed res = new ResourceDistributed( admin,
CLUSTER_NAME,
_resource_name,
_num_partitions,
_num_replicas,
_max_rec_per_partition,
_meta_file,
_model_file);
resource_list.put(_resource_name, res);
// Add a resource with 6 partitions and 2 replicas
Screen.echo("Adding a resurce "+_resource_name +": " + "with "+_num_partitions+" partitions and "+_num_replicas +" replicas");
admin.addResource(CLUSTER_NAME, _resource_name, _num_partitions, STATE_MODEL_NAME, "AUTO");
// this will set up the ideal state, it calculates the preference list for
// each partition similar to consistent hashing
//admin.rebalance(CLUSTER_NAME, _resource_name, _num_replicas);
}
public ResourceDistributed getResource(String res_name)
{
return resource_list.get(res_name);
}
private static StateModelDefinition defineStateModel()
{
StateModelDefinition.Builder builder = new StateModelDefinition.Builder(STATE_MODEL_NAME);
// Add states and their rank to indicate priority. Lower the rank higher the
// priority
builder.addState(MASTER, 1);
builder.addState(SLAVE, 2);
builder.addState(OFFLINE);
builder.addState(DROPPED);
// Set the initial state when the node starts
builder.initialState(OFFLINE);
// Add transitions between the states.
builder.addTransition(OFFLINE, SLAVE);
builder.addTransition(SLAVE, OFFLINE);
builder.addTransition(SLAVE, MASTER);
builder.addTransition(MASTER, SLAVE);
builder.addTransition(OFFLINE, DROPPED);
// set constraints on states.
// static constraint
builder.upperBound(MASTER, 1);
// dynamic constraint, R means it should be derived based on the replication
// factor.
builder.dynamicUpperBound(SLAVE, "R");
StateModelDefinition statemodelDefinition = builder.build();
return statemodelDefinition;
}
public static void startController()
{
// start controller
Screen.echo("Starting Helix Controller");
HelixControllerMain.startHelixController(ZK_ADDRESS, CLUSTER_NAME, "localhost_9100",
HelixControllerMain.STANDALONE);
}
public boolean addNodeToResource(String resource_name, String node_ip, int node_port) throws Exception
{
if(this.resource_list.get(resource_name)!=null)
{
this.resource_list.get(resource_name).addNode(node_ip, node_port);
return true;
}
else
return false;
}
public void stopNodeInResource(String resource_name)
{
}
public boolean rebalanceInResource(String resource_name)
{
Resource res = this.resource_list.get(resource_name);
if(res != null)
{
res.rebalance();
return true;
}
return false;
}
public void printState(String msg, String resource_name)
{
System.out.println("CLUSTER "+CLUSTER_NAME+" STATE: " + msg);
ExternalView resourceExternalView = admin.getResourceExternalView(CLUSTER_NAME, resource_name);
TreeSet<String> sortedSet = new TreeSet<String>(resourceExternalView.getPartitionSet());
StringBuilder sb = new StringBuilder("\t\t");
Resource res = this.resource_list.get(resource_name);
if(res == null)
{
System.err.println("CLUSTER does not has resource " + resource_name);
return;
}
for (int i = 0; i < res.getNodeNumber(); i++)
{
sb.append(res.getInstantConfig(i).getInstanceName()).append("\t");
}
System.out.println(sb);
for (String partitionName : sortedSet)
{
sb.delete(0, sb.length() - 1);
sb.append(partitionName).append("\t");
for (int i = 0; i < res.getNodeNumber(); i++)
{
Map<String, String> stateMap = resourceExternalView.getStateMap(partitionName);
if (stateMap != null && stateMap.containsKey(res.getInstantConfig(i).getInstanceName())) {
sb.append(stateMap.get(res.getInstantConfig(i).getInstanceName()).charAt(0)).append(
"\t\t");
}
else
{
sb.append("-").append("\t\t");
}
}
System.out.println(sb);
}
System.out.println("============================================================");
}
}
| true |
dfe247efd2520cb7b15c41f95106ec630178f499 | Java | rajkboddupally/Datastructures-Algorithms | /src/arrays/SquaresSortedArray.java | UTF-8 | 556 | 3.359375 | 3 | [] | no_license | package arrays;
import java.util.Arrays;
import java.util.TreeMap;
public class SquaresSortedArray {
public static void main(String[] args) {
int[] arr = {-4, -1, 0, 3, 10};
SquaresSortedArray r = new SquaresSortedArray();
// System.out.println(r.sortedSquares(arr));
}
public int[] sortedSquares(int[] nums) {
int[] output = new int[nums.length];
for (int i = 0; i < nums.length;i++) {
output[i] = nums[i]*nums[i];
}
Arrays.sort(output);
return output;
}
}
| true |
4decd7ac8a34ab0a188ce5d79c69e185ebca6e84 | Java | X-lun/Java-web | /教务管理系统/school/src/com/sevenEleven/servlet/student/Result.java | UTF-8 | 1,496 | 2.046875 | 2 | [] | no_license | package com.sevenEleven.servlet.student;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sevenEleven.Beans.CstudentBean;
import com.sevenEleven.javaBean.student.CUsMethod;
/**
* Servlet implementation class for Servlet: test
*
*/
public class Result extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public Result() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);// TODO Auto-generated method stub
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Object userid=((CstudentBean)request.getSession().getAttribute("student")).getS_id();
CUsMethod usmethod=new CUsMethod();
List list=usmethod.getResult1(userid);
request.setAttribute("result_1",list);
request.getRequestDispatcher("result.jsp").forward(request,response);
}
} | true |
83a126a4fb29d9415fdf8dd361220123c2fbe043 | Java | divya0403/poovizhi | /Trip/src/main/java/Cleartrip/Trip/Screenshot.java | UTF-8 | 1,396 | 2.0625 | 2 | [] | no_license | package Cleartrip.Trip;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;
public class Screenshot implements ITestListener
{
public void onTestFailure(ITestResult il)
{
String mn=il.getName();
takeScreenshot(mn);
}
public void takeScreenshot(String name)
{
FirefoxDriver ff= (FirefoxDriver)SuperTestScript.driver;
File f1=ff.getScreenshotAs(OutputType.FILE);
File f2= new File("./failure_screenshots/"+name+".png");
try
{
FileUtils.moveFile(f1,f2);
}
catch(Exception obj)
{
Reporter.log("Screenshot not moved -------",true);
}
}
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub
}
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestStart(ITestResult arg0) {
// TODO Auto-generated method stub
}
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
}
}
| true |
70c5ebebfcc33763865ee24820e0e601bbd633a6 | Java | topera/gradle-springboot-cli | /src/main/java/com/ef/dao/DBCheck.java | UTF-8 | 1,413 | 2.53125 | 3 | [
"MIT"
] | permissive | package com.ef.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
/**
* Check database access
*/
@Component
public class DBCheck {
private static final Logger log = LoggerFactory.getLogger(DBCheck.class);
@Autowired
private JdbcTemplate jdbcTemplate;
public void testConnection() {
log.info("Testing connection with database");
try {
printConnectionDetails();
} catch (SQLException e) {
log.error("Connection Failed!", e);
}
}
private void printConnectionDetails() throws SQLException {
try (Connection connection = jdbcTemplate.getDataSource().getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
log.info("");
log.info("Connection details:");
log.info("");
log.info("> userName: " + metaData.getUserName());
log.info("> URL: " + metaData.getURL());
log.info("> DatabaseProductName: " + metaData.getDatabaseProductName());
log.info("> Version: " + metaData.getDatabaseProductVersion());
log.info("");
}
}
}
| true |
debf15829a3736598489bfbb598a18c40ae2c227 | Java | roshankr1/csc343-Hospital-Management-System | /CSC343-Hospital-Management-System/src/SelectRecord.java | UTF-8 | 15,664 | 2.390625 | 2 | [] | no_license |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author pratik
*/
public class SelectRecord extends javax.swing.JFrame {
/**
* Creates new form SelectRecord
*/
public SelectRecord() {
initComponents();
try
{
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/HMS_0049", Info.user, Info.pass);
stat=conn.createStatement();
String query="Select RecordId from RecordDoctor where DoctorId='"+Info.UserId+"'";
Vector<String> v=new Vector<String>();
rs=stat.executeQuery(query);
while(rs.next())
{
v.add(rs.getString(1));
}
recordCb.setModel(new DefaultComboBoxModel<String>(v));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(rootPane,e.getMessage());
}
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
recordCb = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
nameTf = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
ageTf = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
genderTf = new javax.swing.JTextField();
openBtn = new javax.swing.JButton();
homeBtn = new javax.swing.JButton();
resetBtn = new javax.swing.JButton();
exitBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 24)); // NOI18N
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Record");
jLabel2.setText("Record");
recordCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
recordCb.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
recordCbItemStateChanged(evt);
}
});
jLabel3.setText("Name");
nameTf.setEditable(false);
jLabel4.setText("Age");
ageTf.setEditable(false);
jLabel5.setText("Gender");
genderTf.setEditable(false);
openBtn.setText("Open");
openBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openBtnActionPerformed(evt);
}
});
homeBtn.setText("Home");
homeBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
homeBtnActionPerformed(evt);
}
});
resetBtn.setText("Reset");
resetBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetBtnActionPerformed(evt);
}
});
exitBtn.setText("Exit");
exitBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(recordCb, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nameTf)
.addComponent(ageTf)
.addComponent(genderTf)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(openBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(homeBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(resetBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(exitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(recordCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(nameTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(ageTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(genderTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(openBtn)
.addComponent(homeBtn)
.addComponent(resetBtn)
.addComponent(exitBtn))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void exitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitBtnActionPerformed
// TODO add your handling code here:
System.exit(0);
}//GEN-LAST:event_exitBtnActionPerformed
private void resetBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetBtnActionPerformed
// TODO add your handling code here:
nameTf.setText(null);
ageTf.setText(null);
genderTf.setText(null);
try
{
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/HMS_0049", Info.user, Info.pass);
stat=conn.createStatement();
String query="Select RecordId from RecordDoctor where DoctorId='"+Info.UserId+"'";
Vector<String> v=new Vector<String>();
rs=stat.executeQuery(query);
while(rs.next())
{
v.add(rs.getString(1));
}
recordCb.setModel(new DefaultComboBoxModel<String>(v));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(rootPane,e.getMessage());
}
}//GEN-LAST:event_resetBtnActionPerformed
private void recordCbItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_recordCbItemStateChanged
// TODO add your handling code here:
try
{
Connection conn=null;
Statement stat=null;
ResultSet rs=null;
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/HMS_0049", Info.user, Info.pass);
stat=conn.createStatement();
String RecordId=(String)recordCb.getSelectedItem();
String query="Select concat(FirstName,' ',LastName),Age,Gender from Record,Patient where Record.PatientId=Patient.Id and RecordId='"+RecordId+"'";
rs=stat.executeQuery(query);
String name="",age="",gender="";
if(rs.next())
{
name=rs.getString(1);
age=rs.getString(2);
gender=rs.getString(3);
}
nameTf.setText(name);
ageTf.setText(age);
genderTf.setText(gender);
}
catch(Exception e)
{
JOptionPane.showMessageDialog(rootPane,e.getMessage());
}
}//GEN-LAST:event_recordCbItemStateChanged
private void openBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openBtnActionPerformed
// TODO add your handling code here:
Info.selectedRecordId=(String)recordCb.getSelectedItem();
new Doctor().setVisible(true);
this.dispose();
}//GEN-LAST:event_openBtnActionPerformed
private void homeBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homeBtnActionPerformed
// TODO add your handling code here:
if(Info.Type.equals("Admin"))
{
new AdminHome().setVisible(true);
this.dispose();
}
else
{
new DoctorHome().setVisible(true);
this.dispose();
}
}//GEN-LAST:event_homeBtnActionPerformed
/**
* @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(SelectRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SelectRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SelectRecord.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SelectRecord.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 SelectRecord().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField ageTf;
private javax.swing.JButton exitBtn;
private javax.swing.JTextField genderTf;
private javax.swing.JButton homeBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField nameTf;
private javax.swing.JButton openBtn;
private javax.swing.JComboBox<String> recordCb;
private javax.swing.JButton resetBtn;
// End of variables declaration//GEN-END:variables
}
| true |
a8172c948d36430c0c5fea6fdfa19ff96ab9d59e | Java | JonnathanAndres/simo | /app/src/main/java/com/jari/example/navigationdrawer/utilidades/CustomSpinnerAdapter.java | UTF-8 | 1,887 | 2.375 | 2 | [] | no_license | //package com.jari.example.navigationdrawer.utilidades;
//
//import android.content.Context;
//import android.view.LayoutInflater;
//
//import com.jari.example.navigationdrawer.models.parametros.Nivel;
//
///**
// * Created by Jonnathan on 11/09/2016.
// */
//public class CustomSpinnerAdapter {
//
// public static CustomSpinnerAdapter<NIvel> DevuelveTipoPrestamoConYSinCondicionesEspecialesArrayAdapter(Context context, LayoutInflater inflater, int secuencialModalidadCreditoCliente, boolean tieneCondicionesEspeciales) throws Exception
// {
//
// TipoPrestamoConYSinCondicionesEspecialesMS listaTipoPrestamoMS = new TipoPrestamoActor(context).DevuelveTipoPrestamoConYSinCondicionesEspecialesMS(
// true,
// true,
// true,
// secuencialModalidadCreditoCliente);
//
// ArrayList<TipoPrestamoMSE> tipoPrestamoMSEList = new ArrayList<>();
// String prompt = "";
//
// if(tieneCondicionesEspeciales) {
// prompt = "Condiciones Especiales";
// tipoPrestamoMSEList.add(new TipoPrestamoMSE("0", "Condiciones Especiales"));
// if(secuencialModalidadCreditoCliente!=0)
// tipoPrestamoMSEList.addAll(listaTipoPrestamoMS.getListaTipoPrestamoConCondicionesEspeciales());
// }
// else {
// prompt = "Tipo Producto y Crédito";
// tipoPrestamoMSEList.add(new TipoPrestamoMSE("0", "Tipo Producto y Crédito"));
// if(secuencialModalidadCreditoCliente!=0)
// tipoPrestamoMSEList.addAll(listaTipoPrestamoMS.getListaTipoPrestamoSinCondicionesEspeciales());
// }
//
//
// CustomSpinnerAdapter tipoPrestamoAdapter = new CustomSpinnerAdapter(context, R.layout.custom_spinner,inflater,tipoPrestamoMSEList,prompt,"Codigo","Nombre");
//
// return tipoPrestamoAdapter;
// }
//
//}
| true |
55d88787f307a5ca7d2d65538bb858cd7c1720fe | Java | yeshbhosale/Woof | /app/src/main/java/com/example/dell/woof/model/MyLove.java | UTF-8 | 2,075 | 2.21875 | 2 | [] | no_license | package com.example.dell.woof.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* Created by Dell on 24-09-2016.
*/
public class MyLove implements Serializable {
@SerializedName("pet1")
private Love pet1;
@SerializedName("pet2")
private Love pet2;
@SerializedName("user")
private String userId;
@SerializedName("targetuser")
private String targetUser;
@SerializedName("status")
private String status;
@SerializedName("id")
private String id;
public class Love implements Serializable{
@SerializedName("name")
private String name;
@SerializedName("pet_img")
private String[] pet_Images;
@SerializedName("id")
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String[] getPet_Images() {
return pet_Images;
}
public void setPet_Images(String[] pet_Images) {
this.pet_Images = pet_Images;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
public Love getPet1() {
return pet1;
}
public void setPet1(Love pet1) {
this.pet1 = pet1;
}
public Love getPet2() {
return pet2;
}
public void setPet2(Love pet2) {
this.pet2 = pet2;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTargetUser() {
return targetUser;
}
public void setTargetUser(String targetUser) {
this.targetUser = targetUser;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| true |
b34669bfeba351cf330d66f7838e4dc522762d01 | Java | vikramuvs/msrit-demo | /src/main/java/com/example/demo/model/LatestNews.java | UTF-8 | 2,706 | 2.328125 | 2 | [] | no_license | package com.example.demo.model;
import javax.persistence.*;
import java.sql.Date;
@Entity
@Table(name="tbl_latest_news")
public class LatestNews {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "is_featured")
private boolean isFeatured;
@Column(name = "department_id")
private int departmentId;
@Column(name = "published_date")
private Date publishedDate;
@Column(name = "title")
private String title;
@Column(name = "description")
private String description;
@Column(name = "banner_URL")
private String bannerURL;
@Column(name = "publisher_Name")
private String publisherName;
@Column(name = "link_URL")
private String linkURL;
public LatestNews() {
}
public LatestNews(boolean isFeatured, int departmentId, Date publishedDate, String title, String description, String bannerURL, String publisherName, String linkURL) {
super();
this.isFeatured = isFeatured;
this.departmentId = departmentId;
this.publishedDate = publishedDate;
this.title = title;
this.description = description;
this.bannerURL = bannerURL;
this.publisherName = publisherName;
this.linkURL = linkURL;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isFeatured() {
return isFeatured;
}
public void setFeatured(boolean featured) {
isFeatured = featured;
}
public int getDepartmentId() {
return departmentId;
}
public void setDepartmentId(int departmentId) {
this.departmentId = departmentId;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
this.publishedDate = publishedDate;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
description = description;
}
public String getBannerURL() {
return bannerURL;
}
public void setBannerURL(String bannerURL) {
this.bannerURL = bannerURL;
}
public String getPublisherName() {
return publisherName;
}
public void setPublisherName(String publisherName) {
this.publisherName = publisherName;
}
public String getLinkURL() {
return linkURL;
}
public void setLinkURL(String linkURL) {
this.linkURL = linkURL;
}
}
| true |
55d182b1c6ffee6a3ffdd85640d787cef12da77b | Java | Goldyr/TP7_LAB4_JAVA | /src/entidades/Seguro.java | UTF-8 | 1,243 | 2.71875 | 3 | [] | no_license | package entidades;
public class Seguro {
private int idSeguro;
private String descripcion;
private int idTipo;
private int costoContratacion;
private int costoAsegurado;
public Seguro() {}
public Seguro(int idSeguro, String descripcion, int idTipo, int costoContratacion, int costoAsegurado) {
setIdSeguro(idSeguro);
setDescripcion(descripcion);
setIdTipo(idTipo);
setCostoContratacion(costoContratacion);
setCostoAsegurado(costoAsegurado);
}
public int getIdSeguro() {
return idSeguro;
}
public void setIdSeguro(int idSeguro) {
this.idSeguro = idSeguro;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getIdTipo() {
return idTipo;
}
public void setIdTipo(int idTipo) {
this.idTipo = idTipo;
}
public int getCostoContratacion() {
return costoContratacion;
}
public void setCostoContratacion(int costoContratacion) {
this.costoContratacion = costoContratacion;
}
public int getCostoAsegurado() {
return costoAsegurado;
}
public void setCostoAsegurado(int costoAsegurado) {
this.costoAsegurado = costoAsegurado;
}
}
| true |
6c65c300c6e30a4300edf8b2db770c2d80a38d97 | Java | ironworker/Sweng311 | /HW8P1/src/MyUtility.java | UTF-8 | 1,002 | 2.75 | 3 | [] | no_license | <<<<<<< HEAD
=======
>>>>>>> 2e168cc292326a8e46f5af0eab6002f8e043b1ea
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
<<<<<<< HEAD
*
* @author 401
*/
//import java.lang.reflect;
public class MyUtility extends Utility {
Utility text = new Utility();
String a = text.showData("Data.txt");
//"This is a book."
public void getLine(){
String[] b = a.split("\\s+");//special escape thing to split without space
//int j = 1;
for(int i=0;i<b.length;i++)
{
//if(!b[i].contains(" ")){
System.out.print(i+1);
System.out.print(": ");
//j++;
System.out.println(b[i]);
//}
}
}
=======
*
* @author Matthew_Swenson
*/
public class MyUtility extends Utility{
//@Override
String a;
a = "public static void main( String args[] )";
>>>>>>> 2e168cc292326a8e46f5af0eab6002f8e043b1ea
}
| true |