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
b4cf1455668bf2907018959b9819adb0de5ceacd
Java
Sonhaack/ADS-assignment1
/src/List/Stack.java
UTF-8
191
2.65625
3
[]
no_license
package List; import java.util.EmptyStackException; public interface Stack<T> { public boolean isEmpty(); public void push(T elm); public T pop() throws EmptyStackException; }
true
eda8f9904c4afd2c92a63144f434f58f52ffe9cc
Java
rkalz/CS203
/Lab11/src/Pair.java
UTF-8
2,545
4.28125
4
[]
no_license
/** * Class representing paired object. * * @author spoudel * * @param <E> * Type of object to pair. */ public class Pair<E> { /** * First element of the pair */ private E first; /** * second element of the pair */ private E second; /** * Constructor for creating a pair with two elements. * * @param f * the first element * @param s * the second element */ public Pair(E f, E s) { first = f; second = s; } /** * Get the first element. * * @return first element */ public E getFirst() { return first; // null is dummy, and used to avoid compile error. Please replace false with our actual result } /** * Get the second element. * * @return second element */ public E getSecond() { return second; // null is dummy, and used to avoid compile error. Please replace false with our actual result } /** * Checking if this pair equals the other pair. * * @param other * the pair object to be compared with * * @return true if both pair have same set of elements in same order i.e * first element of both pair are equal and the second element of * both pair are equal */ public boolean equals(Pair other) { if (!(other instanceof Pair)) { return false; } E otherFirst = (E) other.getFirst(); E otherSecond = (E) other.getSecond(); if (otherFirst.equals(first) && otherSecond.equals(second)) { return true; } return false; // false is dummy, and used to avoid compile error. Please replace false with our actual result } /** * Return the hash code of the object. * * @return hash code for the object * @postcondition if pair1 equals pair2 hashCode(pair1) must equal * hashCode(pair2) */ public int hashCode() { /** * XOR is good for combining two hashcodes because XOR has two outputs * as 0 and two outputs as 1 for different combination of 0 & 1 thus * making distribution uniform. 0 0 -> 0 0 1 -> 1 1 0 -> 1 1 1 -> 0 */ // the hash value of the first and second element . XOR those value. Then return the output // XOR operator: ^ return first.hashCode() ^ second.hashCode(); // 0 is dummy, and used to avoid compile error. Please replace false with our actual result } /** * Return the string as (first element, second element) */ public String toString() { return "(" + first.toString() + "," + second.toString() + ")"; // null is temporary. replace null with your actual value } }
true
d2b6149257a4b9fd93226a9bb42fe6bf529a15ed
Java
Jagannathan16/Project_0
/project0Again/src/main/java/com/company/factory/Factory.java
UTF-8
1,122
2.734375
3
[]
no_license
package com.company.factory; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class Factory { static Properties props = new Properties(); static { try { FileInputStream fis = new FileInputStream("./src/main/resources/dataBase.properties"); props.load(fis); Class.forName(props.getProperty("driver")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection addConnection() throws SQLException { String url = props.getProperty("url"); String username = props.getProperty("username"); String password = props.getProperty("password"); Connection con = DriverManager.getConnection(url,username,password); return con; } }
true
02925d01289781ad5057681bbddc648417341961
Java
Oaks907/bookspace
/LeetCode/src/S901_S1000/S988_SmallestStringStartingFromLeaf.java
UTF-8
1,885
3.265625
3
[]
no_license
package S901_S1000; import model.TreeNode; import org.junit.Assert; import org.junit.Test; import javax.swing.*; import java.util.Stack; import java.util.stream.Stream; /** * https://leetcode.com/problems/smallest-string-starting-from-leaf/ * Create by haifei on 16/9/2019 8:05 AM. */ public class S988_SmallestStringStartingFromLeaf { public static String ans = null; public String smallestFromLeaf(TreeNode root) { ans = "zzzzzzzzzz"; smallest(root, ""); return ans; } private void smallest(TreeNode node, String str) { if (null == node) { return; } str = (char) ('a' + node.val) + str; if (node.left == null && node.right == null) { if (str.compareTo(ans) < 0) { ans = str; } return; } smallest(node.left, str); smallest(node.right, str); } @Test public void test() { TreeNode node0 = new TreeNode(0); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); TreeNode node3_1 = new TreeNode(3); TreeNode node4_1 = new TreeNode(4); node0.left = node1; node0.right = node2; node1.left = node3; node1.right = node4; node2.left = node3_1; node2.right = node4_1; String result = smallestFromLeaf(node0); Assert.assertEquals("dba", result); } @Test public void test1() { TreeNode node0 = new TreeNode(0); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node0_1 = new TreeNode(0); TreeNode node1_1 = new TreeNode(1); TreeNode node2_1 = new TreeNode(2); node2.left = node2_1; node2.right = node1; node2_1.right = node1_1; node1_1.left = node0; node1.left = node0_1; String result = smallestFromLeaf(node2); Assert.assertEquals("abc", result); } }
true
47838956cd69bc74f8267795f68c888e307fefc5
Java
m1-bioinfo-amu-01/ProjetFinalFormation
/src/main/java/projetFinal/dao/DaoClientJpaImpl.java
UTF-8
2,665
2.53125
3
[]
no_license
package projetFinal.dao; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.TypedQuery; import projetFinal.Context; import projetFinal.entity.Client; public class DaoClientJpaImpl implements DaoClient { @Override public List<Client> findAll() { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); TypedQuery<Client> query = em.createQuery("from Client o", Client.class); List<Client> list = query.getResultList(); em.close(); return list; } @Override public Client findByKey(Long key) { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); Client obj = em.find(Client.class, key); em.close(); return obj; } @Override public void insert(Client obj) { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(obj); tx.commit(); em.close(); } @Override public Client update(Client obj) { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); obj = em.merge(obj); tx.commit(); em.close(); return obj; } @Override public void delete(Client obj) { deleteByKey(obj.getId()); } @Override public void deleteByKey(Long key) { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); Client objManaged = em.find(Client.class, key); objManaged.getCommandes().forEach(commande -> { commande.setClient(null); em.merge(commande); }); em.remove(objManaged); tx.commit(); em.close(); } public Client findByKeyWithCommandes(Long key) { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); TypedQuery<Client> query = em.createQuery("select c from Client c left join fetch c.commandes where c.id=:key", Client.class); query.setParameter("key", key); Client client = query.getSingleResult(); em.close(); return client; } public List<Client> findAllWithCommandes() { EntityManager em = Context.getInstance().getEntityManagerFactory().createEntityManager(); TypedQuery<Client> query = em.createQuery("select distinct c from Client c left join fetch c.commandes", Client.class); List<Client> clients = query.getResultList(); em.close(); return clients; } // 2 olivier gozlan 1 =>Client(Commandes) // 2 olivier gozlan 2 =>Client // 3 Mathieu 3 =>Client // 4 Louis ... =>Client }
true
58e0ff6c6720504f3564adf0af4d3617190f3df9
Java
wanjinyan/wanjy
/src/main/java/com/wanjy/common/service/impl/ShopCarServiceImpl.java
UTF-8
499
1.554688
2
[]
no_license
package com.wanjy.common.service.impl; import com.wanjy.common.entity.ShopCar; import com.wanjy.common.mapper.ShopCarMapper; import com.wanjy.common.service.ShopCarService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 购物车 服务实现类 * </p> * * @author wanjy * @since 2020-01-12 */ @Service public class ShopCarServiceImpl extends ServiceImpl<ShopCarMapper, ShopCar> implements ShopCarService { }
true
da2a8b5a56699d2969e5fbc5ba1b5d7e858358e8
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/guardianproject_Gibberbot/src/info/guardianproject/otr/app/im/plugin/ImPluginInfo.java
UTF-8
1,592
1.710938
2
[]
no_license
// isComment package info.guardianproject.otr.app.im.plugin; import android.os.Parcel; import android.os.Parcelable; /** * isComment */ public class isClassOrIsInterface implements Parcelable { /** * isComment */ public String isVariable; /** * isComment */ public String isVariable; /** * isComment */ public String isVariable; /** * isComment */ public String isVariable; public isConstructor(String isParameter, String isParameter, String isParameter, String isParameter) { isNameExpr = isNameExpr; isNameExpr = isNameExpr; isNameExpr = isNameExpr; isNameExpr = isNameExpr; } public isConstructor(Parcel isParameter) { isNameExpr = isNameExpr.isMethod(); isNameExpr = isNameExpr.isMethod(); isNameExpr = isNameExpr.isMethod(); isNameExpr = isNameExpr.isMethod(); } public int isMethod() { return isIntegerConstant; } public void isMethod(Parcel isParameter, int isParameter) { isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr); isNameExpr.isMethod(isNameExpr); } public static final Parcelable.Creator<ImPluginInfo> isVariable = new Parcelable.Creator<ImPluginInfo>() { public ImPluginInfo isMethod(Parcel isParameter) { return new ImPluginInfo(isNameExpr); } public ImPluginInfo[] isMethod(int isParameter) { return new ImPluginInfo[isNameExpr]; } }; }
true
a4f7dc02df3814810263652e012d67d273a7e87e
Java
ankitmodi/My-Programming-Pearls
/WorksApp2_ImmutableQueue.java
UTF-8
3,699
3.71875
4
[]
no_license
package jp.co.worksap.global; import java.util.NoSuchElementException; public class WorksApp2_ImmutableQueue<E> { //Helper class : Implementing Immutable Queue using two stacks private static class Stack<E> { private E top; //top element private Stack<E> bottom; //Elements other than top are in a stack called private int size; //keeps count of size of the stack public Stack() //default constructor { this.top =null; this.bottom = null; this.size = 0; } private Stack(Stack<E> stack, E e) //private constructor { this.top = e; this.bottom = stack; this.size = stack.size + 1; } public boolean isEmpty() { return this.getSize() == 0; } public int getSize() { return size; } //returns a new stack with top as the element e and bottom as this stack public Stack<E> push(E e) { return new Stack(this, e); } /*public Stack pop() { return new Stack(this.bottom.bottom, this.bottom.top); }*/ //returns the a stack which is reverse of this stack public Stack reverse() { Stack<E> reverse = new Stack<E>(); Stack straight = this; while(!straight.isEmpty()) { reverse = reverse.push((E) straight.top); straight = straight.bottom; } return reverse; } } //two stacks used in Immutable Queue implementation private Stack<E> stackMain; //elements pushed onto new version of this to protect immutability private Stack<E> stackSpare; //elements popped from new version of this to protect immutability //default constructor public ImmutableQueue() { this.stackMain = new Stack(); this.stackSpare = new Stack(); } //private constructor private ImmutableQueue(Stack<E> main, Stack<E> spare) { this.stackMain = main; this.stackSpare = spare; } //returns a new immutable queue by taking MODIfied version of this.stackMain public ImmutableQueue<E> enqueue(E e) { if(e == null) { throw new IllegalArgumentException(); } return new ImmutableQueue(this.stackMain.push(e), this.stackSpare); } //returns a new immutable queue public ImmutableQueue<E> dequeue() { if(this.isEmpty()) { throw new NoSuchElementException(); } //if stackSpare is empty then pour all its elements onto stackSpare and make an empty StackMain. if(this.stackSpare.isEmpty()) { return new ImmutableQueue(new Stack(), this.stackMain.reverse().bottom); } //else simply dequeue from a new version of stackSpare else { return new ImmutableQueue(this.stackMain, this.stackSpare.bottom); } } //looks on the top element of stackSpare public E peek() { if(this.isEmpty()) { throw new NoSuchElementException(); } //if stackSpare is empty then pour all of stackMain onto stackSpare if(this.stackSpare.isEmpty()) { this.stackSpare = this.stackMain.reverse(); this.stackMain = new Stack<E>(); } return this.stackSpare.top; } public int Size() { return this.stackMain.size + this.stackSpare.size; } public boolean isEmpty() { return this.Size()==0; } //methods to test the correctness of implementation /* public void see() { System.out.println("is the queue Empty? " + this.isEmpty() + "\t Size is: " + this.Size()); if(!this.isEmpty()) { System.out.println("Peek: " + this.peek()); } } public static void main(String[] args) { ImmutableQueue q = new ImmutableQueue(); q.see(); ImmutableQueue q2 = q.enqueue(10); q2.see(); q.see(); ImmutableQueue q3 = q2.enqueue(20); q3.see(); q2.see(); q.see(); ImmutableQueue q4 = q3.dequeue(); q4 = q4.dequeue(); q4.see(); } */ }
true
cedb946f96f2a1ed14e087fbb54124c87abff7ef
Java
theF4b1/InformatikChat
/InformatikChat/src/com/thef4b1/informatikchat/LoginActivity.java
UTF-8
3,123
2.3125
2
[]
no_license
package com.thef4b1.informatikchat; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import android.support.v4.app.NavUtils; @SuppressLint("NewApi") public class LoginActivity extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; SharedPreferences loginInfos; EditText editTextUsername; EditText editTextPassword; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextPassword = (EditText) findViewById(R.id.editTextPassword); loginInfos = getSharedPreferences(PREFS_NAME, 0); editTextUsername.setText(loginInfos.getString("username", "")); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public void login(View view){ if(editTextUsername.length()==0 || editTextPassword.length()==0){ int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(getBaseContext(), R.string.toast_nousername, duration); toast.show(); } else { String username = editTextUsername.getText().toString(); String password = editTextPassword.getText().toString(); SharedPreferences.Editor editor = loginInfos.edit(); editor.putString("username", username); editor.putString("password", password); editor.putBoolean("register?", false); editor.commit(); Intent intent = new Intent(this, ChatClientMessageActivity.class); startActivity(intent); } } public void register(View view){ if(editTextUsername.length()==0 || editTextPassword.length()==0){ int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(getBaseContext(), R.string.toast_nousername, duration); toast.show(); } else { String username = editTextUsername.getText().toString(); String password = editTextPassword.getText().toString(); SharedPreferences.Editor editor = loginInfos.edit(); editor.putString("username", username); editor.putString("password", password); editor.putBoolean("register?", true); editor.commit(); Intent intent = new Intent(this, ChatClientMessageActivity.class); startActivity(intent); } } }
true
ad2658490bc7c09f07b77757331487f831547cc2
Java
RobbDora/online-shop
/src/main/java/ro/msg/learning/strategies/types/StrategyType.java
UTF-8
124
1.820313
2
[]
no_license
package ro.msg.learning.strategies.types; public enum StrategyType { SINGLE, ABUNDANT, GREEDY, PROXIMITY }
true
39b147a2d23f1f5fe6f5137211eda36351ea4919
Java
well-behaved/xuexiong_test
/rabbitmqdemo/src/main/java/com/xue/demo/rabbit/demo1/Recv.java
UTF-8
1,193
2.46875
2
[]
no_license
package com.xue.demo.rabbit.demo1; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.AMQP; import com.xue.demo.common.MyContans; public class Recv { public static void main(String[] argv) throws Exception { ConnectionFactory factory = new ConnectionFactory(); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(MyContans.QUEUE_NAME1, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel) { @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [x] Received '" + message + "'"); } }; channel.basicConsume(MyContans.QUEUE_NAME1, true, consumer); } }
true
cc1f3ae1a19baacc8f903700b0559430210f9367
Java
uib-behar/FussballLiga
/Fussball Liga1/sourceCodes/Spieltag.java
UTF-8
201
2.40625
2
[]
no_license
import java.util.ArrayList; public class Spieltag { ArrayList<Spiel> arrSpiele = new ArrayList<>(); public Spieltag() { } public void spielSpeichern(Spiel s) { arrSpiele.add(s); } }
true
7e0e0eb1daa8cd6d7653f733fbf39d8d31fae7cb
Java
baspiege/ezsched
/src/sched/data/DeleteTask.java
UTF-8
5,027
2.375
2
[]
no_license
package sched.data; import java.util.List; import javax.jdo.PersistenceManager; import javax.jdo.Query; import javax.servlet.http.HttpServletRequest; import sched.data.model.ItemToDelete; import sched.data.model.Role; import sched.data.model.ShiftTemplate; import sched.data.model.Store; import sched.data.model.User; import sched.data.model.UserShift; import sched.data.model.UserShiftRequestSwitch; import sched.utils.EditMessages; import sched.utils.RequestUtils; /** * Delete task. * * @author Brian Spiegel */ public class DeleteTask { /** * Delete task. * * @param aRequest The request * * @since 1.0 */ public void execute(HttpServletRequest aRequest) { PersistenceManager pm=null; Query query=null; try { pm=PMF.get().getPersistenceManager(); query = pm.newQuery(ItemToDelete.class); // Delete by type List<ItemToDelete> results = (List<ItemToDelete>) query.execute(); for (ItemToDelete itemToDelete : results) { int type=itemToDelete.getTypeToDelete(); long storeId=itemToDelete.getStoreId(); if (type==ItemToDelete.STORE) { // Roles query = pm.newQuery(Role.class); query.setFilter("(storeId == storeIdParam)"); query.declareParameters("long storeIdParam"); query.deletePersistentAll(storeId); // Users query = pm.newQuery(User.class); query.setFilter("(storeId == storeIdParam)"); query.declareParameters("long storeIdParam"); query.deletePersistentAll(storeId); // Shift templates query = pm.newQuery(ShiftTemplate.class); query.setFilter("(storeId == storeIdParam)"); query.declareParameters("long storeIdParam"); query.deletePersistentAll(storeId); // User shifts query = pm.newQuery(UserShift.class); query.setFilter("(storeId == storeIdParam)"); query.declareParameters("long storeIdParam"); query.deletePersistentAll(storeId); // User shifts switch request query = pm.newQuery(UserShiftRequestSwitch.class); query.setFilter("(storeId == storeIdParam)"); query.declareParameters("long storeIdParam"); query.deletePersistentAll(storeId); // Store - Should be deleted but just in case. query = pm.newQuery(Store.class); query.setFilter("(key == storeIdParam)"); query.declareParameters("long storeIdParam"); query.deletePersistentAll(storeId); } else if (type==ItemToDelete.ROLE) { // User shifts of this role query = pm.newQuery(UserShift.class); query.setFilter("(storeId == storeIdParam) && (roleId == roleIdParam)"); query.declareParameters("long storeIdParam, long roleIdParam"); query.deletePersistentAll(storeId, itemToDelete.getIdToDelete()); } else if (type==ItemToDelete.USER) { // User shifts of this user query = pm.newQuery(UserShift.class); query.setFilter("(storeId == storeIdParam) && (userId == userIdParam)"); query.declareParameters("long storeIdParam, long userIdParam"); query.deletePersistentAll(storeId, itemToDelete.getIdToDelete()); } else if (type==ItemToDelete.SHIFT_TEMPLATE) { // User shifts of this shift template query = pm.newQuery(UserShift.class); query.setFilter("(storeId == storeIdParam) && (shiftTemplateId == shiftTemplateIdParam)"); query.declareParameters("long storeIdParam, long shiftTemplateIdParam"); query.deletePersistentAll(storeId, itemToDelete.getIdToDelete()); } // Delete the marker itself pm.deletePersistent(itemToDelete); } } catch (Exception e) { System.err.println(this.getClass().getName() + ": " + e); e.printStackTrace(); RequestUtils.addEditUsingKey(aRequest,EditMessages.ERROR_PROCESSING_REQUEST); } finally { if (pm!=null) { pm.close(); } } } }
true
ae61e37690fa10f9f18b55fc138fe788e4ed3d27
Java
ali4heydari/TeamWorkChallenge
/src/main/java/models/Army.java
UTF-8
119
1.601563
2
[]
no_license
package models; import interfaces.Upgradable; public abstract class Army extends Phenom implements Upgradable { }
true
646c0e8b3ea917e4e60ee5600956d17b7786b44a
Java
iric-irri/portal
/chado-pg-orm/src/org/irri/iric/chado/so/ThrTrnaPrimaryTranscript.java
UTF-8
537
1.742188
2
[]
no_license
package org.irri.iric.chado.so; // Generated 05 26, 14 1:32:25 PM by Hibernate Tools 3.4.0.CR1 /** * ThrTrnaPrimaryTranscript generated by hbm2java */ public class ThrTrnaPrimaryTranscript implements java.io.Serializable { private ThrTrnaPrimaryTranscriptId id; public ThrTrnaPrimaryTranscript() { } public ThrTrnaPrimaryTranscript(ThrTrnaPrimaryTranscriptId id) { this.id = id; } public ThrTrnaPrimaryTranscriptId getId() { return this.id; } public void setId(ThrTrnaPrimaryTranscriptId id) { this.id = id; } }
true
d3610dab0404f6a8284a38c74c44f03015ddcf62
Java
Imagination-Realm/PongGL
/src/ponggl/Paddle.java
UTF-8
3,833
2.515625
3
[]
no_license
package ponggl; import java.awt.Color; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import lib2d.GameObject; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.*; public class Paddle extends GameObject { private final int NR_VERTICES = 4; private final int VALUES_PER_VERTEX = 2; private final int VALUES_PER_COLOR = 4; private final byte[] indices = { 0, 1, 2, 2, 3, 0 }; private final Color color; private final int vertBufferId, colBufferId, vertArrayId, indicesBufferId; private final FloatBuffer vertBuffer; public Paddle(float x, float y, float width, float height) { super(x, y, width, height); color = Color.WHITE; vertBuffer = BufferUtils.createFloatBuffer(VALUES_PER_VERTEX * NR_VERTICES); vertBuffer.put(new float[] { area.x, area.y, area.x, area.y+area.height, area.x+area.width, area.y+area.height, area.x+area.width, area.y }); vertBuffer.flip(); FloatBuffer colBuffer = BufferUtils.createFloatBuffer(VALUES_PER_COLOR * NR_VERTICES); for(int i=0; i<NR_VERTICES; i++) { colBuffer.put(color.getComponents(null)); } colBuffer.flip(); ByteBuffer indicesBuffer = BufferUtils.createByteBuffer(indices.length); indicesBuffer.put(indices); indicesBuffer.flip(); vertArrayId = GL30.glGenVertexArrays(); GL30.glBindVertexArray(vertArrayId); vertBufferId = GL15.glGenBuffers(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertBufferId); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertBuffer, GL15.GL_STATIC_DRAW); GL20.glVertexAttribPointer(0, VALUES_PER_VERTEX, GL11.GL_FLOAT, false, 0, 0); colBufferId = GL15.glGenBuffers(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, colBufferId); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, colBuffer, GL15.GL_STATIC_DRAW); GL20.glVertexAttribPointer(1, VALUES_PER_COLOR, GL11.GL_FLOAT, false, 0, 0); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL30.glBindVertexArray(0); indicesBufferId = GL15.glGenBuffers(); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indicesBufferId); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL15.GL_STATIC_DRAW); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0); } public void update() { vertBuffer.rewind(); vertBuffer.put(new float[] { area.x, area.y, area.x, area.y+area.height, area.x+area.width, area.y+area.height, area.x+area.width, area.y }); vertBuffer.flip(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vertBufferId); GL15.glBufferSubData(GL15.GL_ARRAY_BUFFER, 0, vertBuffer); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } @Override public void draw() { GL30.glBindVertexArray(vertArrayId); GL20.glEnableVertexAttribArray(0); GL20.glEnableVertexAttribArray(1); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, indicesBufferId); GL11.glDrawElements(GL11.GL_TRIANGLES, indices.length, GL11.GL_UNSIGNED_BYTE, 0); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, 0); GL20.glDisableVertexAttribArray(0); GL20.glDisableVertexAttribArray(1); GL30.glBindVertexArray(0); } @Override public void think() {} public void setLocation(float x, float y) { super.setLocation(x, y); update(); } @Override public void onRemove() { GL15.glDeleteBuffers(vertBufferId); GL15.glDeleteBuffers(colBufferId); GL15.glDeleteBuffers(indicesBufferId); GL30.glDeleteVertexArrays(vertArrayId); } }
true
67df8448c723ccd0f1546d6303c59f2c6f4cb057
Java
GellioGao/MobileDevelopmentAssignment
/Java/app/src/main/java/com/gao/yingjian/mobiledevelopmentassignmentone/Views/HomeNavigationDrawerActivity.java
UTF-8
6,841
1.867188
2
[ "MIT" ]
permissive
package com.gao.yingjian.mobiledevelopmentassignmentone.Views; import android.content.Intent; import android.os.Bundle; import com.gao.yingjian.mobiledevelopmentassignmentone.Adapters.MainScreenAdapter; import com.gao.yingjian.mobiledevelopmentassignmentone.DAOs.LogInfo; import com.gao.yingjian.mobiledevelopmentassignmentone.Models.MainScreen; import com.gao.yingjian.mobiledevelopmentassignmentone.R; import com.google.android.material.bottomnavigation.BottomNavigationView; import androidx.annotation.IdRes; import androidx.core.view.GravityCompat; import androidx.appcompat.app.ActionBarDrawerToggle; import android.view.MenuItem; import com.google.android.material.navigation.NavigationView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.widget.Toolbar; import androidx.viewpager.widget.ViewPager; import android.view.Menu; import org.litepal.LitePal; import java.util.ArrayList; public class HomeNavigationDrawerActivity extends ActivityBase implements NavigationView.OnNavigationItemSelectedListener, BottomNavigationView.OnNavigationItemSelectedListener { public static final String INTENT_EXTRA_USER ="user"; private static final String TAG = "HomeNavigationDrawerActivity"; private BottomNavigationView bottomNavigationView; private ViewPager viewPagerNavigation; private MainScreenAdapter mainScreenAdapter; private String username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home_navigation_drawer); viewPagerNavigation = findViewById(R.id.viewPagerNavigation); bottomNavigationView = findViewById(R.id.bottomNavigationView); Toolbar toolbar = findViewById(R.id.toolbar); ArrayList<MainScreen> mainScreens = this.getMainScrees(); MainScreen defaultScreen = null; defaultScreen = getMainScreen(mainScreens, R.id.homeMenuItem); mainScreenAdapter = new MainScreenAdapter(getSupportFragmentManager(), 1); mainScreenAdapter.setItems(mainScreens); bottomNavigationView.setSelectedItemId(defaultScreen.getMenuItemId()); bottomNavigationView.setOnNavigationItemSelectedListener(this); viewPagerNavigation.setAdapter(mainScreenAdapter); viewPagerNavigation.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { MainScreen selectedScreen = mainScreenAdapter.getItems().get(position); selectBottomNavigationViewMenuItem(selectedScreen.getMenuItemId()); } @Override public void onPageScrollStateChanged(int state) { } }); scrollToScreen(defaultScreen); setSupportActionBar(toolbar); DrawerLayout drawer = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView.setNavigationItemSelectedListener(this); username = getIntent().getStringExtra(INTENT_EXTRA_USER); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { this.finishAffinity(); //System.exit(0); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_actions, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.settingsMenuItem) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); MainScreen it = getMainScreen(mainScreenAdapter.getItems(), id); if(it != null) { scrollToScreen(it); return true; } if(id == R.id.clearLoggedInUsers){ LitePal.deleteAll(LogInfo.class); } if(id == R.id.logoutMenuItem){ finish(); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } private ArrayList<MainScreen> getMainScrees(){ ArrayList<MainScreen> mainScreens = new ArrayList<>(); mainScreens.add(new MainScreen(R.id.recentMenuItem, R.drawable.ic_recent, R.string.home_bottom_navigation_recent_title_name, RecentFragment.newInstance())); mainScreens.add(new MainScreen(R.id.homeMenuItem, R.drawable.ic_home, R.string.home_bottom_navigation_home_title_name, HomeFragment.newInstance())); mainScreens.add(new MainScreen(R.id.notificationMenuItem, R.drawable.ic_notifications, R.string.home_bottom_navigation_notification_title_name, NotificationFragment.newInstance())); return mainScreens; } private void scrollToScreen(MainScreen mainScreen) { int screenPosition = mainScreenAdapter.getItems().indexOf(mainScreen); if (screenPosition != viewPagerNavigation.getCurrentItem()) { viewPagerNavigation.setCurrentItem(screenPosition); } } private void selectBottomNavigationViewMenuItem(@IdRes int menuItemId) { bottomNavigationView.setOnNavigationItemSelectedListener(null); bottomNavigationView.setSelectedItemId(menuItemId); bottomNavigationView.setOnNavigationItemSelectedListener(this); } private MainScreen getMainScreen(ArrayList<MainScreen> mainScreens, @IdRes int menuItemId) { MainScreen defaultScreen = null; for( MainScreen screen : mainScreens){ if(screen.getMenuItemId() == menuItemId){ defaultScreen = screen; } } return defaultScreen; } }
true
27e3e15a638c2a4c8254f4867f808f5be4cbf180
Java
yyan1119/dzf_channel
/src/main/java/com/dzf/service/channel/impl/ChnPayConfServiceImpl.java
UTF-8
21,177
1.601563
2
[]
no_license
package com.dzf.service.channel.impl; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dzf.dao.bs.SingleObjectBO; import com.dzf.dao.jdbc.framework.SQLParameter; import com.dzf.dao.jdbc.framework.processor.BeanListProcessor; import com.dzf.dao.multbs.MultBodyObjectBO; import com.dzf.model.channel.ChnBalanceVO; import com.dzf.model.channel.ChnDetailVO; import com.dzf.model.channel.ChnPayBillVO; import com.dzf.model.pub.IStatusConstant; import com.dzf.model.pub.QryParamVO; import com.dzf.model.pub.QrySqlSpmVO; import com.dzf.model.sys.sys_power.CorpVO; import com.dzf.model.sys.sys_power.UserVO; import com.dzf.pub.BusinessException; import com.dzf.pub.DZFWarpException; import com.dzf.pub.QueryDeCodeUtils; import com.dzf.pub.StringUtil; import com.dzf.pub.WiseRunException; import com.dzf.pub.cache.CorpCache; import com.dzf.pub.lang.DZFDate; import com.dzf.pub.lang.DZFDateTime; import com.dzf.pub.lang.DZFDouble; import com.dzf.pub.lock.LockUtil; import com.dzf.pub.util.SafeCompute; import com.dzf.pub.util.SqlUtil; import com.dzf.service.channel.IChnPayConfService; import com.dzf.service.pub.IPubService; import com.dzf.service.sys.sys_power.IUserService; @Service("chnpayconfser") public class ChnPayConfServiceImpl implements IChnPayConfService { @Autowired private MultBodyObjectBO multBodyObjectBO; @Autowired private SingleObjectBO singleObjectBO; @Autowired private IUserService userServiceImpl; @Autowired private IPubService pubService; @Override public Integer queryTotalRow(QryParamVO paramvo) throws DZFWarpException { QrySqlSpmVO sqpvo = getQrySqlSpm(paramvo); return multBodyObjectBO.queryDataTotal(ChnPayBillVO.class, sqpvo.getSql(), sqpvo.getSpm()); } @SuppressWarnings("unchecked") @Override public List<ChnPayBillVO> query(QryParamVO paramvo) throws DZFWarpException { QrySqlSpmVO sqpvo = getQrySqlSpm(paramvo); List<ChnPayBillVO> list = (List<ChnPayBillVO>) multBodyObjectBO.queryDataPage(ChnPayBillVO.class, sqpvo.getSql(), sqpvo.getSpm(), paramvo.getPage(), paramvo.getRows(), null); //查询该客户所在渠道大区: Map<Integer, String> areaMap = pubService.getAreaMap(paramvo.getAreaname(), IStatusConstant.IQUDAO); Map<String, UserVO> marmap = pubService.getManagerMap(IStatusConstant.IQUDAO);// 渠道经理 if (list != null && list.size() > 0) { CorpVO accvo = null; UserVO uservo = null; QueryDeCodeUtils.decKeyUtils(new String[] { "vconfirmname" }, list, 1); for (ChnPayBillVO vo : list) { accvo = CorpCache.getInstance().get(null, vo.getPk_corp()); uservo = marmap.get(vo.getPk_corp()); if (accvo != null) { vo.setCorpname(accvo.getUnitname()); vo.setVprovname(accvo.getCitycounty()); } if (uservo != null) { vo.setVmanagername(uservo.getUser_name());// 渠道经理 } if(areaMap.containsKey(vo.getVprovince())){ vo.setAreaname(areaMap.get(vo.getVprovince())); } } } return list; } /** * 获取查询条件 * * @param paramvo * @return */ private QrySqlSpmVO getQrySqlSpm(QryParamVO paramvo) { QrySqlSpmVO qryvo = new QrySqlSpmVO(); StringBuffer sql = new StringBuffer(); SQLParameter spm = new SQLParameter(); sql.append("SELECT t.pk_paybill, "); sql.append(" t.pk_corp, "); sql.append(" t.vbillcode, "); sql.append(" t.dpaydate, "); sql.append(" t.vhandleid, "); sql.append(" t.vconfirmid, "); sql.append(" t.dconfirmtime, "); sql.append(" t.vmemo, "); sql.append(" t.coperatorid, "); sql.append(" t.doperatedate, "); sql.append(" t.npaymny, "); sql.append(" t.ipaymode, "); sql.append(" t.ipaytype, "); sql.append(" t.vstatus, "); sql.append(" t.tstamp, "); sql.append(" t.docName, "); sql.append(" t.docOwner, "); sql.append(" t.docTime, "); sql.append(" t.vfilepath, "); sql.append(" t.vbankname, "); sql.append(" t.vbankcode, "); sql.append(" t.vreason, "); sql.append(" t.submitime, "); sql.append(" t.submitid, "); sql.append(" t.systype, "); sql.append(" t.vapproveid, "); sql.append(" t.dapprovedate, "); sql.append(" t.dapprovetime, "); sql.append(" t.irejectype, "); sql.append(" t.ichargetype, "); sql.append(" us.user_name as vconfirmname, "); sql.append(" account.vprovince "); sql.append(" FROM cn_paybill t "); sql.append(" LEFT JOIN sm_user us ON us.cuserid = t.vconfirmid"); sql.append(" LEFT JOIN bd_account account ON t.pk_corp = account.pk_corp "); sql.append(" WHERE nvl(t.dr,0) = 0 "); sql.append(" AND nvl(account.dr, 0) = 0 "); sql.append(" AND account.ischannel = 'Y' "); sql.append(" AND account.isaccountcorp = 'Y' "); if (paramvo.getQrytype() != null && paramvo.getQrytype() != -1) {// 查询状态 sql.append(" AND t.vstatus = ? "); spm.addParam(paramvo.getQrytype()); } else { sql.append(" AND t.vstatus in ( ?, ?) "); spm.addParam(IStatusConstant.IPAYSTATUS_3); spm.addParam(IStatusConstant.IPAYSTATUS_5); } if (paramvo.getIpaytype() != null && paramvo.getIpaytype() != -1) { sql.append(" AND t.ipaytype = ? "); spm.addParam(paramvo.getIpaytype()); } if (paramvo.getIpaymode() != null && paramvo.getIpaymode() != -1) { sql.append(" AND t.ipaymode = ? "); spm.addParam(paramvo.getIpaymode()); } if (paramvo.getSeletype() != null && paramvo.getSeletype() != -1) { sql.append(" AND t.ichargetype = ? "); spm.addParam(paramvo.getSeletype()); } if (paramvo.getBegdate() != null && paramvo.getEnddate() != null) { sql.append(" AND (t.dpaydate >= ? AND t.dpaydate <= ? ) "); spm.addParam(paramvo.getBegdate()); spm.addParam(paramvo.getEnddate()); } //加盟商过滤: if (!StringUtil.isEmpty(paramvo.getPk_corp())) { String[] strs = paramvo.getPk_corp().split(","); String inSql = SqlUtil.buildSqlConditionForIn(strs); sql.append(" AND t.pk_corp in (").append(inSql).append(")"); }else{ if (paramvo.getCorptype() != null && paramvo.getCorptype() != -1) { sql.append(" AND account.channeltype = ? "); spm.addParam(paramvo.getCorptype()); } else { sql.append(" AND account.channeltype != 9 "); } } if (!StringUtil.isEmpty(paramvo.getPk_bill())) { sql.append(" AND t.pk_paybill = ? "); spm.addParam(paramvo.getPk_bill()); } sql.append(" order by t.dpaydate desc"); qryvo.setSql(sql.toString()); qryvo.setSpm(spm); return qryvo; } @Override public ChnPayBillVO updateOperate(ChnPayBillVO billvo, Integer opertype, String cuserid, String vreason) throws DZFWarpException { checkBillStatus(billvo); return updateData(billvo, opertype, cuserid, vreason); } /** * 校验数据状态 * * @param billVOs */ @Override public void checkBillStatus(ChnPayBillVO billvo) throws DZFWarpException { ChnPayBillVO oldvo = (ChnPayBillVO) singleObjectBO.queryByPrimaryKey(ChnPayBillVO.class, billvo.getPk_paybill()); if (oldvo != null) { if (oldvo.getDr() != null && oldvo.getDr() == 1) { throw new BusinessException("单据号" + billvo.getVbillcode() + "数据错误"); } else { if (oldvo.getTstamp().compareTo(billvo.getTstamp()) != 0) { throw new BusinessException("单据号" + billvo.getVbillcode() + "发生变化"); } } } else { billvo.setVerrmsg("单据号" + billvo.getVbillcode() + "数据错误"); throw new BusinessException("单据号" + billvo.getVbillcode() + "数据错误"); } } /** * 收款确认、确认驳回、取消确认 * * @param billvo * @param opertype * @param cuserid * @return */ private ChnPayBillVO updateData(ChnPayBillVO billvo, Integer opertype, String cuserid, String vreason) { if (StringUtil.isEmpty(billvo.getTableName()) || StringUtil.isEmpty(billvo.getPk_paybill())) { throw new BusinessException("单据号" + billvo.getVbillcode() + "数据错误"); } String uuid = UUID.randomUUID().toString(); try { checkData(billvo); if (opertype == IStatusConstant.ICHNOPRATETYPE_3) {// 收款确认 billvo = updateConfrimData(billvo, opertype, cuserid); } else if (opertype == IStatusConstant.ICHNOPRATETYPE_4) {// 确认驳回 billvo = updateRejectData(billvo, vreason, cuserid); } else if (opertype == IStatusConstant.ICHNOPRATETYPE_5) {// 取消确认 billvo = updateCancelData(billvo, opertype, cuserid); } } catch (Exception e) { if (e instanceof BusinessException) throw new BusinessException(e.getMessage()); else throw new WiseRunException(e); } finally { LockUtil.getInstance().unLock_Key(billvo.getTableName(), billvo.getPk_paybill(), uuid); } return billvo; } /** * 操作数据前校验 * * @param billvo * @throws DZFWarpException */ private void checkData(ChnPayBillVO billvo) throws DZFWarpException { ChnPayBillVO oldvo = (ChnPayBillVO) singleObjectBO.queryByPrimaryKey(ChnPayBillVO.class, billvo.getPk_paybill()); if (oldvo == null || (oldvo != null && oldvo.getDr() != null && oldvo.getDr() == 1)) { throw new BusinessException("界面数据发生变化,请刷新后再次尝试"); } if (billvo.getTstamp().compareTo(oldvo.getTstamp()) != 0) { throw new BusinessException("界面数据发生变化,请刷新后再次尝试"); } } /** * 收款确认 * * @param billvo * @param opertype * @param cuserid * @return * @throws DZFWarpException */ private ChnPayBillVO updateConfrimData(ChnPayBillVO billvo, Integer opertype, String cuserid) throws DZFWarpException { if (billvo.getVstatus() != null && billvo.getVstatus() != IStatusConstant.IPAYSTATUS_5) { throw new BusinessException("单据号" + billvo.getVbillcode() + "状态不为【待确认】"); } //更新余额及明细表 updateBalanceDet(billvo, cuserid); //更新付款单信息 updatePayBill(billvo, cuserid); return billvo; } /** * 更新付款单信息 * @param billvo * @param cuserid * @throws DZFWarpException */ private void updatePayBill(ChnPayBillVO billvo, String cuserid) throws DZFWarpException { List<String> upstr = new ArrayList<String>(); billvo.setVstatus(IStatusConstant.IPAYSTATUS_3);// 付款单状态 billvo.setVconfirmid(cuserid);// 确认人 billvo.setDconfirmtime(new DZFDateTime());// 确认时间 billvo.setTstamp(new DZFDateTime());// 操作时间戳 upstr.add("vstatus"); upstr.add("vconfirmid"); upstr.add("dconfirmtime"); upstr.add("tstamp"); upstr.add("ichargetype"); if (billvo.getIrejectype() != null && billvo.getIrejectype() == 2) {// 确认驳回 billvo.setIrejectype(null);// 清空驳回类型 billvo.setVreason(null);// 清空驳回原因 upstr.add("irejectype"); upstr.add("vreason"); } setChargeType(billvo); singleObjectBO.update(billvo, upstr.toArray(new String[0])); UserVO uservo = userServiceImpl.queryUserJmVOByID(billvo.getVconfirmid()); if (uservo != null) { billvo.setVconfirmname(uservo.getUser_name()); } } /** * 更新付款余额及明细表 * @param billvo * @param cuserid * @throws DZFWarpException */ private void updateBalanceDet(ChnPayBillVO billvo, String cuserid) throws DZFWarpException { ChnDetailVO detvo = new ChnDetailVO(); detvo.setPk_corp(billvo.getPk_corp()); detvo.setNpaymny(billvo.getNpaymny()); detvo.setIpaytype(billvo.getIpaytype()); if (detvo.getIpaytype() != null) { switch (detvo.getIpaytype()) { case 1: detvo.setVmemo("保证金"); break; case 2: detvo.setVmemo("预付款"); break; } } detvo.setPk_bill(billvo.getPk_paybill()); detvo.setCoperatorid(cuserid); detvo.setDoperatedate(billvo.getDpaydate()); detvo.setDr(0); detvo.setIopertype(IStatusConstant.IDETAILTYPE_1); ChnBalanceVO balvo = null; String sql = " nvl(dr,0) = 0 and pk_corp = ? and ipaytype = ? "; SQLParameter spm = new SQLParameter(); spm.addParam(billvo.getPk_corp()); spm.addParam(billvo.getIpaytype()); ChnBalanceVO[] balVOs = (ChnBalanceVO[]) singleObjectBO.queryByCondition(ChnBalanceVO.class, sql, spm); if (balVOs != null && balVOs.length > 0) { String uid = UUID.randomUUID().toString(); try { LockUtil.getInstance().tryLockKey("cn_balance", billvo.getPk_corp() + "" + billvo.getIpaytype(), uid, 120); StringBuffer usql = new StringBuffer(); spm = new SQLParameter(); usql.append("UPDATE cn_balance l "); usql.append(" SET l.npaymny = nvl(l.npaymny,0) + ? "); spm.addParam(billvo.getNpaymny()); usql.append(" WHERE nvl(l.dr,0) = 0 AND l.ipaytype = ? "); spm.addParam(billvo.getIpaytype()); usql.append(" AND l.pk_corp = ? "); spm.addParam(billvo.getPk_corp()); int res = singleObjectBO.executeUpdate(usql.toString(), spm); if (res != 1) { throw new BusinessException("余额表金额更新错误"); } } catch (Exception e) { if (e instanceof BusinessException) throw new BusinessException(e.getMessage()); else throw new WiseRunException(e); } finally { LockUtil.getInstance().unLock_Key("cn_balance", billvo.getPk_corp() + "" + billvo.getIpaytype(), uid); } singleObjectBO.saveObject("000001", detvo); } else { balvo = new ChnBalanceVO(); balvo.setPk_corp(billvo.getPk_corp()); balvo.setNpaymny(billvo.getNpaymny()); balvo.setIpaytype(billvo.getIpaytype()); balvo.setVmemo(billvo.getVmemo()); balvo.setCoperatorid(cuserid); balvo.setDoperatedate(new DZFDate()); balvo.setDr(0); singleObjectBO.saveObject("000001", balvo); singleObjectBO.saveObject("000001", detvo); } } /** * 设置付款类型为预付款,是首次充值,还是后续充值 * * @param billvo */ private void setChargeType(ChnPayBillVO billvo) throws DZFWarpException { if (billvo.getIpaytype() == 2) { billvo.setIchargetype(1); SQLParameter sp = new SQLParameter(); sp.addParam(billvo.getPk_corp()); sp.addParam(IStatusConstant.IPAYTYPE_2); sp.addParam(IStatusConstant.IPAYSTATUS_3); StringBuffer sql = new StringBuffer(); sql.append(" select 1 from cn_paybill "); sql.append(" where nvl(dr, 0) = 0 and pk_corp = ? "); sql.append(" and ipaytype=? and vstatus=?"); boolean b = singleObjectBO.isExists(billvo.getPk_corp(), sql.toString(), sp); if (b) { billvo.setIchargetype(2); } } } /** * 判断是否可以取消,该预付款付款单 * * @param billvo */ @SuppressWarnings("unchecked") private void checkIsCancel(ChnPayBillVO billvo) throws DZFWarpException { if (billvo.getIpaytype() == 2) { SQLParameter sp = new SQLParameter(); sp.addParam(billvo.getPk_corp()); sp.addParam(IStatusConstant.IPAYTYPE_2); sp.addParam(IStatusConstant.IPAYSTATUS_3); sp.addParam(billvo.getDconfirmtime()); sp.addParam(billvo.getPk_paybill()); StringBuffer sql = new StringBuffer(); sql.append(" select vbillcode from cn_paybill "); sql.append(" where nvl(dr, 0) = 0 and pk_corp = ? "); sql.append(" and ipaytype=? and vstatus=? "); sql.append(" and dconfirmtime>? and pk_paybill!=? "); List<ChnPayBillVO> vos = (List<ChnPayBillVO>) singleObjectBO.executeQuery(sql.toString(), sp, new BeanListProcessor(ChnPayBillVO.class)); if (vos != null && vos.size() > 0) { throw new BusinessException("请先取消 " + vos.get(0).getVbillcode() + "付款单"); } } } /** * 取消确认 * * @param billvo * @param opertype * @param cuserid * @return * @throws DZFWarpException */ private ChnPayBillVO updateCancelData(ChnPayBillVO billvo, Integer opertype, String cuserid) throws DZFWarpException { if (billvo.getVstatus() != null && billvo.getVstatus() != IStatusConstant.IPAYSTATUS_3) { throw new BusinessException("单据号" + billvo.getVbillcode() + "状态不为【已确认】"); } checkIsCancel(billvo); ChnBalanceVO balvo = null; String sql = " nvl(dr,0) = 0 and pk_corp = ? and ipaytype = ? "; SQLParameter spm = new SQLParameter(); spm.addParam(billvo.getPk_corp()); spm.addParam(billvo.getIpaytype()); ChnBalanceVO[] balVOs = (ChnBalanceVO[]) singleObjectBO.queryByCondition(ChnBalanceVO.class, sql, spm); if (balVOs != null && balVOs.length > 0) { balvo = balVOs[0]; DZFDouble balance = SafeCompute.sub(balvo.getNpaymny(), balvo.getNusedmny()); if (balance.compareTo(billvo.getNpaymny()) < 0) { throw new BusinessException("单据号" + billvo.getVbillcode() + "余额不足"); } else { String uiid = UUID.randomUUID().toString(); String uid = UUID.randomUUID().toString(); try { LockUtil.getInstance().tryLockKey("cn_balance", billvo.getPk_corp() + "" + billvo.getIpaytype(), uiid, 120); LockUtil.getInstance().tryLockKey("cn_detail", billvo.getPk_paybill(), uid, 120); // 更新余额表: StringBuffer usql = new StringBuffer(); spm = new SQLParameter(); usql.append("UPDATE cn_balance l "); usql.append(" SET l.npaymny = nvl(l.npaymny,0) - ? "); spm.addParam(billvo.getNpaymny()); usql.append(" WHERE nvl(l.dr,0) = 0 AND l.ipaytype = ? "); spm.addParam(billvo.getIpaytype()); usql.append(" AND l.pk_corp = ? "); spm.addParam(billvo.getPk_corp()); int res = singleObjectBO.executeUpdate(usql.toString(), spm); if (res == 1) { sql = " delete from cn_detail where nvl(dr,0) = 0 and pk_bill = ? and pk_corp = ? "; spm = new SQLParameter(); spm.addParam(billvo.getPk_paybill()); spm.addParam(billvo.getPk_corp()); int rest = singleObjectBO.executeUpdate(sql, spm); if (rest != 1) { String unitname = ""; CorpVO corpvo = CorpCache.getInstance().get(null, billvo.getPk_corp()); if (corpvo != null) { unitname = corpvo.getUnitname(); } throw new BusinessException("客户:" + unitname + "余额明细表付款金额更新错误;"); } } else { String unitname = ""; CorpVO corpvo = CorpCache.getInstance().get(null, billvo.getPk_corp()); if (corpvo != null) { unitname = corpvo.getUnitname(); } throw new BusinessException("客户:" + unitname + "余额表付款金额更新错误;"); } } catch (Exception e) { if (e instanceof BusinessException) throw new BusinessException(e.getMessage()); else throw new WiseRunException(e); } finally { LockUtil.getInstance().unLock_Key("cn_balance", billvo.getPk_corp() + "" + billvo.getIpaytype(), uiid); LockUtil.getInstance().unLock_Key("cn_detail", billvo.getPk_paybill(), uid); } } } billvo.setVstatus(IStatusConstant.IPAYSTATUS_5);// 付款单状态 待确认 billvo.setVconfirmid(null);// 取消确认人 billvo.setDconfirmtime(null);// 取消确认时间 billvo.setIchargetype(null);// 付款单充值类型 billvo.setTstamp(new DZFDateTime());// 操作时间 singleObjectBO.update(billvo, new String[] { "vstatus", "vconfirmid", "dconfirmtime", "tstamp", "ichargetype" }); return billvo; } /** * 确认驳回 * * @param billvo * @param vreason * @param cuserid * @return * @throws DZFWarpException */ private ChnPayBillVO updateRejectData(ChnPayBillVO billvo, String vreason, String cuserid) throws DZFWarpException { if (billvo.getVstatus() != null && billvo.getVstatus() != IStatusConstant.IPAYSTATUS_5) { throw new BusinessException("单据号" + billvo.getVbillcode() + "状态不为【待确认】"); } billvo.setIrejectype(2);// 驳回类型:确认驳回 billvo.setVconfirmid(cuserid);// 确认-驳回人 billvo.setDconfirmtime(new DZFDateTime());// 确认驳回时间 billvo.setVreason(vreason); billvo.setVstatus(IStatusConstant.IPAYSTATUS_4);// 付款单状态 已驳回 billvo.setTstamp(new DZFDateTime());// 操作时间 String[] str = new String[] { "irejectype", "vconfirmid", "dconfirmtime", "vreason", "vstatus", "tstamp" }; singleObjectBO.update(billvo, str); UserVO uservo = userServiceImpl.queryUserJmVOByID(billvo.getVconfirmid()); if (uservo != null) { billvo.setVconfirmname(uservo.getUser_name()); } return billvo; } @Override public ChnPayBillVO queryByID(String cid) throws DZFWarpException { return (ChnPayBillVO) singleObjectBO.queryVOByID(cid, ChnPayBillVO.class); } }
true
51c3b357d171d1a387277e46d990e07f82f3a242
Java
jgarrealonso/spring-mvc-rest
/src/test/java/com/dioler/springmvcrest/services/CategoryServiceTest.java
UTF-8
1,874
2.375
2
[]
no_license
package com.dioler.springmvcrest.services; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import com.dioler.springmvcrest.api.v1.mapper.CategoryMapper; import com.dioler.springmvcrest.api.v1.model.CategoryDTO; import com.dioler.springmvcrest.domain.Category; import com.dioler.springmvcrest.repositories.CategoryRepository; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class CategoryServiceTest { public static final String NAME = "Fruits"; public static final long ID = 1L; @Mock CategoryRepository categoryRepository; @InjectMocks CategoryServiceImpl categoryService; @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); } @Test void getAllCategories() { //Given List<Category> categories = Arrays.asList(new Category(), new Category(), new Category()); when(categoryRepository.findAll()).thenReturn(categories); //When List<CategoryDTO> categoriesDTO = categoryService.getAllCategories(); //Then assertEquals(3, categoriesDTO.size()); } @Test void getCategoryByName() { Category category = new Category(); category.setName(NAME); category.setId(ID); //Given when(categoryRepository.findByName(anyString())).thenReturn(Optional.ofNullable(category)); //When CategoryDTO categoryDTO = categoryService.getCategoryByName(NAME).get(); //Then assertEquals(ID, categoryDTO.getId()); assertEquals(NAME, categoryDTO.getName()); } }
true
73aead8e73d54224c049eb4d795b89eb741a8003
Java
sripriyamaturi/projects-management-system
/insert.java
UTF-8
5,063
2.609375
3
[]
no_license
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.DriverManager; //import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.*; public class insert { JFrame frame = new JFrame("Insert"); JLabel heading = new JLabel("ADD A PROJECT"); JLabel Id = new JLabel("Enter id of student : "); JLabel pName = new JLabel("Enter project name :"); JLabel des = new JLabel("Description : "); JLabel dat = new JLabel("Date : "); JLabel course = new JLabel("Enter Course : "); JLabel code = new JLabel("Code(link) : "); JLabel score = new JLabel("Enter the score: "); JLabel go_to = new JLabel("GOTO"); JTextField tpId = new JTextField(); JTextField tpName = new JTextField(); JTextField tscore = new JTextField(); JTextField date = new JTextField(); JTextField tcourse = new JTextField(); JTextField tcode = new JTextField(); JTextField tDescription = new JTextField(); JTextArea resultText = new JTextArea(); JButton home = new JButton("Home"); JButton insert = new JButton("Submit"); JButton back = new JButton("Back"); Statement stmt; public void connDb() { try{ //Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:@218.248.0.7:1521:rdbms","it19737018","vasavi"); stmt = con.createStatement(); System.out.println("connection successful"); // con.close(); } catch(SQLException e){ System.out.println(e); } } public insert(String name){ connDb(); Color Blue = new Color(187, 255, 153); frame.getContentPane().setBackground(Blue); heading.setBounds(50, 50, 100, 20); Id.setBounds(50, 100, 130, 30); pName.setBounds(50, 150, 200, 30); tpId.setBounds(250, 100, 150, 30); tpName.setBounds(250, 150, 150, 30); des.setBounds(50, 200, 150, 30); tDescription.setBounds(250, 200, 150, 30); dat.setBounds(50, 250, 150, 30); date.setBounds(250, 250,150, 30); course.setBounds(50, 300, 150, 30); tcourse.setBounds(250, 300, 150, 30); code.setBounds(50, 350, 150, 30); tcode.setBounds(250, 350, 150, 30); score.setBounds(50, 400, 150, 30); tscore.setBounds(250, 400, 150, 30); resultText.setBounds(250, 450, 200, 150); insert.setBounds(50, 450, 100, 30); go_to.setBounds(50, 500, 100, 30); home.setBounds(50, 550, 100, 30); back.setBounds(50, 600, 100, 30); frame.add(heading); frame.add(Id); frame.add(pName); frame.add(tpId); frame.add(tpName); frame.add(dat); frame.add(date); frame.add(des); frame.add(tDescription); frame.add(course); frame.add(tcourse); frame.add(code); frame.add(tcode); frame.add(score); frame.add(tscore); frame.add(insert); frame.add(go_to); frame.add(home); frame.add(resultText); frame.add(back); frame.setLayout(null); frame.setVisible(true); frame.setBounds(10, 10, 500, 700); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); insert.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { try { String query= "INSERT INTO projects VALUES(" + tpId.getText() + ",'" + tpName.getText() + "','" + tDescription.getText() + "','" + date.getText() + "','" + tcourse.getText() + "','" + tcode.getText() + "'," + tscore.getText() +" )"; int i = stmt.executeUpdate(query); resultText.append("\nInserted " + i + " rows successfully"); //ResultSet rs = stmt.executeQuery(sql); //while(rs.next()){ // System.out.println(rs.getInt(1) + " " + rs.getString(2)); // } } catch(SQLException e){ System.out.println(e); } // frame.dispose(); // new customerLogin(); }}); home.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frame.dispose(); new Gui(); // new clickListener(); }}); back.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { frame.dispose(); new facultyopts(name); // new clickListener(); }}); } }
true
22d88be58c7fa11e57ecd252939db3b33d197e98
Java
zhangwei911/javaSocketServer
/src/main/java/viz/commonlib/socket/SocketApplication.java
UTF-8
530
1.945313
2
[]
no_license
package viz.commonlib.socket; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.io.IOException; @SpringBootApplication public class SocketApplication { public static void main(String[] args) throws IOException { ApplicationContext applicationContext = SpringApplication.run(SocketApplication.class, args); applicationContext.getBean(SocketServer.class).run(); } }
true
8763f5929e1f68ec83bd9e7b6fc07f24c0ac5d13
Java
seariver-org/helloopenshift
/src/main/java/org/seariver/helloopenshift/HelloController.java
UTF-8
702
2.234375
2
[]
no_license
package org.seariver.helloopenshift; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Value("${spring.application.name}") private String appName; @Value("${hello.message}") private String message; @GetMapping(value = "hello", produces = "application/json") public ResponseEntity hello() { String json = String.format("{\"hello\": \"%s\", \"appName\": \"%s\"}", message, appName); return ResponseEntity.ok().body(json); } }
true
1efbfa40b8f3042c0467921b0617a4dce00e9ca7
Java
mcenirm/isotc211-src
/net/opengis/gml/x32/impl/VerticalCSDocumentImpl.java
UTF-8
2,772
1.835938
2
[]
no_license
/* * An XML document type. * Localname: verticalCS * Namespace: http://www.opengis.net/gml/3.2 * Java type: net.opengis.gml.x32.VerticalCSDocument * * Automatically generated - do not modify. */ package net.opengis.gml.x32.impl; /** * A document containing one verticalCS(@http://www.opengis.net/gml/3.2) element. * * This is a complex type. */ public class VerticalCSDocumentImpl extends org.apache.xmlbeans.impl.values.XmlComplexContentImpl implements net.opengis.gml.x32.VerticalCSDocument { private static final long serialVersionUID = 1L; public VerticalCSDocumentImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName VERTICALCS$0 = new javax.xml.namespace.QName("http://www.opengis.net/gml/3.2", "verticalCS"); private static final org.apache.xmlbeans.QNameSet VERTICALCS$1 = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { new javax.xml.namespace.QName("http://www.opengis.net/gml/3.2", "verticalCS"), new javax.xml.namespace.QName("http://www.opengis.net/gml/3.2", "usesVerticalCS"), }); /** * Gets the "verticalCS" element */ public net.opengis.gml.x32.VerticalCSPropertyType getVerticalCS() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.x32.VerticalCSPropertyType target = null; target = (net.opengis.gml.x32.VerticalCSPropertyType)get_store().find_element_user(VERTICALCS$1, 0); if (target == null) { return null; } return target; } } /** * Sets the "verticalCS" element */ public void setVerticalCS(net.opengis.gml.x32.VerticalCSPropertyType verticalCS) { synchronized (monitor()) { check_orphaned(); net.opengis.gml.x32.VerticalCSPropertyType target = null; target = (net.opengis.gml.x32.VerticalCSPropertyType)get_store().find_element_user(VERTICALCS$1, 0); if (target == null) { target = (net.opengis.gml.x32.VerticalCSPropertyType)get_store().add_element_user(VERTICALCS$0); } target.set(verticalCS); } } /** * Appends and returns a new empty "verticalCS" element */ public net.opengis.gml.x32.VerticalCSPropertyType addNewVerticalCS() { synchronized (monitor()) { check_orphaned(); net.opengis.gml.x32.VerticalCSPropertyType target = null; target = (net.opengis.gml.x32.VerticalCSPropertyType)get_store().add_element_user(VERTICALCS$0); return target; } } }
true
a3a37c367921d49f19fce170b3c0095eb3514138
Java
YonatanYehezkel/Project
/RuthPetifours/src/NewMenu/ModelInvoice.java
UTF-8
6,302
2.4375
2
[]
no_license
package NewMenu; import java.math.BigDecimal; //import de.michaprogs.crm.article.ModelArticle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; public class ModelInvoice { private int invoiceID = 0; private String invoiceDate = ""; private int deliverybillID = 0; private String deliveryDate = ""; private String notes = ""; private int customerID = 0; private int clerkID = 0; private String clerk = ""; private BigDecimal total = new BigDecimal("0.00"); private int amountOfPositions = 0; //private ObservableList<ModelArticle> obsListPositions = FXCollections.observableArrayList(); private ObservableList<ModelInvoice> obsListInvoiceSearch = FXCollections.observableArrayList(); private ObservableList<ModelInvoice> obsListCustomerInvoice = FXCollections.observableArrayList(); public ModelInvoice(){} /** * Constructor for Database (Insert Invoice) * @param invoiceID * @param invoiceDate * @param deliverybillID * @param deliveryDate * @param notes * @param customerID * @param clerkID * @param total * @param amountOfPositions * @param obsListPositions */ public ModelInvoice(int invoiceID, String invoiceDate, int deliverybillID, String deliveryDate, String notes, int customerID, int clerkID, int amountOfPositions, BigDecimal total //,ObservableList<ModelArticle> obsListPositions ){ this.invoiceID = invoiceID; this.invoiceDate = invoiceDate; this.deliverybillID = deliverybillID; this.deliveryDate = deliveryDate; this.notes = notes; this.customerID = customerID; this.clerkID = clerkID; this.total = total; this.amountOfPositions = amountOfPositions; //this.obsListPositions = obsListPositions; } /** * Constructor for Database (Search Invoice) * @param invoiceID * @param invoiceDate * @param customerID * @param deliverybillID * @param deliveryDate */ public ModelInvoice(int invoiceID, String invoiceDate, int customerID, int deliverybillID, String deliveryDate){ this.invoiceID = invoiceID; this.invoiceDate = invoiceDate; this.customerID = customerID; this.deliverybillID = deliverybillID; this.deliveryDate = deliveryDate; } /** * Constructor for Database (Select Invoice) * Constructor for Database (Delete Invoice) * @param invoiceID * @param customerID */ public ModelInvoice(int invoiceID, int customerID){ this.invoiceID = invoiceID; this.customerID = customerID; } /** * Constructor for Database (Select Invoice Customer) * @param invoiceID */ public ModelInvoice(int customerID){ this.customerID = customerID; } /** * Constructor for ObservableList (Search Invoice) * @param invoiceID * @param invoiceDate * @param customerID * @param clerkID * @param deliverybillID * @param deliveryDate */ public ModelInvoice(int invoiceID, String invoiceDate, int customerID, int clerkID, int deliverybillID, String deliveryDate){ this.invoiceID = invoiceID; this.invoiceDate = invoiceDate; this.customerID = customerID; this.clerkID = clerkID; this.deliverybillID = deliverybillID; this.deliveryDate = deliveryDate; } /** * Constructor for ObservableList (Customer Invoice) * @param invoiceID * @param invoiceDate * @param deliverybillID * @param deliveryDate * @param clerk * @param amountOfPositions * @param total */ public ModelInvoice(int invoiceID, String invoiceDate, int deliverybillID, String deliveryDate, String clerk, int amountOfPositions, BigDecimal total){ this.invoiceID = invoiceID; this.invoiceDate = invoiceDate; this.deliverybillID = deliverybillID; this.deliveryDate = deliveryDate; this.clerk = clerk; this.amountOfPositions = amountOfPositions; this.total = total; } /* * GETTER & SETTER */ public int getInvoiceID() { return invoiceID; } public void setInvoiceID(int invoiceID) { this.invoiceID = invoiceID; } public String getInvoiceDate() { return invoiceDate; } public void setInvoiceDate(String invoiceDate) { this.invoiceDate = invoiceDate; } public int getDeliverybillID() { return deliverybillID; } public void setDeliverybillID(int deliverybillID) { this.deliverybillID = deliverybillID; } public String getDeliveryDate() { return deliveryDate; } public void setDeliveryDate(String deliveryDate) { this.deliveryDate = deliveryDate; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public int getCustomerID() { return customerID; } public void setCustomerID(int customerID) { this.customerID = customerID; } public int getClerkID() { return clerkID; } public void setClerkID(int clerkID) { this.clerkID = clerkID; } public String getClerk() { return clerk; } public void setClerk(String clerk) { this.clerk = clerk; } public BigDecimal getTotal() { return total; } public void setTotal(BigDecimal total) { this.total = total; } public int getAmountOfPositions() { return amountOfPositions; } public void setAmountOfPositions(int amountOfPositions) { this.amountOfPositions = amountOfPositions; } // public ObservableList<ModelArticle> getObsListPositions() { // return obsListPositions; // } // // public void setObsListPositions(ObservableList<ModelArticle> obsListPositions) { // this.obsListPositions = obsListPositions; // } public ObservableList<ModelInvoice> getObsListInvoiceSearch() { return obsListInvoiceSearch; } public void setObsListInvoiceSearch(ObservableList<ModelInvoice> obsListInvoiceSearch) { this.obsListInvoiceSearch = obsListInvoiceSearch; } public ObservableList<ModelInvoice> getObsListCustomerInvoice() { return obsListCustomerInvoice; } public void setObsListCustomerInvoice(ObservableList<ModelInvoice> obsListCustomerInvoice) { this.obsListCustomerInvoice = obsListCustomerInvoice; } }
true
17dae7d0aca19208dc75c1c6e8c499b59aeb759e
Java
Cortechs5511/Infinite-Recharge
/Outreach/src/main/java/frc/robot/subsystems/Limelight.java
UTF-8
1,913
2.4375
2
[]
no_license
package frc.robot.subsystems; import edu.wpi.first.wpilibj2.command.SubsystemBase; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.networktables.NetworkTable; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.networktables.NetworkTableInstance; public class Limelight extends SubsystemBase { private double x, y, area, distance; private NetworkTable table = NetworkTableInstance.getDefault().getTable("limelight"); private NetworkTableEntry tx = table.getEntry("tx"); private NetworkTableEntry ty = table.getEntry("ty"); private NetworkTableEntry ta = table.getEntry("ta"); private NetworkTableEntry ledMode = table.getEntry("ledMode"); public Limelight() { ledMode.setNumber(1); // sets lights off SmartDashboard.putNumber("Target RPM", 3300); } @Override public void periodic() { x = tx.getDouble(0.0); y = ty.getDouble(0.0); area = ta.getDouble(0.0); SmartDashboard.putNumber("X", x); SmartDashboard.putNumber("Y", y); SmartDashboard.putNumber("Area", area); distance = ((63.65) / Math.tan(Math.toRadians(y + 16.94))) * (((-Math.abs(y)) / 300) + 1); SmartDashboard.putNumber("Calculated Distance", distance); } public double calculateRPM() { /*double rpm = -(0.000215 * Math.pow(distance, 2)) + 4.76 * distance + 2735; SmartDashboard.putNumber("RPM Setpoint", rpm); if (y != 0) { // if image not captured, return default of 4200 return rpm; } else { return 4200; }*/ return (SmartDashboard.getNumber("Target RPM", 3300)); } public double getX() { return x; } public double getY() { return y; } public double getArea() { return area; } public double getLightStatus() { return ledMode.getDouble(1); } public void setLightStatus(double input) { ledMode.setNumber(input); // 3 = on, 1 = off } }
true
0ef39a80277f2a026c13ca6150a895cdf0245c5d
Java
specialkong/chodev
/chodev-web/src/main/java/egovframework/example/cmmn/web/AbstractPaginationRenderer.java
UTF-8
2,725
2.296875
2
[]
no_license
package egovframework.example.cmmn.web; import java.text.MessageFormat; import egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationRenderer; public abstract class AbstractPaginationRenderer implements PaginationRenderer { protected String firstPageLabel; protected String previousPageLabel; protected String currentPageLabel; protected String otherPageLabel; protected String nextPageLabel; protected String lastPageLabel; public String renderPagination(egovframework.rte.ptl.mvc.tags.ui.pagination.PaginationInfo paginationInfo, String jsFunction) { StringBuffer strBuff = new StringBuffer(); int firstPageNo = paginationInfo.getFirstPageNo(); int firstPageNoOnPageList = paginationInfo.getFirstPageNoOnPageList(); int totalPageCount = paginationInfo.getTotalPageCount(); int pageSize = paginationInfo.getPageSize(); int lastPageNoOnPageList = paginationInfo.getLastPageNoOnPageList(); int currentPageNo = paginationInfo.getCurrentPageNo(); int lastPageNo = paginationInfo.getLastPageNo(); if (totalPageCount > pageSize) { if (firstPageNoOnPageList > pageSize) { strBuff.append(MessageFormat.format(this.firstPageLabel, new Object[]{jsFunction, Integer.toString(firstPageNo)})); strBuff.append(MessageFormat.format(this.previousPageLabel, new Object[]{jsFunction, Integer.toString(firstPageNoOnPageList - 1)})); } else { strBuff.append(MessageFormat.format(this.firstPageLabel, new Object[]{jsFunction, Integer.toString(firstPageNo)})); strBuff.append(MessageFormat.format(this.previousPageLabel, new Object[]{jsFunction, Integer.toString(firstPageNo)})); } } for (int i = firstPageNoOnPageList; i <= lastPageNoOnPageList; ++i) { if (i == currentPageNo) { strBuff.append(MessageFormat.format(this.currentPageLabel, new Object[]{Integer.toString(i)})); } else { strBuff.append(MessageFormat.format(this.otherPageLabel, new Object[]{jsFunction, Integer.toString(i), Integer.toString(i)})); } } if (totalPageCount > pageSize) { if (lastPageNoOnPageList < totalPageCount) { strBuff.append(MessageFormat.format(this.nextPageLabel, new Object[]{jsFunction, Integer.toString(firstPageNoOnPageList + pageSize)})); strBuff.append(MessageFormat.format(this.lastPageLabel, new Object[]{jsFunction, Integer.toString(lastPageNo)})); } else { strBuff.append(MessageFormat.format(this.nextPageLabel, new Object[]{jsFunction, Integer.toString(lastPageNo)})); strBuff.append(MessageFormat.format(this.lastPageLabel, new Object[]{jsFunction, Integer.toString(lastPageNo)})); } } return strBuff.toString(); } }
true
b46c82f82dcdb27789362683bcb0e6035205510e
Java
aquadrini/java-circuit-breaker
/src/main/java/com/mercadolibre/resilience/breaker/stats/Stats.java
UTF-8
539
2.421875
2
[ "Apache-2.0" ]
permissive
package com.mercadolibre.resilience.breaker.stats; public abstract class Stats { public abstract long addSuccess(); public abstract long addFailure(); public abstract long successCount(); public abstract long failureCount(); public double failureRate() { long fails = failureCount(); return fails * 1.0 / (fails + successCount()); } public double successRate() { return 1 - failureRate(); } public long count() { return successCount() + failureCount(); } }
true
89d0bb5fcfb3dd49ab761a036f7e2250b38c5182
Java
marius199117/Automation-Testing
/src/main/java/common/Helper2.java
UTF-8
3,228
2.046875
2
[]
no_license
package common; import net.serenitybdd.core.pages.PageObject; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.yecht.Data; import java.util.concurrent.TimeUnit; import static pages.ContactPage.afterClick; public class Helper2 extends PageObject { public void clickElement(WebDriver ldriver, By element, int time) { Actions act = new Actions(ldriver); act.moveToElement(ldriver.findElement(element)).click().build().perform(); waitABit(time); } public void sendKeys(WebDriver ldriver, By element, String message, int time) { Actions act = new Actions(ldriver); act.moveToElement(ldriver.findElement(element)).sendKeys(message).build().perform(); waitABit(time); } public void clickAndSendKeys(WebDriver ldriver, By element, String message, int time) { Actions act = new Actions(ldriver); act.moveToElement(ldriver.findElement(element)).click().build().perform(); waitABit(time); act.moveToElement(ldriver.findElement(element)).sendKeys(message).build().perform(); waitABit(time); } public void clickAndSendKeysAndSelectButton(WebDriver ldriver, By element, String message, By element2, String message2, int time, By signUpButton) { Actions act = new Actions(ldriver); act.moveToElement(ldriver.findElement(element)).click().build().perform(); waitABit(time); act.moveToElement(ldriver.findElement(element)).sendKeys(message).build().perform(); waitABit(time); act.moveToElement(ldriver.findElement(element2)).click().build().perform(); waitABit(time); act.moveToElement(ldriver.findElement(element2)).sendKeys(message2).build().perform(); waitABit(time); act.moveToElement(ldriver.findElement(signUpButton)).click().build().perform(); waitABit(time); } public void clickAndSendKeysPasswordOrUsername(WebDriver webDriver, By element, String message, int time, By signUpButton) { Actions act = new Actions(webDriver); act.moveToElement(webDriver.findElement(element)).click().build().perform(); waitABit(time); act.moveToElement(webDriver.findElement(element)).sendKeys(message).build().perform(); waitABit(time); act.moveToElement(webDriver.findElement(signUpButton)).click().build().perform(); waitABit(time); } public void selectAndAssertTrue(WebDriver webDriver, By element, int time, By element2, String message) { Actions act = new Actions(webDriver); act.moveToElement(webDriver.findElement(element)).click().build().perform(); waitABit(time); element(element2).withTimeoutOf(15, TimeUnit.SECONDS).waitUntilVisible(); Assert.assertTrue(message, find(element2).isDisplayed()); } public void verifyAndAssertElement(By element, String message) { element(element).withTimeoutOf(15, TimeUnit.SECONDS).waitUntilVisible(); Assert.assertTrue(message, find(element).isDisplayed()); } }
true
42e60e69565cdf7dda967bbf3abbc62fb6dd7511
Java
Self-Education-Liavontsi-Brechka/Spittr
/src/main/java/net/liavontsibrechka/spittr/web/controller/SpitterController.java
UTF-8
2,576
2.140625
2
[]
no_license
package net.liavontsibrechka.spittr.web.controller; import net.liavontsibrechka.spittr.Spitter; import net.liavontsibrechka.spittr.data.SpitterRepository; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.Part; import javax.validation.Valid; @Controller @RequestMapping("/spitter") public class SpitterController { private SpitterRepository spitterRepository; //@Autowired public SpitterController(SpitterRepository spitterRepository) { this.spitterRepository = spitterRepository; } @RequestMapping(value = "/register", method = RequestMethod.GET) public String showRegistrationForm(Model model) { model.addAttribute(new Spitter()); return "registerForm"; } /* * Ways to accept requestPart argument: * byte[] profilePicture * MultipartFile profilePicture - requires multipart configuration * Part profilePicture - doesn't require multipart configuration * */ @RequestMapping(value = "/register", method = RequestMethod.POST) public String processRegistration(@RequestPart(name = "profilePicture") Part profilePicture, @Valid Spitter spitter, Errors errors, RedirectAttributes model) { if (errors.hasErrors()) return "registerForm"; spitterRepository.save(spitter); model.addAttribute("username", spitter.getUsername()); model.addFlashAttribute("spitter", spitter); // model.addAttribute("spitterId", spitter.getId()); // because the spitterId attribute from the model doesn’t map to any URL placeholders in the redirect, // it’s tacked on to the redirect automatically as a query parameter. return "redirect:/spitter/{username}"; } @RequestMapping(value = "/{username}", method = RequestMethod.GET) public String showSpitterProfile(@PathVariable("username") String username, Model model) { if (!model.containsAttribute("sptter")) model.addAttribute("spitter", spitterRepository.findByUsername(username)); return "profile"; } }
true
0de9d928bdb3e8dd4845c4278e19146c048531d2
Java
chenzifeng1/algorithm-learn
/src/main/java/dynamicProgramming/DP_Bag.java
UTF-8
1,597
3.390625
3
[]
no_license
package dynamicProgramming; /** * @ProjectName: * @ClassName: DP_Bag * @Author: czf * @Description: 背包问题 * v[] 价值 * w[] 重量 * int bag 容量 * 选出符合容量的最大价值 * * * @Date: 2021/7/21 21:19 * @Version: 1.0 **/ public class DP_Bag { public static void main(String[] args) { int[] value = new int[] { }; int[] weight = new int[] { }; int bag = 0; } /** * * @param v * @param w * @param index * @param rest * @return */ public static int deal(int[] v,int[] w,int index,int rest){ if(v.length==0||index>=v.length||v.length!=w.length){ return 0; } if(rest<0){ return -1; } // 不选index的货物 int bv1 = deal(v,w,index+1,rest); // 选index的货物 int temp = deal(v,w,index+1,rest-w[index]); int bv2 =temp==-1?0: temp; return Math.max(bv1,bv2); } public static int dealByDp(int[] v,int[] w,int index,int bag){ int row = v.length+1; int col = bag+1; int[][]dp = new int[row][col]; for(int i = v.length-1;i>=0;i--){ for(int j = 0;j<col;j++){ int bv1 = dp[i+1][j]; // 选index的货物 int temp =j-w[i]<0?-1:dp[i+1][j-w[i]]; int bv2 = 0; if(temp!=-1){ bv2 = v[i] + temp; } dp[i][j] = Math.max(bv1,bv2); } } return dp[0][bag]; } }
true
369d2a9c832c14bb6041ffcdd71d00ce64b91c70
Java
martinMamani/cursojavase
/Clase13/Clase12/src/ar/com/eduit/curso/java/test/TestConnection.java
UTF-8
945
2.59375
3
[]
no_license
package ar.com.eduit.curso.java.test; import ar.com.eduit.curso.java.connectors.ConnectorMySQL; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.Savepoint; import java.sql.Statement; public class TestConnection { public static void main(String[] args) throws Exception{ Connection conn=ConnectorMySQL.getConnection(); Statement st=conn.createStatement(); String query="insert into cursos(titulo,profesor,dia,turno) values " + "('java','Carlos Ríos','lunes','tarde')"; st.execute(query); ConnectorMySQL.getConnection().createStatement().execute( "insert into cursos(titulo,profesor,dia,turno) values " + "('java2','Carlos Ríos','martes','noche')" ); // ConnectorMySQL.getConnection().createStatement().execute( // "delete from cursos" // ); } }
true
62ba0e27a908d2b71dcf7d4321332652aeafafdf
Java
yy9320/clonecoding_cp
/src/main/java/com/clonecoding/myapp/main/mainService/MainService.java
UTF-8
436
1.789063
2
[]
no_license
package com.clonecoding.myapp.main.mainService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.clonecoding.myapp.main.VO.Greeting; import com.clonecoding.myapp.main.mainDao.MainMapper; @Service public class MainService { @Autowired public MainMapper mapper; public List<Greeting> selectTest() { return mapper.selectTest(); } }
true
b480b6d002d9a743cf2b7a32f723057a6bbd4d68
Java
RuuuvyGo/myProjects
/2015/socialPro/src/dto/CopiedProjectVDTO.java
UTF-8
2,239
2.46875
2
[]
no_license
package dto; public class CopiedProjectVDTO { private String copiedProjectCode; private String copiedFolderCode; private String copiedPath; private String copiedOwnerCode; private String originProjectCode; private String originFolderCode; private String originPath; private String originOwnerCode; public CopiedProjectVDTO() { } public CopiedProjectVDTO(String copiedProjectCode, String copiedFolderCode, String copiedPath, String copiedOwnerCode, String originProjectCode, String originFolderCode, String originPath, String originOwnerCode) { this.copiedProjectCode = copiedProjectCode; this.copiedFolderCode = copiedFolderCode; this.copiedPath = copiedPath; this.copiedOwnerCode = copiedOwnerCode; this.originProjectCode = originProjectCode; this.originFolderCode = originFolderCode; this.originPath = originPath; this.originOwnerCode = originOwnerCode; } public String getCopiedProjectCode() { return copiedProjectCode; } public void setCopiedProjectCode(String copiedProjectCode) { this.copiedProjectCode = copiedProjectCode; } public String getCopiedFolderCode() { return copiedFolderCode; } public void setCopiedFolderCode(String copiedFolderCode) { this.copiedFolderCode = copiedFolderCode; } public String getCopiedPath() { return copiedPath; } public void setCopiedPath(String copiedPath) { this.copiedPath = copiedPath; } public String getCopiedOwnerCode() { return copiedOwnerCode; } public void setCopiedOwnerCode(String copiedOwnerCode) { this.copiedOwnerCode = copiedOwnerCode; } public String getOriginProjectCode() { return originProjectCode; } public void setOriginProjectCode(String originProjectCode) { this.originProjectCode = originProjectCode; } public String getOriginFolderCode() { return originFolderCode; } public void setOriginFolderCode(String originFolderCode) { this.originFolderCode = originFolderCode; } public String getOriginPath() { return originPath; } public void setOriginPath(String originPath) { this.originPath = originPath; } public String getOriginOwnerCode() { return originOwnerCode; } public void setOriginOwnerCode(String originOwnerCode) { this.originOwnerCode = originOwnerCode; } }
true
774515325171074cfa9830634635633484239f7c
Java
SimoneBaselicePolimi/ingswAM2021-Baselice-Bagnoli-Brugnano
/src/main/java/it/polimi/ingsw/server/model/gameitems/developmentcard/DevelopmentCardsTableImp.java
UTF-8
5,293
2.96875
3
[]
no_license
package it.polimi.ingsw.server.model.gameitems.developmentcard; import it.polimi.ingsw.server.model.Player; import it.polimi.ingsw.server.model.gameitems.GameItemsManager; import it.polimi.ingsw.server.model.gameitems.cardstack.ShuffledCoveredCardDeck; import it.polimi.ingsw.server.model.gameitems.cardstack.ShuffledCoveredCardDeckImp; import it.polimi.ingsw.server.modelrepresentation.gameitemsrepresentation.developmentcardrepresentation.ServerDevelopmentCardRepresentation; import it.polimi.ingsw.server.modelrepresentation.gameitemsrepresentation.developmentcardrepresentation.ServerDevelopmentCardsTableRepresentation; import java.util.ArrayList; import java.util.EmptyStackException; import java.util.List; import java.util.Map; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; /** * This class represents the table on which the decks of development cards are located */ public class DevelopmentCardsTableImp implements DevelopmentCardsTable { /** * Map that contains the cards in each deck, along with their colour and level */ private Map<DevelopmentCardLevel, Map<DevelopmentCardColour, ShuffledCoveredCardDeck<ServerDevelopmentCardRepresentation, DevelopmentCard>>> cards; /** * DevelopmentCardsTable constructor * @param cards that are placed in decks * @param gameItemsManager a reference to gameItemsManager is needed to register all the decks created * (see {@link it.polimi.ingsw.server.model.gameitems.RegisteredIdentifiableItem}) * @param getIdForDeckWithColourAndLevel lambda that specifies the criteria for assigning the IDs of the decks */ public DevelopmentCardsTableImp( List<DevelopmentCard> cards, GameItemsManager gameItemsManager, BiFunction<DevelopmentCardColour, DevelopmentCardLevel, String> getIdForDeckWithColourAndLevel ) { this.cards = cards.stream().collect(Collectors.groupingBy( DevelopmentCard::getLevel, Collectors.groupingBy( DevelopmentCard::getColour, Collectors.collectingAndThen( Collectors.toList(), cardsForDeck -> { DevelopmentCardColour deckColour = cardsForDeck.get(0).getColour(); DevelopmentCardLevel deckLevel = cardsForDeck.get(0).getLevel(); String deckID = getIdForDeckWithColourAndLevel.apply(deckColour, deckLevel); return new ShuffledCoveredCardDeckImp<>(deckID, gameItemsManager, cardsForDeck); } ) ) )); } /** * Method to get all the cards that are available (cards that are on top of each deck) * @return list of development cards that are available */ @Override public List<DevelopmentCard> getAvailableCards() { List<DevelopmentCard> availableCards = new ArrayList<>(); for (Map<DevelopmentCardColour, ShuffledCoveredCardDeck<ServerDevelopmentCardRepresentation, DevelopmentCard>> value : cards.values()) { for (ShuffledCoveredCardDeck<ServerDevelopmentCardRepresentation, DevelopmentCard> deck : value.values()) if(!deck.isEmpty()) availableCards.add(deck.peek()); } return availableCards; } /** * Method to remove the Card from the top of the Deck and get this Card. * @param level level of card to remove * @param colour colour of card to remove * @return DevelopmentCard the Development Card to remove * @throws EmptyStackException if the deck is empty */ @Override public DevelopmentCard popCard(DevelopmentCardLevel level, DevelopmentCardColour colour){ return (this.getDeckByLevelAndColour(level, colour).pop()); } /** * Method to get all the cards that are available (cards that are on top of each deck) * @return map of development cards that are available, along with their colour and level */ @Override public Map<DevelopmentCardLevel,Map<DevelopmentCardColour,DevelopmentCard>> getAvailableCardsAsMap() { return getAvailableCards().stream().collect( Collectors.groupingBy( DevelopmentCard::getLevel, Collectors.toMap( DevelopmentCard::getColour, Function.identity() ) ) ); } /** * Method to get the Deck that contains cards of a specific colour and level * @param cardLevel level of cards to return * @param cardColour colour of cards to return * @return the Deck that contains list of development cards that are randomly organized * @throws IllegalArgumentException if the deck does not exist */ @Override public ShuffledCoveredCardDeck<ServerDevelopmentCardRepresentation, DevelopmentCard> getDeckByLevelAndColour(DevelopmentCardLevel cardLevel, DevelopmentCardColour cardColour) throws IllegalArgumentException{ if (!cards.containsKey(cardLevel) || !cards.get(cardLevel).containsKey(cardColour)) throw new IllegalArgumentException(); return(cards.get(cardLevel).get(cardColour)); } @Override public ServerDevelopmentCardsTableRepresentation getServerRepresentation() { return new ServerDevelopmentCardsTableRepresentation( cards.entrySet().stream().collect(Collectors .toMap(Map.Entry::getKey, e -> e.getValue().entrySet().stream().collect(Collectors .toMap(Map.Entry::getKey, v -> v.getValue().getServerRepresentation())) )) ); } @Override public ServerDevelopmentCardsTableRepresentation getServerRepresentationForPlayer(Player player) { return getServerRepresentation(); } }
true
ba7169c9f7ba2c5ab755857395a56828a323138c
Java
Mahrous/complainant
/app/src/main/java/com/example/shehab/complainant/Login_Activity.java
UTF-8
4,621
2.203125
2
[]
no_license
package com.example.shehab.complainant; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class Login_Activity extends AppCompatActivity { private FirebaseAuth mAuth; private EditText eMail,pAssword; private Button signin; private ProgressDialog Loginbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login_); mAuth = FirebaseAuth.getInstance(); TextView link_text = (TextView)findViewById(R.id.text_link); eMail = (EditText)findViewById(R.id.edt_email); pAssword = (EditText)findViewById(R.id.edt_pass); signin = (Button)findViewById(R.id.btn_con); YoYo.with(Techniques.FadeInDown) .duration(2500) .playOn(findViewById(R.id.text_e)); YoYo.with(Techniques.FadeInDown) .duration(4500) .playOn(findViewById(R.id.edt_email)); YoYo.with(Techniques.FadeInDown) .duration(8500) .playOn(findViewById(R.id.edt_pass)); YoYo.with(Techniques.FadeInDown) .duration(8500) .playOn(findViewById(R.id.btn_con)); YoYo.with(Techniques.FadeInDown) .duration(8500) .playOn(findViewById(R.id.text_link)); link_text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(),Register_Activity.class)); } }); signin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { LoginuserAccount(eMail.getText().toString(),pAssword.getText().toString()); } }); Loginbar=new ProgressDialog(this); } @Override protected void onStart() { super.onStart(); FirebaseUser currnetuser=mAuth.getCurrentUser(); if(currnetuser!=null) { startActivity(new Intent(getApplicationContext(),First_departments.class)); } } public void LoginuserAccount(String email, String password) { if(TextUtils.isEmpty(email)) { Toast.makeText(getBaseContext(),"enter your email", Toast.LENGTH_LONG).show(); } if(TextUtils.isEmpty(password)) { Toast.makeText(getBaseContext(),"enter your password", Toast.LENGTH_LONG).show(); }else { Loginbar.setTitle("Login Account"); Loginbar.setMessage("Now will done login the account "); Loginbar.show(); mAuth.signInWithEmailAndPassword(email,password) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Intent mainIntent=new Intent(getApplicationContext(),First_departments.class); mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(mainIntent); finish(); } else { String messgae=task.toString(); Toast.makeText(getBaseContext(),"make sure the email or password is corrected"+messgae, Toast.LENGTH_LONG).show(); } Loginbar.dismiss(); } }); } } @Override protected void onPause() { super.onPause(); finish(); } }
true
ba159eafee78c09d9a229b73bb62da32acc21812
Java
ipartek/web-zalla
/toni-garcia/JAVA/Pruebas/src/subastas/Subasta.java
UTF-8
1,614
2.859375
3
[]
no_license
package subastas; import java.util.ArrayList; public class Subasta { private String nombreObjeto = ""; private Usuario usur = new Usuario("nombre"); private boolean estado = true; private ArrayList<Double> listaPujas = new ArrayList<Double>(); private double pujaMayor = 0.0; public Subasta(String nombreObjeto,Usuario propietario,boolean estado){ this.nombreObjeto=nombreObjeto; this.usur=propietario; this.estado=estado; } @Override public String toString() { return "Subasta [Nombre del Objeto=" + nombreObjeto + ", Propietario=" + usur + ", Estado=" + estado + ", Puja Mayor=" + pujaMayor + "]"; } public Subasta(String nombreObjeto,Usuario propietario,boolean estado,double pujaMayor){ this.nombreObjeto=nombreObjeto; this.usur=propietario; this.estado=estado; this.pujaMayor=pujaMayor; } public String getNombreObjeto() { return nombreObjeto; } public void setNombreObjeto(String nombreObjeto) { this.nombreObjeto = nombreObjeto; } public void setNombrePropietario(Usuario propietario){ this.usur=propietario; } public Usuario getNombrePropietario(){ return usur; } public boolean isEstado() { return estado; } public void setEstado(boolean estado) { this.estado = estado; } public ArrayList<Double> getListaPujas() { return listaPujas; } public void setListaPujas(ArrayList<Double> listaPujas) { this.listaPujas = listaPujas; } public double getPujaMayor() { return pujaMayor; } public void setPujaMayor(double pujaMayor) { this.pujaMayor = pujaMayor; } public static void consultarCatalogo(){ } }
true
2dec134670fd523d714400e8b8721d9ab42a722e
Java
UltraGameCoder/Survival-Islands
/SurvivalIslands/src/main/java/managers/Transaction.java
UTF-8
21,033
2.0625
2
[]
no_license
package managers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import islands.PlayerIsland; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.economy.EconomyResponse; import survivalislands.SurvivalIslands; import utilities.chatUtil; public class Transaction implements InventoryHolder, Listener { private static int ID; private boolean _finished; private int _id; private Inventory _GUI; private TransactionType _type; private UUID uuid; private ItemStack item; private double _costEach; private double _costEachLayer; private String _title; private ItemStack addOne, addFive, addThirdyTwo, addSixtyFour; private ItemStack removeOne, removeFive, removeThirdyTwo, removeSixtyFour; private ItemStack firstLayer, secondLayer, thirdLayer, fourthLayer, fifthLayer; private ItemStack info, cancel, finish, selectableIndicator; private Inventory _from; private int amount; public enum TransactionType { BUYITEM, SELLITEM, BUYLAYERREGEN } public Transaction(TransactionType type, Player player, ItemStack shopItem, Inventory from) { this._finished = false; this._id = (ID++); this._type = type; this.uuid = player.getUniqueId(); this._costEach = 0; this.item = shopItem; this._from = from; if (type == TransactionType.BUYITEM || type == TransactionType.SELLITEM) { this.amount = 1; String costs = getItemCosts(item); if (costs == null) { this._finished = true; return; } String[] args = costs.split(":"); if (type == TransactionType.BUYITEM) { this._costEach = Double.parseDouble(args[0]); this._title = ChatColor.translateAlternateColorCodes('&', "&7Transaction: &aBuy"); }else if (type == TransactionType.SELLITEM) { this._costEach = Double.parseDouble(args[1]); this._title = ChatColor.translateAlternateColorCodes('&', "&7Transaction: &cSell"); } createGUI(); player.openInventory(this._GUI); }else if (type == TransactionType.BUYLAYERREGEN) { this._costEachLayer = ConfigManager.getManager().getConfig().getDouble("LayerRegenCostEach"); this._title = ChatColor.translateAlternateColorCodes('&', "&7Transaction: &aBuy Layer regen"); this.amount = 0; createGUI(); player.openInventory(this._GUI); } SurvivalIslands.getInstance().getServer().getPluginManager().registerEvents(this, SurvivalIslands.getInstance()); } private void createGUI() { createItems(); this._GUI = Bukkit.createInventory(this, 6 * 9, this._title); if (this._type == TransactionType.BUYITEM || this._type == TransactionType.SELLITEM ) { this._GUI.setItem(18, addOne); this._GUI.setItem(19, addFive); this._GUI.setItem(20, addThirdyTwo); this._GUI.setItem(21, addSixtyFour); this._GUI.setItem(13, info); this._GUI.setItem(45, cancel); this._GUI.setItem(53, finish); this._GUI.setItem(23, removeOne); this._GUI.setItem(24, removeFive); this._GUI.setItem(25, removeThirdyTwo); this._GUI.setItem(26, removeSixtyFour); } if (this._type == TransactionType.BUYLAYERREGEN ) { this._GUI.setItem(4, info); this._GUI.setItem(0, cancel); this._GUI.setItem(8, finish); setRow(this._GUI,13,firstLayer,false); setRow(this._GUI,22,secondLayer,false); setRow(this._GUI,31,thirdLayer,false); setRow(this._GUI,40,fourthLayer,false); setRow(this._GUI,49,fifthLayer,false); } updateInfo(); } @SuppressWarnings("deprecation") private void createItems() { if (this._type == TransactionType.BUYITEM ||this._type == TransactionType.SELLITEM) { info = item.clone(); }else if (this._type == TransactionType.BUYLAYERREGEN) { info = new ItemStack(Material.PAPER,1); } if (this._type == TransactionType.BUYLAYERREGEN) { firstLayer = new ItemStack(Material.STAINED_CLAY, 1); ItemMeta meta = firstLayer.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aFirst Layer")); firstLayer.setItemMeta(meta); secondLayer = new ItemStack(Material.STAINED_CLAY, 1); meta = secondLayer.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aSecond Layer")); secondLayer.setItemMeta(meta); thirdLayer = new ItemStack(Material.STAINED_CLAY, 1); meta = thirdLayer.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aThird Layer")); thirdLayer.setItemMeta(meta); fourthLayer = new ItemStack(Material.STAINED_CLAY, 1); meta = fourthLayer.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aFourth Layer")); fourthLayer.setItemMeta(meta); fifthLayer = new ItemStack(Material.STAINED_CLAY, 1); meta = fifthLayer.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aFifth Layer")); fifthLayer.setItemMeta(meta); meta = info.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Info")); meta.setLore(new ArrayList<String>()); info.setItemMeta(meta); cancel = new ItemStack(Material.WOOL, 1, (short) 0, (byte) 14); meta = cancel.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&cCancel")); cancel.setItemMeta(meta); finish = new ItemStack(Material.WOOL, 1, (short) 0, (byte) 5); meta = finish.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&6Finish")); finish.setItemMeta(meta); selectableIndicator = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short)0, (byte) 7); meta = selectableIndicator.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&a")); selectableIndicator.setItemMeta(meta); } if (this._type == TransactionType.BUYITEM ||this._type == TransactionType.SELLITEM) { addOne = new ItemStack(Material.STAINED_CLAY, 1); ItemMeta meta = addOne.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&a+1")); addOne.setItemMeta(meta); addFive = new ItemStack(Material.IRON_BLOCK, 1); meta = addFive.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&a+5")); addFive.setItemMeta(meta); addThirdyTwo = new ItemStack(Material.GOLD_BLOCK, 1); meta = addThirdyTwo.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&a+32")); addThirdyTwo.setItemMeta(meta); addSixtyFour = new ItemStack(Material.DIAMOND_BLOCK, 1); meta = addSixtyFour.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&a+64")); addSixtyFour.setItemMeta(meta); meta = info.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Info")); meta.setLore(new ArrayList<String>()); info.setItemMeta(meta); cancel = new ItemStack(Material.WOOL, 1, (short) 0, (byte) 14); meta = cancel.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&cCancel")); cancel.setItemMeta(meta); finish = new ItemStack(Material.WOOL, 1, (short) 0, (byte) 5); meta = finish.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&6Finish")); finish.setItemMeta(meta); removeOne = new ItemStack(Material.STAINED_CLAY, 1); meta = removeOne.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&c-1")); removeOne.setItemMeta(meta); removeFive = new ItemStack(Material.IRON_BLOCK, 1); meta = removeFive.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&c-5")); removeFive.setItemMeta(meta); removeThirdyTwo = new ItemStack(Material.GOLD_BLOCK, 1); meta = removeThirdyTwo.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&c-32")); removeThirdyTwo.setItemMeta(meta); removeSixtyFour = new ItemStack(Material.DIAMOND_BLOCK, 1); meta = removeSixtyFour.getItemMeta(); meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&c-64")); removeSixtyFour.setItemMeta(meta); } } @EventHandler public void onClose(InventoryCloseEvent e) { if (!e.getInventory().getTitle().equalsIgnoreCase(this._GUI.getTitle()))return; this._finished = true; } @EventHandler public void onGUI(InventoryClickEvent e) { if (!e.getInventory().getTitle().equalsIgnoreCase(this._GUI.getTitle()))return; ItemStack selected = e.getCurrentItem(); if (selected == null || selected.getType() == Material.AIR)return; e.setCancelled(true); if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(finish.getItemMeta().getDisplayName())) { finish(); Player player = getPlayer(); if (player == null) { this._finished = true; return; } if (this._type == TransactionType.BUYITEM || this._type == TransactionType.SELLITEM) { player.openInventory(this._from); }else if (this._type == TransactionType.BUYLAYERREGEN) { IslandsManager.getManager().openIslandManager(player); } } if (selected.getItemMeta().toString().equalsIgnoreCase(cancel.getItemMeta().toString())) { Player player = getPlayer(); if (player == null) { this._finished = true; return; } if (this._type == TransactionType.BUYITEM || this._type == TransactionType.SELLITEM) { player.openInventory(this._from); }else if (this._type == TransactionType.BUYLAYERREGEN) { IslandsManager.getManager().openIslandManager(player); } } if (this._type == TransactionType.BUYITEM || this._type == TransactionType.SELLITEM) { if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(addOne.getItemMeta().getDisplayName())) { amount += 1; if (amount < 1) { amount = 1; } updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(addFive.getItemMeta().getDisplayName())) { amount += 5; if (amount < 1) { amount = 1; } updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(addThirdyTwo.getItemMeta().getDisplayName())) { amount += 32; if (amount < 1) { amount = 1; } updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(addSixtyFour.getItemMeta().getDisplayName())) { amount += 64; if (amount < 1) { amount = 1; } updateInfo(); } // if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(removeOne.getItemMeta().getDisplayName())) { amount -= 1; if (amount < 1) { amount = 1; } updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(removeFive.getItemMeta().getDisplayName())) { amount -= 5; if (amount < 1) { amount = 1; } updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(removeThirdyTwo.getItemMeta().getDisplayName())) { amount -= 32; if (amount < 1) { amount = 1; } updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(removeSixtyFour.getItemMeta().getDisplayName())) { amount -= 64; if (amount < 1) { amount = 1; } updateInfo(); } }else if (this._type == TransactionType.BUYLAYERREGEN ) { if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(firstLayer.getItemMeta().getDisplayName())) { boolean active = (firstLayer.getDurability() == 5); amount += (active)? -1 : 1; if (amount < 0) { amount = 0; } setRow(this._GUI,13,firstLayer,!active); updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(secondLayer.getItemMeta().getDisplayName())) { boolean active = (secondLayer.getDurability() == 5); amount += (active)? -1 : 1; if (amount < 0) { amount = 0; } setRow(this._GUI,22,secondLayer,!active); updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(thirdLayer.getItemMeta().getDisplayName())) { boolean active = (thirdLayer.getDurability() == 5); amount += (active)? -1 : 1; if (amount < 0) { amount = 0; } setRow(this._GUI,31,thirdLayer,!active); updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(fourthLayer.getItemMeta().getDisplayName())) { boolean active = (fourthLayer.getDurability() == 5); amount += (active)? -1 : 1; if (amount < 0) { amount = 0; } setRow(this._GUI,40,fourthLayer,!active); updateInfo(); } if (selected.getItemMeta().getDisplayName().equalsIgnoreCase(fifthLayer.getItemMeta().getDisplayName())) { boolean active = (fifthLayer.getDurability() == 5); amount += (active)? -1 : 1; if (amount < 0) { amount = 0; } setRow(this._GUI,49,fifthLayer,!active); updateInfo(); } } } private void setRow(Inventory inv, int index, ItemStack layer, boolean selected) { selectableIndicator.setDurability((short) ((selected)? 5 : 7)); layer.setDurability((short) ((selected)? 5 : 0)); this._GUI.setItem(index-4, selectableIndicator); this._GUI.setItem(index-3, selectableIndicator); this._GUI.setItem(index-2, selectableIndicator); this._GUI.setItem(index-1, selectableIndicator); this._GUI.setItem(index, layer); this._GUI.setItem(index+1, selectableIndicator); this._GUI.setItem(index+2, selectableIndicator); this._GUI.setItem(index+3, selectableIndicator); this._GUI.setItem(index+4, selectableIndicator); } private void updateInfo() { Economy econ = SurvivalIslands.getEconomy(); OfflinePlayer player = getPlayer(); if (player == null) { this._finished = true; return; } if (this._type == TransactionType.BUYITEM || this._type == TransactionType.SELLITEM) { List<String> lore = new ArrayList<String>(); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Your balance: &6"+econ.getBalance(player))); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Amount: &6"+this.amount)); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Cost&8: &6"+this._costEach+"&7/each")); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Total: &6"+(this.amount * this._costEach))); lore.add(""); ItemMeta meta = info.getItemMeta(); meta.setLore(lore); info.setItemMeta(meta); this._GUI.setItem(13, info); }else if (this._type == TransactionType.BUYLAYERREGEN) { List<String> lore = new ArrayList<String>(); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Your balance: &6"+econ.getBalance(player))); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Amount: &6"+this.amount)); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Cost&8: &6"+this._costEachLayer+"&7/each")); lore.add(""); lore.add(ChatColor.translateAlternateColorCodes('&', "&7Total: &6"+(this.amount * this._costEachLayer))); lore.add(""); ItemMeta meta = info.getItemMeta(); meta.setLore(lore); info.setItemMeta(meta); this._GUI.setItem(4, info); } } public boolean finish() { Economy econ = SurvivalIslands.getEconomy(); Player player = getPlayer(); if (player == null) { this._finished = true; return false; } double totalCost = 0.0f; if (this._type == TransactionType.BUYITEM || this._type == TransactionType.SELLITEM) { totalCost = this._costEach * this.amount; }else if (this._type == TransactionType.BUYLAYERREGEN) { totalCost = _costEachLayer * this.amount; } if (this._type == TransactionType.BUYITEM) { EconomyResponse transactionPaper = econ.withdrawPlayer(player, totalCost); if (transactionPaper.transactionSuccess()) { chatUtil.sendMessage(player, "&a"+totalCost+"$ withdraw successful!", true); ItemStack invItem = getRawItem(this.item); for (int i = 0; i < this.amount; i++) { player.getInventory().addItem(invItem); } this._finished = true; return true; }else { chatUtil.sendMessage(player, "&cYou can't afford this item!", true); } }else if (this._type == TransactionType.SELLITEM) { ItemStack invItem = getRawItem(this.item); if (player.getInventory().contains(invItem.getType(), this.amount)) { Map<Integer, ItemStack> totalRests = new HashMap<Integer, ItemStack>(); for (int i = 0; i < this.amount; i++) { Map<Integer, ItemStack> rests = player.getInventory().removeItem(invItem); for (Entry<Integer, ItemStack> entry : rests.entrySet()) { totalRests.put(entry.getKey(), entry.getValue()); } } if (totalRests.isEmpty()) { EconomyResponse transactionPaper = econ.depositPlayer(player, totalCost); if (transactionPaper.transactionSuccess()) { chatUtil.sendMessage(player, "&a"+totalCost+"$ deposit successful!", true); this._finished = true; return true; }else { chatUtil.sendMessage(player, "&cDeposit failure! please contact staff to deposit "+ totalCost +" to your account!", true); } }else { chatUtil.sendMessage(player, "&cSomething went wrong when trying to remove the selling item from your inventory!", true); chatUtil.sendMessage(player, "Please contact a staff member to report this problem", true); } }else { chatUtil.sendMessage(player, "You don't have enough of this item to sell it!", true); } }else if (this._type == TransactionType.BUYLAYERREGEN) { if (amount <= 0) { this._finished = true; return true; } EconomyResponse transactionPaper = econ.withdrawPlayer(player, totalCost); if (transactionPaper.transactionSuccess()) { chatUtil.sendMessage(player, "&a"+totalCost+"$ withdraw successful!", true); regenIsland(); this._finished = true; return true; }else { chatUtil.sendMessage(player, "&cYou can't afford this amount of layers to regenerate!", true); } } player.closeInventory(); this._finished = true; return false; } @SuppressWarnings("deprecation") private void regenIsland() { boolean[] selected = new boolean[5]; selected[0] = (firstLayer.getData().getData() == 5); selected[1] = (secondLayer.getData().getData() == 5); selected[2] = (thirdLayer.getData().getData() == 5); selected[3] = (fourthLayer.getData().getData() == 5); selected[4] = (fifthLayer.getData().getData() == 5); Player p = getPlayer(); if (p == null) { this._finished = true; return; } PlayerIsland island = IslandsManager.getManager().getIslandOf(p); island.regenLayers(selected, 30 / 5); } private Player getPlayer() { return Bukkit.getPlayer(this.uuid); } @SuppressWarnings("deprecation") private String getItemCosts(ItemStack shopItem) { for (Entry<ItemStack, String> entry : ShopManager.getManager().shopItemPrices.entrySet()) { ItemStack key = entry.getKey(); Material mat = key.getType(); int amount = key.getAmount(); byte data = key.getData().getData(); if (shopItem.getType() == mat && shopItem.getAmount() == amount && shopItem.getData().getData() == data) { return entry.getValue(); } } return null; } @SuppressWarnings("deprecation") private ItemStack getRawItem(ItemStack shopItem) { for (Entry<ItemStack, String> entry : ShopManager.getManager().shopItemPrices.entrySet()) { ItemStack key = entry.getKey(); Material mat = key.getType(); int amount = key.getAmount(); byte data = key.getData().getData(); if (shopItem.getType() == mat && shopItem.getAmount() == amount && shopItem.getData().getData() == data) { return entry.getKey(); } } return null; } @Override public Inventory getInventory() { // TODO Auto-generated method stub return null; } public int getID() { return this._id; } public boolean isFinished() { return _finished; } }
true
2461076afcc4f11a99a979240a777ed691681018
Java
ABRUZI/octopus-slaver
/octopus-slaver/src/main/java/org/rhino/octopus/slaver/listener/remote/RemoteListener.java
UTF-8
2,030
2.296875
2
[]
no_license
package org.rhino.octopus.slaver.listener.remote; import org.apache.thrift.TProcessor; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.server.TServer; import org.apache.thrift.server.TThreadPoolServer; import org.apache.thrift.transport.TServerSocket; import org.rhino.octopus.base.configuration.OctopusConfiguration.ConfigurationItem; import org.rhino.octopus.base.configuration.Property; import org.rhino.octopus.base.exception.OctopusException; import org.rhino.octopus.base.remote.SlaverRemoteService; import org.rhino.octopus.slaver.context.SlaverContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RemoteListener implements Runnable{ private static final Logger logger = LoggerFactory.getLogger(RemoteListener.class); private static RemoteListener instance = new RemoteListener(); private TServer server; private RemoteListener(){} public static RemoteListener getInstance(){ return instance; } public void open()throws OctopusException{ try{ logger.debug("初始化远程服务监听器"); Property remotePortProp = SlaverContext.getInstance().getConfiguration().getProperty(ConfigurationItem.SLAVER_REMOTE_LISTENER_PORT); TProcessor tprocessor = new SlaverRemoteService.Processor<SlaverRemoteService.Iface>( new SlaveRemoteServiceImpl()); TServerSocket serverTransport = new TServerSocket(Integer.parseInt(remotePortProp.getValue())); TThreadPoolServer.Args ttpsArgs = new TThreadPoolServer.Args( serverTransport); ttpsArgs.processor(tprocessor); ttpsArgs.protocolFactory(new TBinaryProtocol.Factory()); this.server = new TThreadPoolServer(ttpsArgs); logger.debug("远程服务监听器初始化完毕"); }catch(Exception e){ logger.error("Init remote service listener failed", e); throw new OctopusException(e); } } public void close(){ this.server.stop(); } @Override public void run() { this.server.serve(); } }
true
0d88bd6c65b80db6e9b8650c35cebdb0a66eb054
Java
bkmzli1/InstallerDrizzle
/src/main/java/ru/bkmz/installer/controllerD/MainD.java
UTF-8
2,357
2.21875
2
[]
no_license
package ru.bkmz.installer.controllerD; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import ru.bkmz.installer.util.ImageLoader; import ru.bkmz.installer.util.PaneNext; public class MainD { public ImageView imeg; public Button next; public Label TL; public CheckBox dDekctop; public CheckBox dGame; public CheckBox dSave; public CheckBox deleteAll; public AnchorPane rootPane; public void initialize() { imeg.setImage(ImageLoader.IMAGE_LOADER.getImage("img/fon_d")); } public static boolean bDGame = false; public static boolean bDSave = false; public static boolean bDDekctop = false; public static boolean bDeleteAll = false; public void next(ActionEvent actionEvent) { bDDekctop = dDekctop.isSelected(); bDGame = dGame.isSelected(); bDSave = dSave.isSelected(); bDeleteAll = deleteAll.isSelected(); new PaneNext(rootPane, "fxml/dezenstaler/delete.fxml"); } public void OnDDekctop(ActionEvent actionEvent) { allOn(); if (!dDekctop.isSelected()) { deleteAll.setSelected(false); } } public void onDGame(ActionEvent actionEvent) { allOn(); if (!dGame.isSelected()) { deleteAll.setSelected(false); } } public void onDSave(ActionEvent actionEvent) { allOn(); if (!dSave.isSelected()) { deleteAll.setSelected(false); } } public void onDeleteAll(ActionEvent actionEvent) { if (!deleteAll.isSelected()) { dDekctop.setSelected(false); dGame.setSelected(false); dSave.setSelected(false); deleteAll.setSelected(false); } else { dDekctop.setSelected(true); dGame.setSelected(true); dSave.setSelected(true); deleteAll.setSelected(true); } } void allOn() { if (dDekctop.isSelected() && dGame.isSelected() && dSave.isSelected()) { dDekctop.setSelected(true); dGame.setSelected(true); dSave.setSelected(true); deleteAll.setSelected(true); } } }
true
0489811b68b9d04de458abb01f480b6a3a41e071
Java
AlbertXe/xiang-xue-moudle
/my-springboot-autoconfig/src/main/java/com/config/HelloConfigProperties.java
UTF-8
424
1.90625
2
[]
no_license
package com.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @description: * @author: AlbertXe * @create: 2020-10-29 10:52 */ @ConfigurationProperties(prefix = "hello") public class HelloConfigProperties { private String msg; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
true
1241efee050f3b329adda2e87f538d26342021a4
Java
hishidama/asakusafw-wrapper-plugin
/plugin/src/jp/hishidama/eclipse_plugin/asakusafw_wrapper/jdt/hyperlink/DeclaredMasterSelectionHyperlink.java
UTF-8
1,091
2.171875
2
[]
no_license
package jp.hishidama.eclipse_plugin.asakusafw_wrapper.jdt.hyperlink; import java.text.MessageFormat; import jp.hishidama.eclipse_plugin.asakusafw_wrapper.internal.LogUtil; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.hyperlink.IHyperlink; public class DeclaredMasterSelectionHyperlink implements IHyperlink { private IJavaElement element; private IRegion region; public DeclaredMasterSelectionHyperlink(IJavaElement element, IRegion region) { this.element = element; this.region = region; } @Override public IRegion getHyperlinkRegion() { return region; } @Override public String getTypeLabel() { return "Open MasterSelection"; } @Override public String getHyperlinkText() { return "Open MasterSelection"; } @Override public void open() { try { JavaUI.openInEditor(element); } catch (Exception e) { LogUtil.logWarn(MessageFormat.format("{0} openEditor error.", getClass().getSimpleName()), e); } } }
true
3a88153b8e12cad9bc209c02ec43481a922ac94b
Java
kyle-love/student_homework_system
/JavaEE_01/src/main/java/org/example/javaee/class01/model/Homework.java
UTF-8
1,705
2.84375
3
[]
no_license
package org.example.javaee.class01.model; import java.sql.Date; import java.sql.Timestamp; import java.text.SimpleDateFormat; public class Homework { private Long id; private String homeworkTitle; private String homeworkContent; private java.util.Date createTime; private java.util.Date updateTime; public Homework(){ } public Homework(long homework_id, String homework_title) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //设置日期格式 java.util.Date date = new java.util.Date(); //System.out.println(df.format(date)); Date creat_time = new Date(date.getTime()); //uilt.Date this.createTime = creat_time; this.id = homework_id; this.homeworkTitle = homework_title; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getHomeworkTitle() { return homeworkTitle; } public void setHomeworkTitle(String homeworkTitle) { this.homeworkTitle = homeworkTitle; } public String getHomeworkContent() { return homeworkContent; } public void setHomeworkContent(String homeworkContent) { this.homeworkContent = homeworkContent; } public java.util.Date getCreateTime() { return createTime; } public void setCreateTime(java.util.Date createTime) { this.createTime = createTime; } public java.util.Date getUpdateTime() { return updateTime; } public void setUpdateTime(java.util.Date updateTime) { this.updateTime = updateTime; } }
true
7e2b1d3c4f652377a4c02b7117cf3ccdcb64c3b4
Java
Njanderson/Synapse-Repository-Services
/tools/tool-migration-utility/src/main/java/org/sagebionetworks/tool/migration/job/AWSInfo.java
UTF-8
710
2.234375
2
[]
no_license
package org.sagebionetworks.tool.migration.job; import com.amazonaws.auth.AWSCredentials; /** * Information need to work with S3 Objects. * @author John * */ public class AWSInfo { private AWSCredentials credentials = null; private String bucket = null; public AWSCredentials getCredentials() { return credentials; } public void setCredentials(AWSCredentials credentials) { this.credentials = credentials; } public String getBucket() { return bucket; } public void setBucket(String bucket) { this.bucket = bucket; } public AWSInfo(AWSCredentials credentials, String bucket) { super(); this.credentials = credentials; this.bucket = bucket; } }
true
e059b76095552a46a0d58a7d58a84da729027a82
Java
ZLBer/DaliyOfProgramme
/src/main/java/leetcode/leetcode500_999/leet806.java
UTF-8
492
2.828125
3
[]
no_license
package leetcode.leetcode500_999; public class leet806 { public int[] numberOfLines(int[] widths, String S) { int line=1; int temp=0; char []chars=S.toCharArray(); for(char c:chars){ temp+=widths[c-'a']; if (temp>100) { line++; temp=widths[c-'a']; } else if(temp==100){ temp=0; line++; } } return new int[]{line,temp}; } }
true
f69afca847902feebf295af817ebc4c5f6f28db2
Java
DhruvamSharma/Fidelity-ThinkFil
/thinkFIL/src/main/java/com/fil/thinkFIL/dao/models/User.java
UTF-8
2,752
2.125
2
[]
no_license
package com.fil.thinkFIL.dao.models; import java.util.ArrayList; import java.util.List; 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.ManyToMany; import javax.persistence.OneToMany; import org.hibernate.annotations.GeneratorType; import org.hibernate.annotations.ValueGenerationType; @Entity public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; @Column private String userName; @Column private String picture; @Column private String employeeName; @Column private String password; @Column private int rewardPoint; // @OneToMany(fetch=FetchType.EAGER) // @JoinColumn(name="corpId") // private List<Question> questions=new ArrayList<>(); // @OneToMany(fetch=FetchType.LAZY) // @JoinColumn(name="corpId") // private List<Answer> answers=new ArrayList<>(); // @ManyToMany(fetch=FetchType.EAGER) // @JoinColumn(name="corpId") // private List<Bookmark> bookmarks=new ArrayList<>(); public User() { super(); } public User(User user) { this.userName=user.getUserName(); this.employeeName=user.getEmployeeName(); this.rewardPoint=user.getRewardPoint(); this.id=user.getId(); this.picture=user.getPicture(); this.password=user.getPassword(); // TODO Auto-generated constructor stub } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public void setId(int id) { this.id = id; } private int getId() { // TODO Auto-generated method stub return 0; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getRewardPoint() { return rewardPoint; } public void setRewardPoint(int rewardPoint) { this.rewardPoint = rewardPoint; } // public List<Question> getQuestions() { // return questions; // } // public void setQuestions(List<Question> questions) { // this.questions = questions; // } // public List<Answer> getAnswers() { // return answers; // } // public void setAnswers(List<Answer> answers) { // this.answers = answers; // } // public List<Bookmark> getBookmark() { // return bookmarks; // } // public void setBookmark(List<Bookmark> bookmark) { // this.bookmarks = bookmark; // } }
true
f691525992c410a6c9c8e3249a505d22f464d38c
Java
NabasaPatrick/MessageDriven
/KafkaMessageDriven/src/main/java/com/example/KafkaMessageDriven/KafkaMessageDrivenApplication.java
UTF-8
612
1.78125
2
[]
no_license
package com.example.KafkaMessageDriven; import java.util.HashMap; import java.util.Map; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KafkaMessageDrivenApplication { public static void main(String[] args) { SpringApplication app = new SpringApplication(KafkaMessageDrivenApplication.class); Map<String, Object> map = new HashMap<>(); map.put("SERVER_PORT", "8081"); app.setDefaultProperties(map); app.run(args); //SpringApplication.run(KafkaMessageDrivenApplication.class, args); } }
true
6c97d4d5828171e7dddfc6634cbdcf3727c1bf79
Java
Avery246813579/TheAveryBot
/src/com/frostbyte/theaverybot/loading/bots/BotLoading.java
UTF-8
1,257
2.53125
3
[]
no_license
package com.frostbyte.theaverybot.loading.bots; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.frostbyte.theaverybot.sql.SqlHandler; import com.frostbyte.theaverybot.util.ObjectUtil; public class BotLoading { public static List<ActiveBot> bots = new ArrayList<ActiveBot>(); public void update(){ List<Map<String, Object>> tables = SqlHandler.byte_Bots.get(); List<ActiveBot> activeBots = new ArrayList<ActiveBot>(); for(Map<String, Object> table : tables){ ActiveBot activeBot = get(ObjectUtil.objectToInt(table.get("account_id"))); if(activeBot == null){ ActiveBot botActive = new ActiveBot(ObjectUtil.objectToInt(table.get("byte_id")), ObjectUtil.objectToInt(table.get("account_id"))); bots.add(botActive); activeBots.add(botActive); }else{ activeBots.add(activeBot); } } for(ActiveBot activeBot : bots){ if(!activeBots.contains(activeBot)){ activeBot.getBotManager().shutdown(); bots.remove(activeBot); break; } } } public ActiveBot get(int acccount_id){ for(ActiveBot activeBot : bots){ if(activeBot.getAccount_id() == acccount_id){ return activeBot; } } return null; } }
true
f2e0aab16029255dde5ca63409aac959e0c74da4
Java
FrankMbappe/Houser
/app/src/main/java/cm/btech2021/houser/adapters/HouseAdapter.java
UTF-8
3,657
2.40625
2
[]
no_license
package cm.btech2021.houser.adapters; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Locale; import cm.btech2021.houser.R; import cm.btech2021.houser.activities.DetailsActivity; import cm.btech2021.houser.models.HouseModel; public class HouseAdapter extends RecyclerView.Adapter<HouseAdapter.ViewHolder> { public static final String EXTRA_HOUSE_MODEL = "EXTRA_HOUSE_MODEL"; final ArrayList<HouseModel> houseModels; int layoutID; public HouseAdapter(ArrayList<HouseModel> houseModels, int layoutID) { this.houseModels = houseModels; this.layoutID = layoutID; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Context context = parent.getContext(); View view = LayoutInflater.from(context).inflate(layoutID, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { HouseModel houseModel = houseModels.get(position); final View view = holder.itemView; view.setOnClickListener(event -> { Context context = view.getContext(); Intent intent = new Intent(context, DetailsActivity.class); intent.putStringArrayListExtra(EXTRA_HOUSE_MODEL, houseModel.toShortStringArrayList()); context.startActivity(intent); }); if (holder.txtLikeCount != null) holder.txtLikeCount.setText(String.valueOf(houseModel.getLikeCount())); if (holder.imageHouseView != null) holder.imageHouseView.setImageResource(houseModel.getImageResourceId()); if (holder.imageHeartView != null) { if (houseModel.isLiked()) holder.imageHeartView.setImageResource(R.drawable.ic_heart_fill); else holder.imageHeartView.setImageResource(R.drawable.ic_heart_outline); } if (holder.txtTitle != null) holder.txtTitle.setText(houseModel.getTitle()); if (holder.txtSubTitle != null) holder.txtSubTitle.setText(houseModel.getAddress()); if (holder.txtPostedDate != null) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); holder.txtPostedDate.setText(simpleDateFormat.format(houseModel.getPostedDate())); } } @Override public int getItemCount() { return houseModels.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { ImageView imageHouseView; ImageView imageHeartView; TextView txtLikeCount; TextView txtTitle; TextView txtSubTitle; TextView txtPostedDate; public ViewHolder(@NonNull View itemView) { super(itemView); imageHouseView = itemView.findViewById(R.id.cardHouseImageView); imageHeartView = itemView.findViewById(R.id.cardHouseImageHeartView); txtLikeCount = itemView.findViewById(R.id.cardHouseTxtLikeCount); txtTitle = itemView.findViewById(R.id.cardNewHouseTitle); txtSubTitle = itemView.findViewById(R.id.cardNewHouseSubTitle); txtPostedDate = itemView.findViewById(R.id.cardNewHouseTxtDate); } } }
true
1074622440b988f3ee839dcf63e9c0bb2831c991
Java
ryangreenhall/intercept
/core/src/intercept/configuration/StubRequest.java
UTF-8
607
2.28125
2
[ "Apache-2.0" ]
permissive
package intercept.configuration; import intercept.model.UriMatcher; import static intercept.utils.UriMatchers.simpleMatcher; import java.util.Map; public class StubRequest { String path; String response; public void define(Map<UriMatcher, StubResponse> stubs) { UriMatcher key = simpleMatcher(path); stubs.put(key, new StubResponse(key, response)); } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public void setResponse(String response) { this.response = response; } }
true
f90bf92133a5f1f8d5dc6407053e38869448f991
Java
shaikji/algorithms
/ProblemSolving/src/com/jilani/graphs/MatrixProbability.java
UTF-8
875
3.609375
4
[]
no_license
package com.jilani.graphs; public class MatrixProbability { public static void main(String[] args) { int m = 5; int n = 5; int x = 1; int y = 1; int N = 2; System.out.println(" Matrix probability after N moves to reach the boundary = " + findProbability(m, n, x, y,N)); } static double findProbability( int m, int n, int x, int y, int N ) { if ( !isSafe(m, n, x, y)) { return 0.0; } if ( N == 0 ) return 1.0; double prob = 0.0; prob += findProbability(m, n, x-1, y, N-1) * 0.25; prob += findProbability(m, n, x-1, y, N-1) * 0.25; prob += findProbability(m, n, x, y-1, N-1) * 0.25; prob += findProbability(m, n, x, y+1, N-1) * 0.25; return prob; } static boolean isSafe ( int m, int n, int x, int y) { if ( (x >=0 && x < m) && (y >= 0 && y < n) ) return true; return false; } }
true
5da2c7bdc671049fb48f9b95e23445bc0e6f04f0
Java
benja-123/fisisacback
/src/main/java/com/fisisac/developer/fisisackback/service/impl/ClasificadorGastoServiceImpl.java
UTF-8
882
2.1875
2
[]
no_license
package com.fisisac.developer.fisisackback.service.impl; import java.util.ArrayList; import java.util.List; import com.fisisac.developer.fisisackback.domain.ClasificadorGasto; import com.fisisac.developer.fisisackback.repository.ClasificadorGastoRepository; import com.fisisac.developer.fisisackback.service.ClasificadorGastoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class ClasificadorGastoServiceImpl implements ClasificadorGastoService{ @Autowired ClasificadorGastoRepository clasificadorRepository; public List<ClasificadorGasto> getAllClasificadorGastos(){ List<ClasificadorGasto> clasificadores = new ArrayList<>(); clasificadorRepository.findAll().forEach(clasificador -> clasificadores.add(clasificador)); return clasificadores; } }
true
801be622f5f5a497669665fe2d88fe4d6691faac
Java
bennypickard/DvcCodeGit
/COMSC-255/asStatus/src/asStatus/Rectangle.java
UTF-8
845
3.3125
3
[]
no_license
package asStatus; import javax.swing.JOptionPane; public class Rectangle implements Status { //instance variables private double length; private double width; //constructor public Rectangle(double l, double w) { length = l; width = w; } //accessor methods public double getLength() { return length; } public double getWidth() { return width; } //other instance methods public double computeArea() { return (width * length);//return calculated area } public double computePerim() { return 2*(width+length);//return calculated perimeter } //Interface Fuctions public String getStatus() { String status = "Rectangle\nlength="+length+", width="+width+"\n"; return status; } public void displayStatus() { String status = getStatus(); JOptionPane.showMessageDialog(null, status); } }
true
45064d5b5e13e673251051884f7a381dec70232c
Java
lilonglai/citi
/webservice/src/main/java/com/lex/webservice/UserWebService.java
UTF-8
725
2.3125
2
[]
no_license
package com.lex.webservice; import javax.jws.HandlerChain; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import java.util.ArrayList; import java.util.List; @WebService @HandlerChain(file = "Handler.xml") public class UserWebService { public @WebResult(name = "User") User testUser(@WebParam(name = "name") String name) { return new UserRepository().findUser(name); } public @WebResult(name = "User") List<User> testUsers(@WebParam(name = "name") String name) { String[] array = name.split(","); List<User> l = new ArrayList<>(); for(String a: array){ l.add(new UserRepository().findUser(a)); } return l; } }
true
7446b8450b157b4c1a07fd334176ac35ddb6df6e
Java
gal-yedidovich/AndroidRepeaters
/MyNotifications/app/src/main/java/com/example/hackeru/mynotifications/NtfReceiver.java
UTF-8
1,943
2.34375
2
[]
no_license
package com.example.hackeru.mynotifications; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.Build; public class NtfReceiver extends BroadcastReceiver { private Context context; private NotificationManager ntfMngr; private static final int NTF_TWO = 2; @Override public void onReceive(Context context, Intent intent) { String data = intent.getStringExtra(NtfService.MY_DATA); //data from broadcast if (data != null) { this.context = context; this.ntfMngr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); this.sendNotif(data); } } private void sendNotif(String data) { Notification.Builder ntfBuilder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //API 26+ ntfBuilder = new Notification.Builder(context, MainActivity.NTF_CHANNEL); //reusing main activity channel } else { ntfBuilder = new Notification.Builder(context); } Notification ntf = ntfBuilder.setContentTitle("New Data") .setContentText(data) .setSmallIcon(R.mipmap.dollar) .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.dollar2)) .setAutoCancel(true) .setContentIntent(contentIntent(data)) .build(); ntfMngr.notify(NTF_TWO, ntf); } private PendingIntent contentIntent(String data) { Intent i = new Intent(context, NtfActivity.class); //explicit intent i.putExtra(NtfService.MY_DATA, data); return PendingIntent.getActivity(context, NTF_TWO, i, PendingIntent.FLAG_UPDATE_CURRENT); } }
true
ddf25fb6078171c72f7a150cfc57f34507551946
Java
RedFriend/jpa-mongo-demo
/knowledge-ws/src/main/java/com/taiji/knowledge/ws/vo/WsDict.java
UTF-8
1,753
2
2
[]
no_license
package com.taiji.knowledge.ws.vo; import java.util.Date; public class WsDict { private static final long serialVersionUID = -287369810087816750L; protected Long id; protected String createBy; protected Date createTime; protected String updateBy; protected Date updateTime; protected Integer enableFlag; /** * 类型 */ private String type; /** * 值 */ private Integer value; /** * 名字 */ private String name; /** * 备注 */ private String remark; /** * 获取类型 * * @return type - 类型 */ public String getType() { return type; } /** * 设置类型 * * @param type 类型 */ public void setType(String type) { this.type = type == null ? null : type.trim(); } /** * 获取值 * * @return value - 值 */ public Integer getValue() { return value; } /** * 设置值 * * @param value 值 */ public void setValue(Integer value) { this.value = value; } /** * 获取名字 * * @return name - 名字 */ public String getName() { return name; } /** * 设置名字 * * @param name 名字 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * 获取备注 * * @return remark - 备注 */ public String getRemark() { return remark; } /** * 设置备注 * * @param remark 备注 */ public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } }
true
2db6ea9f01af532521651b45a5f727db1bd5b921
Java
minyun02/Seoulmate-Spring-Project
/SeoulMate/src/main/java/com/seoulmate/home/dao/MateWriteDAO.java
UTF-8
1,565
1.882813
2
[]
no_license
package com.seoulmate.home.dao; import java.util.List; import com.seoulmate.home.vo.HouseMatePagingVO; import com.seoulmate.home.vo.ListVO; import com.seoulmate.home.vo.MateWriteVO; import com.seoulmate.home.vo.MemberVO; import com.seoulmate.home.vo.PropensityVO; public interface MateWriteDAO { //메이트 등록 public int mateInsert(MateWriteVO vo); //메이트 성향 no 가져오기 // public PropensityVO mateSelect(String userid); //메이트 수정 public int mateUpdate(MateWriteVO vo); //메이트 테이블 no 가져오기 // public int mateSelect(String userid); //matewrite 가져오기 public MateWriteVO mateSelect(String userid); //메이트 삭제 public int mateDel(int no, String userid); //메이트 사진 가져오기 public String[] MateProfilePic(String userid, int no); //matewrite 가져오기 (본인 작성글 아니여도) public MateWriteVO mateSelect2(int no); //메이트 인덱스에서 New 메이트 리스트 9개 출력하기 public List<MateWriteVO> getNewIndexMate(HouseMatePagingVO pVO); //메이트 희망지역 == 회원정보 희망지역 public int mateAreaUpdate(String area, String userid); // 페이징 토탈레코드수 구하기 public int mateTotalRecord(HouseMatePagingVO pVO); //메이트 글 카운트 public int mateCount(String userid); // 메이트 매칭 리스트 구하기 public List<ListVO> mateMatchList(HouseMatePagingVO pVO); // 메이트 매칭리스트 페이징 토탈레코드수 구하기 public int mateMatchTotal(HouseMatePagingVO pVO); }
true
6c60fd78ad5f2f4ef09ca78d6a2d0325c774b404
Java
yu1085/Software-Design-Pattern
/src/main/java/com/example/designPattern/享元模式/FlyweightPattern.java
UTF-8
2,156
3.71875
4
[]
no_license
package com.example.designPattern.享元模式; import java.util.HashMap; public class FlyweightPattern { public static void main(String[] args) { FlyweightFactory flyweightFactory = new FlyweightFactory(); Flyweight a = flyweightFactory.getFlyweight("a"); Flyweight b = flyweightFactory.getFlyweight("a"); Flyweight c = flyweightFactory.getFlyweight("a"); Flyweight d = flyweightFactory.getFlyweight("b"); Flyweight e = flyweightFactory.getFlyweight("b"); a.operation(new UnsharedConcreteFlyweight("第一次调用a.")); b.operation(new UnsharedConcreteFlyweight("第2次调用a.")); c.operation(new UnsharedConcreteFlyweight("第3次调用a.")); d.operation(new UnsharedConcreteFlyweight("第1次调用b.")); e.operation(new UnsharedConcreteFlyweight("第2次调用b.")); } } class UnsharedConcreteFlyweight { private String info; public UnsharedConcreteFlyweight(String info) { this.info = info; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } } interface Flyweight { public void operation(UnsharedConcreteFlyweight state); } class ConcreteFlyweight implements Flyweight { private String key; public ConcreteFlyweight(String key) { this.key = key; System.out.println("具体享元" + key + "被创建"); } @Override public void operation(UnsharedConcreteFlyweight state) { System.out.print("具体享元" + key + "被调用,"); System.out.println("非享元信息是:" + state.getInfo()); } } class FlyweightFactory { HashMap<String, Flyweight> hashMap = new HashMap<String, Flyweight>(); public Flyweight getFlyweight(String key) { Flyweight flyweight = (Flyweight) hashMap.get(key); if (flyweight != null) { System.out.println("具体享元" + key + "已经存在,被获取成功"); } else { flyweight = new ConcreteFlyweight(key); hashMap.put(key, flyweight); } return flyweight; } }
true
23feac9fed812e847af4c6b790d41847369d3adb
Java
killghost/framework
/framework-stock-commons/src/main/java/com/romaway/android/phone/cache/MinuteCacheHandlerMgr.java
UTF-8
2,781
2.375
2
[ "Apache-2.0" ]
permissive
package com.romaway.android.phone.cache; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import com.romaway.common.protocol.hq.HQFSZHProtocol; import com.romaway.common.protocol.hq.HQKXZHProtocol; /** * 异步存增量缓存数据 (目前没用,想改进效率同学可以研究,小心竞争问题。) * * @author qinyn * */ public class MinuteCacheHandlerMgr { private static MinuteCacheHandlerMgr instance = new MinuteCacheHandlerMgr(); public static MinuteCacheHandlerMgr getInstance() { return instance; } private static final int toSaveMinData = 0; private static final int toSelDwTime = 1; private SaveHandler handler; private MinRun minRun; public void toSaveMinData(HQFSZHProtocol ptl, String stockCode, String stockName, int marketId, int type) { if (handler == null) { HandlerThread thread = new HandlerThread("min"); thread.start(); handler = new SaveHandler(thread.getLooper()); } minRun = new MinRun(ptl, stockCode, stockName, marketId, type); handler.sendEmptyMessage(toSaveMinData); } public void toSelDwTime(String stockCode, int marketId) { HandlerThread thread = new HandlerThread("min"); thread.start(); SelRun run = new SelRun(stockCode, marketId); handler = new SaveHandler(thread.getLooper()); handler.sendEmptyMessage(toSelDwTime); } private class MinRun implements Runnable { private HQFSZHProtocol hqfszh; private String stockCode; private String stockName; private int marketId; private int stockType; public MinRun(HQFSZHProtocol ptl, String stockCode, String stockName, int marketId, int type) { this.hqfszh = ptl; this.stockCode = stockCode; this.stockName = stockName; this.marketId = marketId; this.stockType = type; } @Override public void run() { MinuteCacheUtil.getInstance().delStockData(stockCode, marketId); MinuteCacheUtil.getInstance().add(hqfszh, stockCode, stockName, marketId, stockType); handler.removeCallbacks(minRun); } } private class SelRun implements Runnable { private String stockCode; private int marketId; public SelRun(String stockCode, int marketId) { this.stockCode = stockCode; this.marketId = marketId; } @Override public void run() { // dwtime = MinuteCacheUtil.getInstance().selLastDwtime(stockCode, // marketId); } } private class SaveHandler extends Handler { public SaveHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case toSaveMinData: handler.post(minRun); break; case toSelDwTime: // handler default: break; } } } }
true
b3167ab4f732f6eb7f2c8c5484e37108fc0424a5
Java
zhongxingyu/Seer
/Diff-Raw-Data/31/31_9e01216a1dd28439935c934092463d486b2c18c4/Solution/31_9e01216a1dd28439935c934092463d486b2c18c4_Solution_s.java
UTF-8
1,925
3.5
4
[]
no_license
public class Solution { class Pair{ int left; int right; public Pair(int left, int right){ this.left = left; this.right =right; } } private ArrayList<ArrayList<Integer> >getFours(int [] num, List<Pair> srcPairs, List<Pair> destPairs){ ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>(); //this will make sure a<b<c<d for(Pair src: srcPairs) for(Pair dest:destPairs){ if(src.right < dest.left){ ArrayList<Integer> al = new ArrayList<Integer>(); al.add(num[src.left]); al.add(num[src.right]); al.add(num[dest.left]); al.add(num[dest.right]); all.add(al); } } return all; } public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { //if input is invalid, return empty results ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>> (); if(num == null || num.length < 4) return all; //sort first for removing duplicates in the future Arrays.sort(num); //building pair sum index map Map<Integer, List<Pair>> pairSumMap = new HashMap<Integer, List<Pair>>(); for(int i = 0; i < num.length; ++i) for(int j = i+1; j< num.length; ++j) { int sum = num[i] + num [j]; Pair pair = new Pair(i, j); if(!pairSumMap.containsKey(sum)){ pairSumMap.put(sum, new LinkedList<Pair>()); } List<Pair> pairList = pairSumMap.get(sum); pairList.add(pair); } //Finding two pairs sum to target for(Integer val : pairSumMap.keySet()){ //otherwise may cause duplicates if(val > target/2) continue; //no the other pair match if(!pairSumMap.containsKey(target- val)) continue; //src and dest List<Pair> srcPairs = pairSumMap.get(val); List<Pair> destPairs = pairSumMap.get(target-val); ArrayList<ArrayList<Integer>> al = getFours(num,srcPairs, destPairs); all.addAll(al); } return all; } }
true
1a243307fbf0b719f077c9aca6e582bc72322a11
Java
ADDYADAM/isd-voip
/inde/src/sip4me/gov/nist/siplite/stack/SIPServerRequestInterface.java
UTF-8
1,887
2.390625
2
[]
no_license
/******************************************************************************* * Product of NIST/ITL Advanced Networking Technologies Division (ANTD). * *******************************************************************************/ package sip4me.gov.nist.siplite.stack; import sip4me.gov.nist.siplite.message.Request; /** * An interface for a genereic message processor for SIP Request messages. * This is implemented by the application. The stack calls the message * factory with a pointer to the parsed structure to create one of these * and then calls processRequest on the newly created SIPServerRequest * It is the applications responsibility to take care of what needs to be * done to actually process the request. * *@version JAIN-SIP-1.1 * *@author M. Ranganathan <mranga@nist.gov> <br/> * *<a href="{@docRoot}/uncopyright.html">This code is in the public domain.</a> * */ public interface SIPServerRequestInterface { /** Get the channel to where to send the response * (the outgoing message channel). */ public MessageChannel getResponseChannel(); /** * Process the message. This incorporates a feature request * by Salvador Rey Calatayud <salreyca@TELECO.UPV.ES> * @param sipRequest is the incoming SIP Request. * @param incomingChannel is the incoming message channel (parameter * added in response to a request by Salvador Rey Calatayud.) * @throws SIPServerException Exception that gets thrown by * this processor when an exception is encountered in the * message processing. */ public void processRequest(Request sipRequest, MessageChannel incomingChannel ) throws SIPServerException ; /** Get processing information. * The stack queries processing information to add to the message log. * by calling this interface. Return null if no processing information * of interes thas been generated. */ public String getProcessingInfo(); }
true
25381a1d55691686565c1cb28c8f1de8cf72b9dd
Java
ajaybhat/Toy-Projects
/Assignment#3/src/com/airwatch/employee/EmployeeTest.java
UTF-8
4,237
3.78125
4
[]
no_license
package com.airwatch.employee; import java.util.*; /** * Created by ABhat on 12 Aug 2014 - 12/08/14. */ public class EmployeeTest { public static void main(String[] args) { Comparator<Employee> employeeComparator = new Comparator<Employee>() { @Override public int compare(Employee o1, Employee o2) { return (o1.getSalary() > o2.getSalary()) ? -1 : (o1.getSalary() < o2.getSalary()) ? 1 : 0; } }; Employee e1 = new Employee("Ajay", 2350, 30); Employee e2 = new Employee("Lazim", 3520, 31); Employee e3 = new Employee("Piya", 3520, 32); Employee e4 = new Employee("Ammu", 6320, 63); Employee e5 = new Employee("Sharon", 5120, 30); Employee e6 = new Developer("Jubin", 3320, 34); Employee e7 = new Developer("Sruthi", 2701, 31); Employee e8 = new Developer("Priyanka", 2604, 21); Developer e9 = new Developer("Tobit", 2021, 32); Developer e10 = new Developer("Arif", 2434, 32); Employee e11 = new QAEngineer("Alan", 2032, 31); Employee e12 = new QAEngineer("JK", 2704, 30); Employee e13 = new QAEngineer("Deepu", 2601, 29); QAEngineer e14 = new QAEngineer("Girish", 5202, 30); QAEngineer e15 = new QAEngineer("Athma", 2022, 31); List<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); employeeList.add(e5); employeeList.add(e6); employeeList.add(e7); employeeList.add(e8); employeeList.add(e9); employeeList.add(e10); employeeList.add(e11); employeeList.add(e12); employeeList.add(e13); employeeList.add(e14); employeeList.add(e15); //Creating a HashMap to store the details of employees HashMap<Integer, List<String>> employeeMap = new HashMap<Integer, List<String>>(); for (Employee e : employeeList) { List<String> names; int key = e.getAge(); if (employeeMap.containsKey(key)) { names = employeeMap.get(key); names.add(e.getName()); } else { names = new ArrayList<String>(); names.add(e.getName()); } employeeMap.put(key, names); } //Testing HashMap with null values // employeeMap.get(null);//exception thrown System.out.println(employeeMap.get(3944));//null o/p // employeeMap.put(21, null); //causes more than half of the values in the HashMap to become nulled + exception on reading below //Displaying the HashMap for (int key : employeeMap.keySet()) { List<String> names = employeeMap.get(key); System.out.println(key + " : " + Arrays.toString(names.toArray())); } //Using iterator to iterate over the employees list Iterator<Employee> employeeIterator = employeeList.iterator(); while (employeeIterator.hasNext()) { Employee employee = employeeIterator.next(); if (employee.getSalary() < 2500) employeeIterator.remove(); } Collections.sort(employeeList, employeeComparator); //Displaying list of employees with salary over 2500 for (Employee e : employeeList) { System.out.println(e); } //TreeSet test Employee emp1 = new Employee("ABC", 20000, 20); Employee emp2 = new Employee("ABC", 20000, 20); Employee emp3 = new Employee("ABC", 20000, 20); Employee emp4 = new Employee("ABC", 20000, 20); Employee emp5 = new Employee("ABC", 20000, 20); TreeSet<Employee> employeeTreeSet = new TreeSet<Employee>(); employeeTreeSet.add(emp1); employeeTreeSet.add(emp2); employeeTreeSet.add(emp3); employeeTreeSet.add(emp4); employeeTreeSet.add(emp5); /* For employee not done as comparable Exception in thread "main" java.lang.ClassCastException: com.airwatch.employee.Employee cannot be cast to java.lang.Comparable */ } }
true
5025d177ed63f5224518bc06e10cbb3dd2313c06
Java
yqdaddy/space
/space-service-zhouyi/src/main/java/com/huyouxiao/space/zhouyi/enums/BoneYearEnum.java
UTF-8
5,246
2.546875
3
[]
no_license
package com.huyouxiao.space.zhouyi.enums; /** * ganzhiList = ["甲子", "乙丑", "丙寅", "丁卯", "戊辰", "己巳", "庚午", "辛未", "壬申", "癸酉", "甲戌", "乙亥", * "丙子", "丁丑", "戊寅", "己卯", "庚辰", "辛巳", "壬午", "癸未", "甲申", "乙酉", "丙戌", "丁亥", * "戊子", "己丑", "庚寅", "辛卯", "壬辰", "癸巳", "甲午", "乙未", "丙申", "丁酉", "戊戌", "己亥", * "庚子", "辛丑", "壬寅", "癸卯", "甲辰", "乙巳", "丙午", "丁未", "戊申", "己酉", "庚戌", "辛亥", * "壬子", "癸丑", "甲寅", "乙卯", "丙辰", "丁巳", "戊午", "己未", "庚申", "辛酉", "壬戌", "癸亥"] * */ public enum BoneYearEnum { YEAR_AT_JIA_ZI(0,"鼠", "甲子", "一两二钱", 1, 2), YEAR_AT_BING_ZI(12,"鼠", "丙子", "一两六钱", 1, 6), YEAR_AT_WU_ZI(24, "鼠", "戊子", "一两五钱", 1, 5), YEAR_AT_GEN_ZI(36, "鼠", "庚子", "七钱", 0 ,7), YEAR_AT_REN_ZI(48, "鼠","壬子", "五钱", 0, 5), YEAR_OX_YI_COU(1,"牛", "乙丑", "九钱", 0,9), YEAR_OX_DING_COU(13,"牛", "丁丑", "八钱", 0, 8), YEAR_OX_JI_COU(25, "牛", "己丑", "七钱", 0, 7), YEAR_OX_XIN_COU(37,"牛", "辛丑", "七钱", 0, 7), YEAR_OX_GUI_COU(49, "牛", "癸丑", "七钱", 0, 7), YEAR_TIGER_BIN_YIN(2, "虎", "丙寅", "六钱", 0, 6), YEAR_TIGER_WU_YIN(14,"虎", "戊寅", "八钱", 0, 8), YEAR_TIGER_GEN_YIN(26,"虎", "庚寅", "九钱", 0, 9), YEAR_TIGER_REN_YIN(38,"虎", "壬寅", "九钱", 0, 9), YEAR_TIGER_JIA_YIN(50,"虎", "甲寅", "一两二钱", 1, 2), YEAR_RABBIT_DING_MAO(3,"兔", "丁卯", "七钱", 0, 7), YEAR_RABBIT_JI_MAO(15,"兔", "己卯", "一两九钱", 1, 9), YEAR_RABBIT_XIN_MAO(27, "兔", "辛卯", "一两二钱", 1, 2), YEAR_RABBIT_GUI_MAO(39, "兔", "癸卯", "一两二钱", 1, 2), YEAR_RABBIT_YI_MAO(51, "兔", "乙卯", "八钱", 0, 8), YEAR_DRAGON_WU_CHEN(4, "龙", "戊辰", "一两二钱", 1, 2), YEAR_DRAGON_GEN_CHEN(16, "龙", "庚辰", "一两二钱", 1, 2), YEAR_DRAGON_REN_CHEN(28, "龙", "壬辰", "一两", 1, 0), YEAR_DRAGON_JIA_CHEN(40, "龙", "甲辰", "八钱", 0, 8), YEAR_DRAGON_BIB_CHEN(52, "龙", "丙辰", "八钱", 0, 8), YEAR_SNAKE_JI_SI(5, "蛇", "己已", "五钱", 0, 5), YEAR_SNAKE_XIN_SI(17,"蛇", "辛已", "六钱", 0, 6), YEAR_SNAKE_GUI_SI(29,"蛇", "癸已", "七钱",0 ,7), YEAR_SNAKE_YI_SI(41,"蛇", "乙已", "七钱", 0, 7), YEAR_SNAKE_DING_SI(53, "蛇", "丁已", "六钱", 0 ,6), YEAR_HOURSE_GEN_WU(6, "马", "庚午", "九钱", 0, 9), YEAR_HOURSE_REN_WU(18, "马", "壬午", "八钱", 0, 8), YEAR_HOURSE_JIA_WU(30, "马", "甲午", "一两五钱", 1, 5), YEAR_HOURSE_BIN_WU(42, "马", "丙午", "一两三钱", 1, 3), YEAR_HOURSE_WU_WU(54, "马", "戊午", "一两九钱",1, 9), YEAR_GOAT_XIN_WEI(7, "羊", "辛未", "八钱", 0, 8), YEAR_GOAT_GUI_WEI(19, "羊", "癸未", "七钱", 0, 7), YEAR_GOAT_YI_WEI(31, "羊", "乙未", "六钱",0, 6), YEAR_GOAT_DING_WEI(43, "羊", "丁未", "五钱",0 ,5), YEAR_GOAT_JI_WEI(55, "羊", "己未", "六钱", 0, 6), YEAR_MONKEY_REN_SHEN(8,"猴", "壬申", "七钱", 0, 7), YEAR_MONKEY_JIA_SHEN(20,"猴", "甲申", "五钱", 0, 5), YEAR_MONKEY_BIN_SHEN(32, "猴", "丙申", "五钱", 0, 5), YEAR_MONKEY_WU_SHEN(44, "猴", "戊申", "一两四钱", 1, 4), YEAR_MONKEY_GEN_SHEN(56, "猴", "庚申", "八钱", 0 ,8), YEAR_ROOSTER_GUI_YOU(9, "鸡", "癸酉", "八钱", 0, 8), YEAR_ROOSTER_YI_YOU(21, "鸡", "乙酉", "一两五钱", 1, 5), YEAR_ROOSTER_DING_YOU(33,"鸡", "丁酉", "一两四钱", 1, 4), YEAR_ROOSTER_JI_YOU(45, "鸡", "己酉", "五钱", 0, 5), YEAR_ROOSTER_XIN_YOU(57, "鸡", "辛酉", "一两六钱", 1, 6), YEAR_DOG_JIA_XU(10, "狗", "甲戍", "一两五钱",1,5), YEAR_DOG_BIN_XU(22, "狗", "丙戍", "六钱",0 ,6 ), YEAR_DOG_WU_XU(34,"狗", "戊戍", "一两四钱" , 1,4), YEAR_DOG_GEN_XU(46, "狗", "庚戍", "九钱",0, 9), YEAR_DOG_REN_XU(58, "狗", "壬戍", "一两",1, 0), YEAR_PIG_YI_HAI(11, "猪", "乙亥", "九钱", 0, 9), YEAR_PIG_DING_HAI(23, "猪", "丁亥", "一两六钱",1,6), YEAR_PIG_JI_HAI(35, "猪", "己亥", "九钱",0, 9), YEAR_PIG_XIN_HAI(47, "猪", "辛亥", "一两七钱", 1, 7), YEAR_PIG_GUI_HAI(59, "猪", "癸亥", "六钱", 0 , 6), ; private int number; private String zodiac; private String yearName; private String weightName; private int liang; private int qian; private BoneYearEnum(int number, String zodiac, String yearName, String weightName, int liang, int qian) { this.number = number; this.zodiac = zodiac; this.yearName = yearName; this.weightName = weightName; this.liang = liang; this.qian = qian; } public static BoneYearEnum getByNumber(int number) { for (BoneYearEnum year : BoneYearEnum.values()) { if (year.number == number) { return year; } } return null; } public String getZodiac() { return zodiac; } public String getYearName() { return yearName; } public String getWeightName() { return weightName; } public int getLiang() { return liang; } public int getQian() { return qian; } }
true
70cfe61976736033f2cbfeb268fc6f6c009cf8b8
Java
Bessss-zyw/ebook
/bookstore_backend/src/main/java/com/reins/bookstore/service/BookService.java
UTF-8
1,235
2.3125
2
[]
no_license
package com.reins.bookstore.service; import com.reins.bookstore.constant.Constant; import com.reins.bookstore.dao.BookDao; import com.reins.bookstore.entity.Book; import com.reins.bookstore.entity.BookImage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BookService { @Autowired private BookDao bookDao; public Book findBookById(Integer id){ return bookDao.findOne(id); } public List<Book> getBooks() { return bookDao.getBooks(); } public void modifyBook(Book book){ bookDao.saveBook(book); } public boolean modifyBookImage(BookImage bookImage){ Book book = bookDao.findOne(bookImage.getId()); if (book == null) return false; bookDao.saveBookImage(bookImage); book.setImage(Constant.USE_BASE64); bookDao.saveBook(book); return true; } public void newBook(Book book){ bookDao.saveBook(book); } public boolean deleteBook(int id){ Book book = bookDao.findOne(id); if (book == null) return false; bookDao.removeBookAndImage(book); return true; } }
true
809b61adb67df634f4d44b16a7790451ce05bdfa
Java
byKyMy/Mlg-Rush-recoded
/src/main/java/me/byKyMy/mlgrush/Listener/NoPvP.java
UTF-8
487
2.015625
2
[]
no_license
package me.byKyMy.mlgrush.Listener; import me.byKyMy.mlgrush.gamestates.LobbyPhase; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; public class NoPvP implements Listener { @EventHandler public void onHit(EntityDamageByEntityEvent event){ if(LobbyPhase.lobbyPhase = true){ event.setCancelled(true); }else { event.setCancelled(false); } } }
true
9daab7ab596f57a8c4a187cef1bfd5df831676e2
Java
jwoolley/wrestler-mod
/src/main/java/thewrestler/cards/skill/Octopus.java
UTF-8
4,059
2.09375
2
[ "MIT" ]
permissive
package thewrestler.cards.skill; import basemod.abstracts.CustomCard; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.AbstractCreature; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.ArtifactPower; import com.megacrit.cardcrawl.vfx.combat.FlashAtkImgEffect; import thewrestler.enums.AbstractCardEnum; import thewrestler.powers.InjuredPower; import static thewrestler.WrestlerMod.getCardResourcePath; public class Octopus extends CustomCard { public static final String ID = "WrestlerMod:Octopus"; public static final String NAME; public static final String DESCRIPTION; public static final String[] EXTENDED_DESCRIPTION; public static final String IMG_PATH = "octopus.png"; private static final int DEBUFF_APPLICATIONS = 8; private static final int DEBUFF_AMOUNT_PER_APPLICATION = 1; private static final CardStrings cardStrings; private static final CardType TYPE = CardType.SKILL; private static final CardRarity RARITY = CardRarity.UNCOMMON; private static final CardTarget TARGET = CardTarget.NONE; private static final int COST = 1; public Octopus() { super(ID, NAME, getCardResourcePath(IMG_PATH), COST, getDescription(DEBUFF_APPLICATIONS, true), TYPE, AbstractCardEnum.THE_WRESTLER_ORANGE, RARITY, TARGET); this.baseMagicNumber = this.magicNumber = DEBUFF_AMOUNT_PER_APPLICATION; this.misc = DEBUFF_APPLICATIONS; this.exhaust = true; } @Override public void use(AbstractPlayer p, AbstractMonster m) { AbstractDungeon.actionManager.addToBottom(new OctopusAction(m, this.magicNumber, this.misc)); } private static class OctopusAction extends AbstractGameAction { private static final float EFFECT_DURATION = 0.01f; private final int numReps; public OctopusAction(AbstractCreature target, int amountPerRep, int numReps) { this.target = target; this.amount = amountPerRep; this.numReps = numReps; this.duration = EFFECT_DURATION; } public void update() { this.target = AbstractDungeon.getRandomMonster(); if (numReps <= 0 || this.target == null) { this.isDone = true; return; } if (!AbstractDungeon.getCurrRoom().monsters.areMonstersBasicallyDead()) { trigger(); AbstractDungeon.actionManager.addToBottom( new OctopusAction(this.target, this.amount, this.numReps - 1)); } else { AbstractDungeon.actionManager.clearPostCombatActions(); } this.isDone = true; } private void trigger() { AbstractDungeon.effectList.add(new FlashAtkImgEffect(this.target.hb.cX, this.target.hb.cY, AbstractGameAction.AttackEffect.BLUNT_LIGHT,this.target.hasPower(ArtifactPower.POWER_ID))); AbstractDungeon.actionManager.addToBottom( new ApplyPowerAction(this.target, AbstractDungeon.player, new InjuredPower(this.target, this.amount), this.amount)); } } @Override public AbstractCard makeCopy() { return new Octopus(); } @Override public void upgrade() { if (!this.upgraded) { this.upgradeName(); this.exhaust = false; this.rawDescription = getDescription(DEBUFF_APPLICATIONS, false); initializeDescription(); } } public static String getDescription(int numTimesApplied, boolean willExhaust) { return DESCRIPTION + numTimesApplied + (!willExhaust ? EXTENDED_DESCRIPTION[0] : EXTENDED_DESCRIPTION[1]); } static { cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); NAME = cardStrings.NAME; DESCRIPTION = cardStrings.DESCRIPTION; EXTENDED_DESCRIPTION = cardStrings.EXTENDED_DESCRIPTION; } }
true
9e752b341ef3597794d36eb9bb1089542421c2b8
Java
Kevinwong206/PCLabManagementSystem
/SoftwareModule.java
UTF-8
6,837
3.5
4
[]
no_license
import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class SoftwareModule { //create variables private ArrayList<Software> sArray; //stores current running objects private ArrayList<String> tempArray; private String[] softwareName = new String[100]; private int count; //default constructor to initialise variables public SoftwareModule() { sArray = new ArrayList<Software>(); tempArray = new ArrayList<String>(); count = 0; } //method to add the object to the arraylist public void addItemArrayList(Software aSoftware) { sArray.add(aSoftware); } //method to add the PCName into array public void addNameToArray(int sCount, String sName) { int sC = sCount - 1; softwareName[sC] = sName; } //Method to modify the array public void modifyArray(int choice, String sName) { int decision = choice - 1; softwareName[decision] = sName; } //Method to save array to text public void saveArraytoText() throws IOException { FileWriter p = new FileWriter("SoftwareName.txt"); PrintWriter c = new PrintWriter(p); //Loop to save the array for (int i = 0; i < softwareName.length; i++) { c.println(softwareName[i]); } c.close(); } //Method to delete the array public void deleteArray(int choice, String PCName) { int decision = choice - 1; for (int i = decision; i < softwareName.length; i++) { softwareName[decision] = softwareName[decision++]; } } //method to modify the arraylist based on the option user chooses public void modifyAList(int choice, Software aSoftware) { int decision = choice - 1; String tempString = aSoftware.toString(); tempArray.set(decision, tempString); } //method to save the data to tempArray public void saveToTempArray() throws IOException { File file = new File("Software.txt"); Scanner sc = new Scanner(file); //Clear the temp array if it is not empty if (!tempArray.isEmpty()) { tempArray.clear(); } while (sc.hasNextLine()) { tempArray.add(sc.nextLine()); } sc.close(); } //method to delete arraylist based on the option user chooses public void deleteAList(int choice) throws IOException { int decision = choice - 1; // use . remove to remove elemements in the array list tempArray.remove(decision); System.out.println("\nNumber " + choice + " element has been removed"); //write the tempArray to text file FileWriter fw = new FileWriter("Software.txt"); PrintWriter pw = new PrintWriter(fw); for (int i = 0; i < tempArray.size(); i++) { pw.println(tempArray.get(i)); } pw.close(); } //method to print the arraylist public void printArrayList() { try { //the file to be opened for reading FileInputStream fis = new FileInputStream("Software.txt"); Scanner sc = new Scanner(fis); //file to be scanned //returns true if there is another line to read while (sc.hasNextLine()) { System.out.println(sc.nextLine()); //returns the line that was skipped } sc.close(); //closes the scanner } catch (IOException e) { e.printStackTrace(); } } //method to save the object to Text File public void saveToFile(Software aSoftware) throws IOException { //Open filewriter and printWriter FileWriter fw = new FileWriter("Software.txt", true); PrintWriter pw = new PrintWriter(fw); pw.println(aSoftware); pw.close(); } //Method to save to file overwrite public void saveToFileOverWrite() throws IOException { FileWriter fw = new FileWriter("Software.txt"); PrintWriter pw = new PrintWriter(fw); for (int i = 0; i < tempArray.size(); i++) { pw.println(tempArray.get(i)); } pw.close(); } //Method to search from array list public int searchFromArrayList(String sName) { File file = new File("SoftwareName.txt"); int index = 0; try { Scanner scanner = new Scanner(file); //now read the file line by line. int lineNum = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains(sName)) { index = lineNum; } lineNum++; } } catch (FileNotFoundException e) { System.out.println("The software is not found in the database!"); } return index; } //Method to save PC to file public void saveToPCFile(String PCName, int position) throws IOException { FileWriter fw = new FileWriter(PCName + ".txt", true); PrintWriter pw = new PrintWriter(fw); pw.println(sArray.get(position)); pw.close(); } //Method to export to file public void exportToFile() throws IOException { FileWriter fw = new FileWriter("software.html"); PrintWriter pw = new PrintWriter(fw); //create html header pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head><title>PC details</title></head>"); pw.println("<body>"); //create table tag<table> and table header <th> pw.println("<table border=\"1\">"); pw.println("<tr><th>Software Name</th><th>Software type</th><th>Software expiration date</th><th>Software RAM</th></tr>"); int i = 0; //Iterate the array //print the content and <tr><td> tag for (Software aSoftware : sArray) { pw.println("<tr>"); pw.println("<td>" + sArray.get(i).getSoftwareName() + "</td>"); pw.println("<td>" + sArray.get(i).getSoftwareType() + "</td>"); pw.println("<td>" + sArray.get(i).getDate() + "</td>"); pw.println("<td>" + sArray.get(i).getRam() + "</td>"); pw.println("</tr>"); i++; } //close html document pw.println("</table>"); pw.println("</body>"); pw.println("</html>"); //close file stream System.out.println("The software details have been saved into pc.html file"); pw.close(); } }
true
51e2ba307869a45525e36ed35b31b4e2e6a46535
Java
Daclas95/PageObject-Project-B4
/src/test/java/test/plan/JobCatogoryTest.java
UTF-8
1,016
1.632813
2
[]
no_license
package test.plan; import com.pages.DashboardPage; import com.pages.admin.EmploymentStatus; import com.pages.admin.JobCatogoryPage; import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; import utils.TestBase; public class JobCatogoryTest extends TestBase { @Test public void employeeTest() { softAssert = new SoftAssert(); softAssert.assertTrue(DashboardPage.isHrmDashboardPageDisplayed(), "Hrm Dashboard Page Not Display"); softAssert.assertAll(); JobCatogoryPage.clickMenuJobcatogory(); JobCatogoryPage.clickJobcatogoryAdd(); JobCatogoryPage.setTxtjobcatogoryName("IT"); JobCatogoryPage.clickJobCatogorycancel(); JobCatogoryPage.clickJobcatogoryAdd(); JobCatogoryPage.setTxtjobcatogoryName("IT filed"); JobCatogoryPage.clickJobcatogorySave(); JobCatogoryPage.clickJobcatCheck(); JobCatogoryPage.clickJobCatconfirmdelete(); JobCatogoryPage.clickEmpstatusdelete(); } }
true
80c977408eb85e3e414cce85f424f177e1a74004
Java
emirchus/HiddenKiller
/src/main/java/dev/emir/managers/GameManager.java
UTF-8
2,771
2.46875
2
[]
no_license
package dev.emir.managers; import dev.emir.Main; import dev.emir.models.*; import dev.emir.utils.Encrypter; import dev.emir.utils.Multithreading; import org.bukkit.GameMode; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; public class GameManager extends ManagerModel<GameModel> { public GameManager() { load(); } public void save() { this.getList().forEach(GameModel::save); } public void load() { Multithreading.runAsync(new Runnable() { @Override public void run() { File dir = new File(Main.getInstance().getDataFolder().getPath().concat(File.pathSeparator + "games")); File[] files = dir.listFiles(File::isFile); if (files != null && files.length > 0) { Arrays.stream(files).forEach(file -> { try { BufferedReader bufferLectura; java.io.FileReader flujoLectura; String linea; if (file.exists()) { flujoLectura = new java.io.FileReader(file); bufferLectura = new BufferedReader(flujoLectura); StringBuilder ss = new StringBuilder(); linea = bufferLectura.readLine(); while (linea != null) { ss.append(linea); linea = bufferLectura.readLine(); } GameModel model = Main.gson.fromJson(Encrypter.decode(ss.toString(), 26), GameModel.class); model.setRollback(Main.getInstance().getWorldEdit().rollbacks.get(model.getGameName())); model.loadButton(); add(model); } } catch (IOException e) { e.printStackTrace(); } }); } } }); } public GameModel get(String identifier) { for (GameModel model : this.getList()) { if (model.getGameName().equals(identifier)) return model; } return null; } public GameModel getByPlayerName(String playerName) { for (GameModel model : this.getList()) { for (PlayerModel player : model.getPlayers()) { if (player.getPlayer().getDisplayName().equalsIgnoreCase(playerName)) return model; } } return null; } }
true
5052b3ed3809a3e776cabfa70a18fa820861e79f
Java
ShekharChoudhary/practice.java.puzzles
/src/threads/puzzles/StatiscticsAggregator.java
UTF-8
195
2.078125
2
[]
no_license
package threads.puzzles; public interface StatiscticsAggregator { void putNewPrice(String symbol, double price); double getAveragePrice(String symbol); int getTickCount(String symbol); }
true
06c9fba0453fcb9d7726be96e80ff5990de7eae6
Java
rlkb63569/community
/src/main/java/com/baizhi/controller/CommentController.java
UTF-8
1,901
2.1875
2
[]
no_license
package com.baizhi.controller; import com.baizhi.dto.CommentCreateDto; import com.baizhi.dto.CommentDto; import com.baizhi.dto.ResultDto; import com.baizhi.exception.CustomizeErrorCode; import com.baizhi.model.Comment; import com.baizhi.model.User; import com.baizhi.service.CommentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.List; @RestController @RequestMapping("/comment") public class CommentController { @Autowired private CommentService commentService; @RequestMapping(value="/add",method= RequestMethod.POST) public Object post(CommentCreateDto commentCreateDto, HttpServletRequest request){ User user = (User) request.getSession().getAttribute("user"); if(user==null){ return ResultDto.errorOf(CustomizeErrorCode.NO_LOGIN); } if(StringUtils.isEmpty(commentCreateDto.getContent())){ return ResultDto.errorOf(CustomizeErrorCode.COMMENT_IS_NULL); } Comment comment = new Comment(); comment.setParent_id(commentCreateDto.getParent_id()); comment.setContent(commentCreateDto.getContent()); comment.setType(commentCreateDto.getType()); comment.setGmt_create(System.currentTimeMillis()); comment.setGmt_modified(comment.getGmt_create()); comment.setCommentator(1); commentService.insert(comment); ResultDto resultDto = ResultDto.okOf(); return resultDto; } @ResponseBody @RequestMapping(value="/{id}",method=RequestMethod.GET) public ResultDto<List<CommentDto>> comment(@PathVariable(name="id") Long id){ List<CommentDto> commentDtos = commentService.getByCommentId(id); return ResultDto.okOf(commentDtos); } }
true
fa669da53104a47e705228c60960dbd02c3b0275
Java
onero/JavaFXComponents
/DigitalClock/src/digitalclock/gui/controller/DigitalClockMainController.java
UTF-8
2,401
2.84375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package digitalclock.gui.controller; import java.net.URL; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.ResourceBundle; import java.util.Timer; import java.util.TimerTask; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; /** * FXML Controller class * * @author gta1 */ public class DigitalClockMainController implements Initializable { @FXML private Label lblClock; private final StringProperty mTimerString; private Calendar mCalendar; private final Timer mTimer; private TimerTask mTimerTask; private static final String HOUR_MINUTE_SECONDS = "HH:mm:ss"; private static final String HOUR_MINUTE_SECONDS_MILLIS = "HH:mm:ss.SS"; private SimpleDateFormat sdf; public DigitalClockMainController() { mTimerString = new SimpleStringProperty(); mTimer = new Timer(true); } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { lblClock.textProperty().bind(mTimerString); handleNormal(); } @FXML private void handleNormal() { sdf = new SimpleDateFormat(HOUR_MINUTE_SECONDS); createTimerTask(1000, 1000); } @FXML private void handleMillis() { sdf = new SimpleDateFormat(HOUR_MINUTE_SECONDS_MILLIS); createTimerTask(1, 1); } @FXML private void handleExit() { System.exit(0); } /** * Create a timer task for the clock * * @param delayInMillis * @param periodInMillis */ private void createTimerTask(int delayInMillis, int periodInMillis) { mTimerTask = new TimerTask() { @Override public void run() { Platform.runLater(() -> { mCalendar = Calendar.getInstance(); mTimerString.setValue(sdf.format(mCalendar.getTime())); }); } }; mTimer.schedule(mTimerTask, delayInMillis, periodInMillis); } }
true
481e1af7f9e7a59953b79a5e1422fa610cdb2195
Java
duydatpham/react-native-tuya-minisdk
/android/src/main/java/com/hogar/tuyaminisdk/activator/TuyaActivatorModule.java
UTF-8
2,374
1.804688
2
[]
no_license
package com.hogar.tuyaminisdk.activator; import android.content.Intent; import android.os.Handler; import androidx.annotation.NonNull; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableMap; import com.tuya.smart.config.TuyaConfig; //#define kTuyaRNActivatorModuleHomeId @"homeId" // #define kTuyaRNActivatorModuleSSID @"ssid" // #define kTuyaRNActivatorModulePassword @"password" // #define kTuyaRNActivatorModuleActivatorMode @"type" // #define kTuyaRNActivatorModuleOverTime @"time" // #define kTuyaRNActivatorModuleAcccessToken @"token" // #define kTuyaRNActivatorModuleDeviceId @"devId" public class TuyaActivatorModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public TuyaActivatorModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @NonNull @Override public String getName() { return "TuyaActivatorModule"; } @ReactMethod public void initActivator(ReadableMap options) { String ssid = options.getString("ssid"); String password = options.getString("password"); String type = options.getString("type"); String token = options.getString("token"); if("TY_EZ".equals(type)) TuyaConfig.getEZInstance().startConfig(ssid,password,token); if("TY_AP".equals(type)) TuyaConfig.getAPInstance().startConfig(this.getReactApplicationContext(),ssid,password,token); } @ReactMethod public void newGwSubDevActivator(ReadableMap options) { String token = options.getString("token"); TuyaConfig.getWiredConfigInstance().startConfig(this.getReactApplicationContext(),token); } @ReactMethod public void stopConfig(){ TuyaConfig.getWiredConfigInstance().stopConfig(); TuyaConfig.getAPInstance().stopConfig(); TuyaConfig.getEZInstance().stopConfig(); } @ReactMethod public void openNetworkSettings(){ try { this.getCurrentActivity().startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS)); } catch (Exception e) { } } }
true
0e6fd18c06899cdd8aaab6b83f40ad7bbdd772f8
Java
teodorst/eim
/schelet/MyApplication/app/src/main/java/ro/pub/cs/systems/eim/scheletapplication/general/Constants.java
UTF-8
559
1.53125
2
[]
no_license
package ro.pub.cs.systems.eim.scheletapplication.general; public interface Constants { public final static boolean DEBUG = true; public final static String TAG = "Colocviu"; public final static String SERVER_HOST = "localhost"; public final static int SERVER_PORT = 2014; public final static String RESPONSE_FIELD = "relative_humidity"; public final static String API_SERVER = "http://api.wunderground.com/api/bdfed6464b1c8ba1/conditions/q/"; public final static String WEB_POST_SERVER_ADDRESS = "http://httpbin.org/post"; }
true
1d2859b03adc6db13b1cac29a1ccf44966ce1579
Java
skoopsk8/Conquest
/src/com/nasser/poulet/conquest/menu/Font.java
UTF-8
787
2.671875
3
[ "MIT" ]
permissive
package com.nasser.poulet.conquest.menu; import org.newdawn.slick.*; import org.newdawn.slick.Image; import java.awt.*; import java.util.Hashtable; import java.util.Map; /** * Created by Thomas on 12/30/13. */ public class Font { static public Map<String, TrueTypeFont> fonts = new Hashtable<String, TrueTypeFont>(); static public org.newdawn.slick.Font getFont(String font){ String[] fontValue = font.split(":"); if(!fonts.containsKey(font)){ System.out.println("Load font: "+font); fonts.put(font, new TrueTypeFont(new java.awt.Font(fontValue[0], java.awt.Font.TRUETYPE_FONT, Integer.parseInt(fontValue[1])), true)); } return fonts.get(font); } static public void destroy(){ fonts.clear(); } }
true
77f4cbdc57e5aa83d8b3df9f1146871b5f3f724b
Java
ruffy0002/anthena
/AnthenaPC/src/entity/Collectable.java
UTF-8
2,911
2.515625
3
[]
no_license
package entity; import javafx.geometry.Bounds; import javafx.scene.canvas.GraphicsContext; import javafx.scene.effect.BlendMode; import javafx.scene.effect.Bloom; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import resource.Resources; public class Collectable extends Sprite { private static final double[][] FRAME_POSITION = new double[7][2]; private static final double FRAME_WIDTH = 100; private static final double FRAME_HEIGHT = 170; public static final double DRAW_WIDTH = 50; public static double DRAW_HEIGHT; private static double animationLength = 7; private static double animationSpeed = 40; private static double frameSpeed = animationLength / animationSpeed; private double timeElapse = 0; private boolean isActive = true; private static Bloom bloom = new Bloom(); public static void initMain() { bloom.setThreshold(0.3); FRAME_POSITION[0][0] = 0; FRAME_POSITION[0][1] = 0; FRAME_POSITION[1][0] = FRAME_WIDTH; FRAME_POSITION[1][1] = 0; FRAME_POSITION[2][0] = FRAME_WIDTH * 2; FRAME_POSITION[2][1] = 0; FRAME_POSITION[3][0] = FRAME_WIDTH * 3; FRAME_POSITION[3][1] = 0; FRAME_POSITION[4][0] = FRAME_WIDTH * 2; FRAME_POSITION[4][1] = 0; FRAME_POSITION[5][0] = FRAME_WIDTH; FRAME_POSITION[5][1] = 0; FRAME_POSITION[6][0] = 0; FRAME_POSITION[6][1] = 0; DRAW_HEIGHT = DRAW_WIDTH / FRAME_WIDTH * FRAME_HEIGHT; } public Collectable(double x, double y) { init(x,y); } public void init(double x, double y) { super.setScaleXY(1, 1); super.setWidth(DRAW_WIDTH); super.setHeight(DRAW_HEIGHT); super.setPositionX(x); super.setPositionY(y); super.setVelocityX(0); super.setRotationAngle(0); currentAnimationFrame = 0; super.setMovingFrames(Resources.getCollectable(0)); calculateBoundary(); } private void calculateBoundary() { double boundaryWidth = width; double boundaryHeight = height * 0.3; double boundaryX = positionX; double boundaryY = positionY + (height - boundaryHeight); super.collisionZone = new Rectangle(boundaryX, boundaryY, boundaryWidth, boundaryHeight); } public void render(GraphicsContext gc) { gc.save(); gc.setGlobalBlendMode(BlendMode.SRC_OVER); gc.setEffect(bloom); gc.drawImage(movingStateFrames, FRAME_POSITION[currentAnimationFrame][0], FRAME_POSITION[currentAnimationFrame][1], FRAME_WIDTH, FRAME_HEIGHT, positionX, positionY, displayWidth, displayHeight); gc.restore(); } public void update(double time) { timeElapse += time; if (timeElapse > frameSpeed) { timeElapse = timeElapse - frameSpeed; currentAnimationFrame++; if (currentAnimationFrame > animationLength - 1) { currentAnimationFrame = 0; } } } public void disable() { isActive = false; } public boolean isActive() { return isActive; } }
true
14c253706f929a2d42be1d33e3931422e29acd59
Java
moutainhigh/scanPosp
/src/main/java/com/epay/scanposp/common/utils/slf/vo/DeductInfo.java
UTF-8
2,201
2.25
2
[]
no_license
package com.epay.scanposp.common.utils.slf.vo; /** * 支付信息对象 * @author administrator * */ public class DeductInfo { private String payOrderId = ""; private String payAmt = ""; private String payTime = ""; private String payStatus = ""; private String payDesc = ""; private String xml=""; /** * 取得支付订单号 * @return 支付订单号 */ public String getPayOrderId() { return payOrderId; } /** * 设置支付订单号 * @param payOrderId 支付订单号 */ public void setPayOrderId(String payOrderId) { this.payOrderId = payOrderId; } /** * 取得支付金额 * @return 支付金额 */ public String getPayAmt() { return payAmt; } /** * 设置支付金额 * @param payAmt 支付金额 */ public void setPayAmt(String payAmt) { this.payAmt = payAmt; } /** * 取得支付时间 * @return 得支付时间 */ public String getPayTime() { return payTime; } /** * 设置得支付时间 * @param payTime 得支付时间 */ public void setPayTime(String payTime) { this.payTime = payTime; } /** * 取得支付状态 * @return 支付状态 */ public String getPayStatus() { return payStatus; } /** * 设置支付状态 * @param payStatus 支付状态 */ public void setPayStatus(String payStatus) { this.payStatus = payStatus; } /** * 取得支付描述 * @return 支付描述 */ public String getPayDesc() { return payDesc; } /** * 支付描述 * @param payDesc 支付描述 */ public void setPayDesc(String payDesc) { this.payDesc = payDesc; } /** * 取得xml报文 * @return xml报文 */ public String getXml() { return xml; } /** * 设置xml报文 * @param xml xml报文 */ public void setXml(String xml) { this.xml = xml; } public String toString(){ String temp = ""; temp = temp + "payOrderId="+payOrderId+"\n"; temp = temp + "payAmt="+payAmt+"\n"; temp = temp + "payTime="+payTime+"\n"; temp = temp + "payStatus="+payStatus+"\n"; temp = temp + "payDesc="+payDesc+"\n"; temp = temp + "xml="+xml+"\n"; return temp; } }
true
f415c3dc8151e0e04a8f82b156f00a486965b987
Java
zhonglh/logisticsc
/logisticsc/src/main/java/com/brightsoft/controller/tms/platform/financialmanager/FinancialManagerController.java
UTF-8
14,330
1.671875
2
[]
no_license
package com.brightsoft.controller.tms.platform.financialmanager; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.brightsoft.common.constants.DictionaryType; import com.brightsoft.common.constants.SystemConstant; import com.brightsoft.controller.base.BaseController; import com.brightsoft.controller.vo.BaseSearchParams; import com.brightsoft.controller.vo.ReceivablePayBillSearchParams; import com.brightsoft.controller.vo.SearchParams; import com.brightsoft.controller.vo.WayBillSearchParams; import com.brightsoft.model.DepositRatio; import com.brightsoft.model.InsteadCollectMoney; import com.brightsoft.model.MoneyDiaryRecord; import com.brightsoft.model.OutletsInfo; import com.brightsoft.model.PlatformDictionary; import com.brightsoft.model.ReceivablePayBillRecord; import com.brightsoft.model.TakeCashApply; import com.brightsoft.model.User; import com.brightsoft.model.lineAdvanceMoneyRecord; import com.brightsoft.model.receiveMoneyRecord; import com.brightsoft.repeat.RepeatSubmission; import com.brightsoft.service.platform.DictionaryService; import com.brightsoft.service.system.platform.TakeCashApplyService; import com.brightsoft.service.tms.platform.DepositRatioService; import com.brightsoft.service.tms.platform.LineInfoService; import com.brightsoft.service.tms.platform.OutletsService; import com.brightsoft.service.tms.platform.financialmanager.InsteadCollectMoneyService; import com.brightsoft.service.tms.platform.financialmanager.LineAdvanceMoneyRecordService; import com.brightsoft.service.tms.platform.financialmanager.MoneyDiaryRecordService; import com.brightsoft.service.tms.platform.financialmanager.ReceivablePayBillRecordService; import com.brightsoft.service.tms.platform.financialmanager.ReceivablePayBillService; import com.brightsoft.service.tms.platform.financialmanager.ReceiveMoneyRecordService; import com.brightsoft.service.tms.platform.startsitemanager.WayBillOrderService; /** * 财务管理 * @author yangshoubao * */ @Controller @RequestMapping("/tms/financial") public class FinancialManagerController extends BaseController{ @Autowired private ReceiveMoneyRecordService receiveMoneyRecordService; @Autowired private LineInfoService lineInfoService; @Autowired private OutletsService outletsService; @Autowired private LineAdvanceMoneyRecordService advanceMoneyRecordService; @Autowired private MoneyDiaryRecordService moneyDiaryRecordService; @Autowired private DictionaryService dictionaryService; @Autowired private WayBillOrderService wayBillOrderService; @Autowired private InsteadCollectMoneyService insteadCollectMoneyService; @Autowired private ReceivablePayBillService receivablePayBillService; @Autowired private ReceivablePayBillRecordService receivablePayBillRecordService; @Autowired private TakeCashApplyService takeCashApplyService; @Autowired private DepositRatioService depositRatioService; /** * 跳转到 财务管理-应收款页面 * @return */ @RequestMapping("/toreceivableaccount") public String toReceivableAccountPage(HttpServletRequest request){ User user = (User)request.getSession().getAttribute(SystemConstant.TMS_USER_SESSION); Long outletsId = user.getOutletsId(); if(outletsId != null){ OutletsInfo outletsInfo = outletsService.selectById(outletsId); request.setAttribute("outletsName", outletsInfo.getName()); } List<OutletsInfo> outletsInfos = outletsService.selectByCompanyId(user.getCompanyId()); request.setAttribute("outletsInfos", outletsInfos); return "/tms/platform/financialmanager/receivable-account"; } /** * 添加收款记录 * @param receiveMoneyRecord * @return */ @RequestMapping("/addreceivemoneyrecord") @ResponseBody public String addReceiveMoneyRecord(receiveMoneyRecord receiveMoneyRecord, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); receiveMoneyRecord.setOutletsId(user.getOutletsId()); receiveMoneyRecord.setOperatePerson(user.getId()); int rows = receiveMoneyRecordService.insertReceiveMoneyRecord(receiveMoneyRecord); if(rows > 0){ return SUCCESS_STATUS; } return FAILURE_STATUS; } /** * 获取收款记录 * @param departNumber * @return */ @RequestMapping("/getreceivemoneyrecordbydepartnumber") @ResponseBody public Object getReceiveMoneyRecordByDepartNumber(String departNumber){ return receiveMoneyRecordService.selectByDepartNumber(departNumber); } /** * 跳转到 财务管理-预付款页面 * @return */ @RequestMapping("/toadvancemoneypage") public String toAdvanceMoneyPage(HttpServletRequest request){ DepositRatio depositRatio = depositRatioService.selectCurrentDeposit(); request.setAttribute("depositRatio", depositRatio); return "/tms/platform/financialmanager/advance-money"; } /** * 获取线路信息 * @return */ @RequestMapping("/getlineinfos") @ResponseBody public Object getLineInfos(HttpSession session, BaseSearchParams params){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); Long outletsId = user.getOutletsId(); if(outletsId == null){ return null; } params.setOutletsId(outletsId); return lineInfoService.selectByParams(params); } /** * 添加 线路充值 记录 * @param lineAdvanceMoneyRecord * @return */ @RequestMapping("/addlineadvancemoneyrecord") @ResponseBody public String addLineAdvanceMoneyRecord(lineAdvanceMoneyRecord lineAdvanceMoneyRecord){ int rows = advanceMoneyRecordService.insert(lineAdvanceMoneyRecord); if(rows > 0){ return SUCCESS_STATUS; } return FAILURE_STATUS; } /** * 获取线路充值记录 * @param lineId * @return */ @RequestMapping("/getlineadvancemoneyrecord") @ResponseBody public Object getLineAdvanceMoneyRecord(String lineId){ return advanceMoneyRecordService.selectByLineId(lineId); } /** * 跳转到 财务管理-现金日记页面 * @return */ @RequestMapping("/tomoneydiarypage") public String toMoneyDiaryPage(HttpServletRequest request){ List<PlatformDictionary> dictionaries = dictionaryService.selectDictDataByType(DictionaryType.COST_SUBJECT); request.setAttribute("dictionaries", dictionaries); User user = (User)request.getSession().getAttribute(SystemConstant.TMS_USER_SESSION); Long outletsId = user.getOutletsId(); if(outletsId != null){ request.setAttribute("outletsInfo", outletsService.selectById(outletsId)); } return "/tms/platform/financialmanager/money-diary"; } /** * 获取 现金日记 列表 * @param searchParams * @return */ @RequestMapping("/getmoneydiarylist") @ResponseBody public Object getMoneyDiaryList(SearchParams searchParams, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); Long outletsId = user.getOutletsId(); if(outletsId == null){ return null; } searchParams.setOutletsId(user.getOutletsId()); return moneyDiaryRecordService.selectByParams(searchParams); } /** * 添加现金日记 记录 * @param moneyDiaryRecord * @return */ @RequestMapping("/addmoneydiaryrecord") @ResponseBody public String addMoneyDiaryRecord(MoneyDiaryRecord moneyDiaryRecord, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); int rows = 0; try { moneyDiaryRecord.setOutletsId(user.getOutletsId()); moneyDiaryRecord.setOperatePerson(user.getId()); rows = moneyDiaryRecordService.insert(moneyDiaryRecord); } catch (Exception e) { e.printStackTrace(); } if(rows > 0){ return SUCCESS_STATUS; } return FAILURE_STATUS; } /** * 跳转到网点对账 页面 * @return */ @RequestMapping("/tooutletscheckaccountpage") public String toOutletsCheckAccountPage(HttpServletRequest request){ User user = (User)request.getSession().getAttribute(SystemConstant.TMS_USER_SESSION); List<OutletsInfo> outletsInfos = outletsService.selectByCompanyId(user.getCompanyId()); request.setAttribute("outletsInfos", outletsInfos); Long outletsId = user.getOutletsId(); if(outletsId != null){ OutletsInfo outletsInfo = outletsService.selectById(outletsId); request.setAttribute("outletsInfo", outletsInfo); } return "/tms/platform/financialmanager/outlets-check-account"; } /** * 跳转到代收货款 页面 * @return */ @RequestMapping("/toinsteadcollectmoneypage") public String toInsteadCollectMoneyPage(HttpServletRequest request){ User user = (User)request.getSession().getAttribute(SystemConstant.TMS_USER_SESSION); List<OutletsInfo> outletsInfos = outletsService.selectByCompanyId(user.getCompanyId()); Long outletsId = user.getOutletsId(); if(outletsId != null){ OutletsInfo outletsInfo = outletsService.selectById(user.getOutletsId()); request.setAttribute("outletsInfo", outletsInfo); } request.setAttribute("outletsInfos", outletsInfos); return "/tms/platform/financialmanager/instead-collect-money"; } /** * 查询代收货款运单列表 * @param params * @return */ @RequestMapping("/getinsteadcollectmoneywaybilllist") @ResponseBody public Object getInsteadCollectMoneyWayBillList(WayBillSearchParams params, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); Long outletsId = user.getOutletsId(); if(outletsId == null){ return null; } params.setTargetOutlets(outletsId); params.setIsAgencyFund("1"); return wayBillOrderService.selectByParams(params); } /** * 添加 代收款 记录 * @param insteadCollectMoney * @return */ @RequestMapping("/addinsteadcollectmoney") @ResponseBody public String addInsteadCollectMoney(InsteadCollectMoney insteadCollectMoney, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); insteadCollectMoney.setOperatePerson(user.getId()); int rows = 0; try { rows = insteadCollectMoneyService.insert(insteadCollectMoney); } catch (Exception e) { e.printStackTrace(); } if(rows > 0){ return SUCCESS_STATUS; } return FAILURE_STATUS; } /** * 获取代收货款列表 * @param wayBillNumber 运单号 * @return */ @RequestMapping("/getinsteadcollectmoneylist") @ResponseBody public Object getInsteadCollectMoneyList(String wayBillNumber){ return insteadCollectMoneyService.selectByWayBillNumber(wayBillNumber); } /** * 跳转到 专线钱包页面 * @return */ @RequestMapping("/tolinewalletpage") public String toLineWalletPage(){ return "/tms/platform/financialmanager/line-wallet"; } /** * 跳转到 应付款订单表页面 * @return */ @RequestMapping("/toreceivablepayrecord") @RepeatSubmission(needSaveToken = true) public String toReceivablePayRecordPage(HttpServletRequest request){ List<PlatformDictionary> dictionaries = dictionaryService.selectDictDataByType(DictionaryType.COST_SUBJECT); request.setAttribute("dictionaries", dictionaries); return "/tms/platform/financialmanager/receivable-payrecord"; } /** * 跳转到 应付款页面 * @return */ @RequestMapping("/toreceivablepay") @RepeatSubmission(needSaveToken = true) public String toReceivablePayPage(HttpServletRequest request){ List<PlatformDictionary> dictionaries = dictionaryService.selectDictDataByType(DictionaryType.COST_SUBJECT); request.setAttribute("dictionaries", dictionaries); return "/tms/platform/financialmanager/receivable-pay"; } /** * 获取 应付款 列表 * @param session * @return */ @RequestMapping("/getreceivablepaybill") @ResponseBody public Object getReceivablePayBill(HttpSession session, ReceivablePayBillSearchParams params){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); if(user.getOutletsId() == null||user.getOutletsId().equals("")){ List<OutletsInfo> outs =outletsService.selectOutlesNotBind(user.getCompanyId()); String ids = ""; for(int i =0;i<outs.size();i++){ if(i == 0){ ids += outs.get(i).getId(); }else{ ids += ","+outs.get(i).getId(); } } if(outs == null || outs.size() == 0){ params.setOutletsIds("no"); }else{ params.setOutletsIds(ids); } }else{ params.setOutletsIds(user.getOutletsId()+""); } return receivablePayBillService.selectByParams(params); } /** * 保存 应收款 账单 收款记录 * @param receivablePayBillRecord * @return */ @RequestMapping("/savereceivablepaybillrecord") @ResponseBody @RepeatSubmission(needUpdateToken = true) public String saveReceivablePayBillRecrod(ReceivablePayBillRecord receivablePayBillRecord, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); receivablePayBillRecord.setOperatePerson(user.getId()); int rows = receivablePayBillRecordService.insert(receivablePayBillRecord, user); if(rows > 0){ return SUCCESS_STATUS; } return FAILURE_STATUS; } /** * 查询 应收款 账单 收款记录 * @param receivablePayBillRecord * @return */ @RequestMapping("/getreceivablepaybillrecord") @ResponseBody public Object getReceivablePayBillRecrod(String billId){ return receivablePayBillRecordService.selectByBillId(billId); } /** * 跳转到订单退款页面 * @return */ @RequestMapping("/toorderrefundpage") public String toOrderRefundPage(){ return "/tms/platform/financialmanager/order-refund"; } /** * 跳转到运单统计页面 * @return */ @RequestMapping("/towaybillanalysepage") public String toWayBillAnalysePage(){ return "/tms/platform/financialmanager/way-bill-analyse"; } /** * 保存 提现申请 * @param takeCashApply * @return */ @RequestMapping("/savetakecashapply") @ResponseBody public String saveTakeCashApply(TakeCashApply takeCashApply, HttpSession session){ User user = (User)session.getAttribute(SystemConstant.TMS_USER_SESSION); takeCashApply.setUserId(user.getId()); int rows = takeCashApplyService.save(takeCashApply); if(rows > 0){ return SUCCESS_STATUS; } return FAILURE_STATUS; } }
true
b088d6042c7f2709fc7bf8d822ac7c3f5ea480a3
Java
extFM/extFM-Tooling
/tests/org.js.model.feature.test/src/test/java/org/js/model/feature/TestModel.java
UTF-8
1,848
1.992188
2
[]
no_license
package org.js.model.feature; import java.io.IOException; import java.net.URL; import java.util.Collections; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource.Factory; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import org.js.model.feature.FeatureModel; import org.js.model.feature.resource.eft.mopp.EftResourceFactory; public class TestModel { private FeatureModel featureModel; private ResourceSet resourceSet = new ResourceSetImpl(); public TestModel() { loadTestModels(); } private void loadTestModels() { featureModel = (FeatureModel) loadTestModel("smallfm.eft", "eft", new EftResourceFactory()); } private EObject loadTestModel(String filename, String suffix, Factory resourceFactory) { resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(suffix, resourceFactory); URL fileresource = this.getClass().getClassLoader().getResource(filename); String path = fileresource.getPath(); URI uri = URI.createFileURI(path); Resource resource = resourceSet.getResource(uri, true); try { resource.load(Collections.EMPTY_MAP); System.out.println("Loaded " + uri); EList<EObject> contents = resource.getContents(); if (contents != null && !contents.isEmpty()) { return contents.get(0); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } FeatureModel getFMTestModel() { return featureModel; } }
true
17e53b287638ca4f673d65a9168922fb06b431f0
Java
TheArchitect123/Xcode-Portfolio-Projects
/SWAPIConsumer.Droid/app/src/main/java/ui/activities/DashboardActivity.java
UTF-8
1,455
1.921875
2
[ "MIT" ]
permissive
package ui.activities; import android.content.ComponentName; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.dg.swapiconsumer.R; import ui.view_bindings.DashboardBindings; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import butterknife.BindView; import view_models.pages.DashboardViewModel; public class DashboardActivity extends AppCompatActivity { //The view model will contain a reference to the view model, on initialization DashboardViewModel viewModel; @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch(item.getItemId()){ case 0: //Dashboard Items //Render the dashboard elements, and refresh the items from the database break; default: //Settings Items break; } return super.onOptionsItemSelected(item); } @Override protected void onPause() { super.onPause(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.setSupportActionBar(viewModel.getBindings().getDashboardToolbar()); } }
true
c712ff654a35f13e5e969f5d2165fce49c036c49
Java
ngotruongtn99/Rocket_13
/Java/Assignment 5/TestingSystem_Assignment_5/src/com/vti/entity/Ex1/Q2/Student.java
UTF-8
698
3.171875
3
[]
no_license
package com.vti.entity.Ex1.Q2; public class Student { private int id; private String name; private String address; private int priority; private KhoiThi khoiThi; public int getId() { return id; } private static int CODE = 0; public Student(String name, String address, int priority, KhoiThi khoiThi) { CODE++; this.id = CODE; this.name = name; this.address = address; this.priority = priority; this.khoiThi = khoiThi; } @Override public String toString() { return "Student \nID:" + CODE +"\nHọ tên: " + name + "\nĐịa chỉ: " + address + "\nMức ưu tiên: " + priority + "\nKhối Thi: " + khoiThi.getName() +"\nMôn thi: " + khoiThi.getSubject(); } }
true
3bb182b20affff67a4ac64c7cbc9b296bd5ee0a5
Java
skchaudhary/Data-Structure-Algorithms
/CompanyPreparation/src/main/java/com/studypoint/hackerEarth/byju/ManHattanMatrix.java
UTF-8
2,362
3.03125
3
[]
no_license
package com.studypoint.hackerEarth.byju; import com.learn.util.MyReader; import java.util.*; public class ManHattanMatrix { static MyReader mr; public static void main(String[] args) { mr=new MyReader(); int t=mr.nextInt(); while (t-->0){ int m=mr.nextInt(); int n=mr.nextInt(); int[][] arr=new int[m][n]; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ arr[i][j]=mr.nextInt(); } } Graph graph=new Graph(m*n); makeAdjList(graph, arr, m, n); int src=(mr.nextInt()-1)*m+(mr.nextInt()-1); findDist(src, graph, m, n); int q=mr.nextInt(); for (int i=0;i<q;i++){ int dest=(mr.nextInt()-1)*m+(mr.nextInt()-1); System.out.println(graph.d[dest]); } } } private static void findDist(int src, Graph graph, int m, int n) { Queue<Integer> q=new LinkedList<>(); boolean[] visited=new boolean[m*n]; Arrays.fill(visited, false); q.offer(src); graph.d[src]=0; while (!q.isEmpty()){ int u=q.poll(); for (int v:graph.adjList[u]){ if (!visited[v]){ visited[v]=true; q.offer(v); graph.d[v]=graph.d[u]+1; } } } } private static void makeAdjList(Graph graph, int[][] arr, int m, int n) { for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ for(int k=0;k<m;k++){ for(int l=0;l<n;l++){ if (k!=i && l!=j){ int mh=Math.abs(i-k)+Math.abs(j-l); if (mh==arr[i][j]) graph.adjList[i*n+j].add(k*n+l); } } } } } } static class Graph{ int v; List<Integer>[] adjList; int[] d; Graph(int v){ this.v=v; d=new int[v]; adjList=new List[v]; for (int i=0;i<v;i++){ d[i]=-1; adjList[i]=new ArrayList<>(); } } } } /** * byju1.txt has the description */
true
67fac96fcb379f753e48c8a4b47d9f6ad73e7995
Java
cztwin/test
/src/com/czt/hello/User.java
UTF-8
940
2.703125
3
[]
no_license
package com.czt.hello; import java.util.Date; public class User { private String id; private String name; private Integer age; private Date brithDay; public User(String id, String name, Integer age, Date brithDay) { this.id = id; this.name = name; this.age = age; this.brithDay = brithDay; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBrithDay() { return brithDay; } public void setBrithDay(Date brithDay) { this.brithDay = brithDay; } public User(String id) { this.id = id; } }
true
219d5b7785279e8d6f26d7747ea1c6b3fde82fc0
Java
Michal-dotcom/Testowanie
/src/test/java/Zad3Test.java
UTF-8
385
2.25
2
[]
no_license
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class Zad3Test { @Test void dodawacz() { int[] daneWejsciowe = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] wynik = new Zad3().dodawacz(daneWejsciowe); int[] oczekiwanywynik = {4, 6, 8, 10, 12, 14, 16, 18, 9, 10}; assertArrayEquals(oczekiwanywynik, wynik); } }
true
0f0c4ac166e40cd2b6c2efc02bdf8ae38abda7c0
Java
jinricheng/surfdev
/app/src/main/java/myaplication/tfg/org/models/Address.java
UTF-8
1,337
2.578125
3
[]
no_license
package myaplication.tfg.org.models; /** * Created by jin on 2015/5/29. */ public class Address { private String streetName=""; private String code=""; private String telefon=""; private String countryName=""; private String cityName=""; public Address(){ } public Address(String streetName,String code, String telefon,String cityName){ this.streetName = streetName; this.code = code; this.telefon = telefon; this.countryName = countryName; this.cityName = cityName; } public void setStreetName(String streetName){ this.streetName = streetName; } public void setCode(String postCode){ this.code = postCode; } public void setTelefon(String telefon){ this.telefon = telefon; } public void setCountryName(String countryName){ this.countryName = countryName; } public void setCityName(String cityName){ this.cityName = cityName; } public String getStreetName(){ return this.streetName; } public String getCode(){ return this.code; } public String getTelefon(){ return this.telefon; } public String getCountryName(){ return this.countryName; } public String getCityName(){ return this.cityName; } }
true
465406083b4c3f1a08e270dd2470909af0503770
Java
CheolHo-0428/AdminPage
/src/main/java/com/example/study/repository/AdminUsersRepository.java
UTF-8
298
1.632813
2
[]
no_license
package com.example.study.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.example.study.model.entity.AdminUsers; @Repository public interface AdminUsersRepository extends JpaRepository<AdminUsers, Long> { }
true
cba7ace4fcf82cf62c46419c6ab2046be8db556a
Java
dipeshji/javaWorkSpace
/SpringWorkSpace/Coupling/src/com/tightcoupling/Main.java
UTF-8
373
2.109375
2
[]
no_license
/* * output is coupled to Csvoutput generator, every change of output generator may involve code change */ package com.tightcoupling; public class Main { public static void main(String[] args) { IoutputGenerator output = new CsvOutputGenerator(); output.generateOutput(); // IoutputGenerator output = new JsonOutputGenerator(); // output.generateOutput(); } }
true
96c36caca22f7c80a92c685165377ccfdea370ee
Java
amiralizadehit/Sample-Code
/Android Development Sample Code/MainActivity.java
UTF-8
6,330
2.03125
2
[]
no_license
package com.arsheet.arsheetpresencesystem; import java.nio.Buffer; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.format.DateFormat; import android.text.style.BackgroundColorSpan; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.GridView; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; @SuppressLint("NewApi") public class MainActivity extends Activity implements OnItemSelectedListener { public static MainActivity globalActivity = null; public static DatabaseHelper db; public static Context globalContext; public static FragmentManager fragmentManager; public static Resources res; public static TextView passwordField; public static TextView usernameField; public static TextView time; public static Calendar calendar; public static SimpleDateFormat timeFormat; public static RelativeLayout rLayout; private Spinner spinner; private TextView type; private Button timeRefresher; private Button admin; private Button record; private SimpleDateFormat dateFormat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); globalContext = this.getApplicationContext(); globalActivity = this; fragmentManager = getFragmentManager(); res = getResources(); //resource handle passwordField = (TextView)findViewById(R.id.passwordText); usernameField = (TextView)findViewById(R.id.usernameText); db = new DatabaseHelper(this); spinner=(Spinner) findViewById(R.id.spinner1); admin = (Button)findViewById(R.id.adminpage); record=(Button) findViewById(R.id.button1); time=(TextView) findViewById(R.id.textView1); timeFormat = new SimpleDateFormat("HH:mm:ss a"); dateFormat = new SimpleDateFormat("dd"); calendar = Calendar.getInstance(); time.setText(timeFormat.format(calendar.getTime())); rLayout = (RelativeLayout) findViewById (R.id.relative); ArrayAdapter adapter=ArrayAdapter.createFromResource(this,R.array.outworks, R.layout.custom_xml_spinner_layout); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView<?> adapterView, View view, int i ,long l) { type = (TextView)view; } public void Admin (View view){ String enteredUsername = usernameField.getText().toString(); String enteredPassword = passwordField.getText().toString(); int rank =db.AdminPage(enteredUsername, enteredPassword); if (rank ==2){ // Starting admin activity Toast.makeText(getApplicationContext(), "You are admin!",Toast.LENGTH_LONG).show(); AdminPage(); } else if (rank ==1){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setTitle("Error"); builder.setMessage("You are not allowded to access admin page"); builder.show(); } else Toast.makeText(getApplicationContext(), "Username or Password is incorrect",Toast.LENGTH_LONG).show(); } public void AdminPage() { Intent i = new Intent(this,Admin_page.class); startActivity(i); //Declaring new activity using Intents } public void Record(View view){ calendar = Calendar.getInstance(); String enteredUsername = usernameField.getText().toString(); String enteredPassword = passwordField.getText().toString(); int rank =db.InformationProcessor(enteredUsername, enteredPassword ,type.getText().toString(),dateFormat.format(calendar.getTime()),timeFormat.format(calendar.getTime())); if (rank>=1){ BackgroundChanger (true); } } public static void Reset (){ passwordField.setText(""); usernameField.setText(""); calendar = Calendar.getInstance(); time.setText(timeFormat.format(calendar.getTime())); BackgroundChanger(false); } public static void BackgroundChanger (boolean correction){ if(correction==false){ Drawable drawable = res.getDrawable(R.drawable.pig1); //new Image that was added to the res folder rLayout.setBackground(drawable);} else{ Drawable drawable = res.getDrawable(R.drawable.pass); //new Image that was added to the res folder rLayout.setBackground(drawable);} } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }
true
f0d5bd70d9c45ad29d0111441250beb580c1b9f5
Java
nirmal976/Final-Automation
/SmartTech_Automation/src/test/java/com/inheritance/Orders.java
UTF-8
433
2.9375
3
[]
no_license
package com.inheritance; public class Orders extends Items { private int no; public int getNo() { return no; } public void setNo(int no) { this.no = no; } void displayinformation() { System.out.println(getName()); // otherway we can create 1 method in Orders than here we can call System.out.println(getId()); System.out.println(getNo()); System.out.println("\n"); } }
true
c830e38f6099ea9bd0a91949f086b9c12ba191ac
Java
m0ar/hotel-papyrus
/Hotelsystem/src/implementation/util/ImplementationSwitch.java
UTF-8
21,794
2.390625
2
[]
no_license
/** */ package implementation.util; import implementation.*; import java.util.List; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see implementation.ImplementationPackage * @generated */ public class ImplementationSwitch { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static ImplementationPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ImplementationSwitch() { if (modelPackage == null) { modelPackage = ImplementationPackage.eINSTANCE; } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ public Object doSwitch(EObject theEObject) { return doSwitch(theEObject.eClass(), theEObject); } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected Object doSwitch(EClass theEClass, EObject theEObject) { if (theEClass.eContainer() == modelPackage) { return doSwitch(theEClass.getClassifierID(), theEObject); } else { List eSuperTypes = theEClass.getESuperTypes(); return eSuperTypes.isEmpty() ? defaultCase(theEObject) : doSwitch((EClass)eSuperTypes.get(0), theEObject); } } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ protected Object doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case ImplementationPackage.BOOKING_CONTROLLER: { BookingController bookingController = (BookingController)theEObject; Object result = caseBookingController(bookingController); if (result == null) result = caseIBooking(bookingController); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.MODEL: { Model model = (Model)theEObject; Object result = caseModel(model); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.ROOM_TYPE: { RoomType roomType = (RoomType)theEObject; Object result = caseRoomType(roomType); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.BED: { Bed bed = (Bed)theEObject; Object result = caseBed(bed); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.ROOM: { Room room = (Room)theEObject; Object result = caseRoom(room); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.BILL: { Bill bill = (Bill)theEObject; Object result = caseBill(bill); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.ROOM_ISSUE: { RoomIssue roomIssue = (RoomIssue)theEObject; Object result = caseRoomIssue(roomIssue); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.GUEST: { Guest guest = (Guest)theEObject; Object result = caseGuest(guest); if (result == null) result = casePerson(guest); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.PERSON: { Person person = (Person)theEObject; Object result = casePerson(person); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.KEY: { Key key = (Key)theEObject; Object result = caseKey(key); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.CONFERENCE_ROOM_BOOKING: { ConferenceRoomBooking conferenceRoomBooking = (ConferenceRoomBooking)theEObject; Object result = caseConferenceRoomBooking(conferenceRoomBooking); if (result == null) result = caseBooking(conferenceRoomBooking); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.BOOKING: { Booking booking = (Booking)theEObject; Object result = caseBooking(booking); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.ROOM_BOOKING: { RoomBooking roomBooking = (RoomBooking)theEObject; Object result = caseRoomBooking(roomBooking); if (result == null) result = caseBooking(roomBooking); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.CUSTOMER: { Customer customer = (Customer)theEObject; Object result = caseCustomer(customer); if (result == null) result = casePerson(customer); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.CONFERENCE_ROOM: { ConferenceRoom conferenceRoom = (ConferenceRoom)theEObject; Object result = caseConferenceRoom(conferenceRoom); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.IPROFILE: { IProfile iProfile = (IProfile)theEObject; Object result = caseIProfile(iProfile); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.PROFILE_HANDLER: { ProfileHandler profileHandler = (ProfileHandler)theEObject; Object result = caseProfileHandler(profileHandler); if (result == null) result = caseIProfile(profileHandler); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.BANK_PROVIDES: { BankProvides bankProvides = (BankProvides)theEObject; Object result = caseBankProvides(bankProvides); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.IBOOKING: { IBooking iBooking = (IBooking)theEObject; Object result = caseIBooking(iBooking); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.ADMIN_CONTROLLER: { AdminController adminController = (AdminController)theEObject; Object result = caseAdminController(adminController); if (result == null) result = caseIAdministration(adminController); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.IADMINISTRATION: { IAdministration iAdministration = (IAdministration)theEObject; Object result = caseIAdministration(iAdministration); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.MODEL_FACTORY: { ModelFactory modelFactory = (ModelFactory)theEObject; Object result = caseModelFactory(modelFactory); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.MAIN: { Main main = (Main)theEObject; Object result = caseMain(main); if (result == null) result = defaultCase(theEObject); return result; } case ImplementationPackage.BANK: { Bank bank = (Bank)theEObject; Object result = caseBank(bank); if (result == null) result = caseBankProvides(bank); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>Booking Controller</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Booking Controller</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseBookingController(BookingController object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Model</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Model</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseModel(Model object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Room Type</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Room Type</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseRoomType(RoomType object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Bed</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Bed</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseBed(Bed object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Room</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Room</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseRoom(Room object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Bill</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Bill</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseBill(Bill object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Room Issue</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Room Issue</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseRoomIssue(RoomIssue object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Guest</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Guest</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseGuest(Guest object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Person</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Person</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object casePerson(Person object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Conference Room Booking</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Conference Room Booking</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseConferenceRoomBooking(ConferenceRoomBooking object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Booking</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Booking</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseBooking(Booking object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Room Booking</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Room Booking</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseRoomBooking(RoomBooking object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Key</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Key</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseKey(Key object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Conference Room</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Conference Room</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseConferenceRoom(ConferenceRoom object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IBooking</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IBooking</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseIBooking(IBooking object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Customer</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Customer</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseCustomer(Customer object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Admin Controller</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Admin Controller</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseAdminController(AdminController object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Bank Provides</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Bank Provides</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseBankProvides(BankProvides object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IAdministration</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IAdministration</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseIAdministration(IAdministration object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Model Factory</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Model Factory</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseModelFactory(ModelFactory object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Main</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Main</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseMain(Main object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Bank</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Bank</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseBank(Bank object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Profile Handler</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Profile Handler</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseProfileHandler(ProfileHandler object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IProfile</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IProfile</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public Object caseIProfile(IProfile object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ public Object defaultCase(EObject object) { return null; } } //ImplementationSwitch
true
df190e2b54a92ff1034dc5b1e3d2b89ba4990bd4
Java
WilailakBua/Batch
/demo/src/main/java/com/example/demo/entity/ParamInfoBatch.java
UTF-8
858
1.648438
2
[]
no_license
package com.example.demo.entity; public class ParamInfoBatch { public String paramInfoCode; public String paramInfoValue; public String paramInfoValue2; public String paramGroupCode; public String getParamInfoCode() { return paramInfoCode; } public void setParamInfoCode(String paramInfoCode) { this.paramInfoCode = paramInfoCode; } public String getParamInfoValue() { return paramInfoValue; } public void setParamInfoValue(String paramInfoValue) { this.paramInfoValue = paramInfoValue; } public String getParamInfoValue2() { return paramInfoValue2; } public void setParamInfoValue2(String paramInfoValue2) { this.paramInfoValue2 = paramInfoValue2; } public String getParamGroupCode() { return paramGroupCode; } public void setParamGroupCode(String paramGroupCode) { this.paramGroupCode = paramGroupCode; } }
true
0429f4900c644d8b3245985efc7eb0c40938c04a
Java
omnya-alaa-eddin/TestSpringBoot
/FirstSpringBoot/src/main/java/springBoot/config/SpringBootApplicationConfig.java
UTF-8
502
1.78125
2
[]
no_license
/** * */ package springBoot.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * @author o.alaa * */ @SpringBootApplication @ComponentScan({ "springBoot.presentation,springBoot.service"}) public class SpringBootApplicationConfig { public static void main(String[]args) { SpringApplication.run(SpringBootApplicationConfig.class, args); } }
true
3db2aedf72964a13ad729a8d3b69b6dabaa3e2d0
Java
hhu-stups/tla2bAST
/src/test/java/de/tla2b/typechecking/ExtendsTest.java
UTF-8
503
1.882813
2
[]
no_license
package de.tla2b.typechecking; import static org.junit.Assert.assertEquals; import org.junit.Test; import de.tla2b.util.TestTypeChecker; import de.tla2b.util.TestUtil; public class ExtendsTest { @Test public void TestExtendsCounter() throws Exception { String path = "src/test/resources/typechecking/modules/"; TestTypeChecker t = TestUtil.typeCheck(path + "ExtendsCounter.tla"); assertEquals("INTEGER", t.getVariableType("x")); assertEquals("INTEGER", t.getConstantType("start")); } }
true
b2aabced0804ca7ae1d81f1d041fdb3349392fa3
Java
mygitsource/data-structures
/trees/src/com/datastructures/trees/bst/InOrderSuccessor_Set1.java
UTF-8
3,026
4.0625
4
[]
no_license
package com.datastructures.trees.bst; public class InOrderSuccessor_Set1 { /* * In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. * Inorder Successor is NULL for the last node in Inoorder traversal. * * In Binary Search Tree, * Inorder Successor of an input node can also be defined as the node with the * smallest key greater than the key of input node. * So, it is sometimes important to find next node in sorted order. * */ static class Node{ private int data; private Node left; private Node right; private Node parent; public Node(int data){ this.data = data; } public Node(Node left, Node right, Integer data, Node parent){ this.data = data; this.left = left; this.right = right; this.parent = parent; } @Override public String toString() { return this.data+""; } } static Node inOrderSuccessor(Node root, Node k){ //1) If right subtree of node is not NULL, then succ lies in right subtree. //Go to right subtree and return the node with minimum key value in right subtree. if(k.right != null){ return minValue(k.right); } //2) If right sbtree of node is NULL, then succ is one of the ancestors. //Travel up using the parent pointer until you see a node which is left child of it’s parent. //The parent of such a node is the succ. Node parent = k.parent; //TODO :: Need to test second condition with full tree while((parent != null && parent.right != null) && (k.data == parent.right.data)){ k = parent; parent = parent.parent; } return parent; } static Node minValue(Node node){ Node current = node; while(current.left != null){ current = current.left; } return current; } public static void main(String[] args) { Node root = getBinaryTree4(); Node temp = root.left.left; Node inS = inOrderSuccessor(root, temp); System.out.println(inS.data); } /** 50 / \ 17 76 / \ / 9 23 54 \ / \ 14 19 72 / / 12 67 */ public static Node getBinaryTree4(){ Node root = null; root = insert(root, 50); root = insert(root, 17); root = insert(root, 9); root = insert(root, 23); root = insert(root, 14); root = insert(root, 19); root = insert(root, 12); root = insert(root, 76); root = insert(root, 54); root = insert(root, 72); root = insert(root, 67); return root; } static Node insert(Node node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == null) return(new Node(data)); else { Node temp = null; /* 2. Otherwise, recur down the tree */ if (data <= node.data) { temp = insert(node.left, data); node.left = temp; temp.parent= node; }else{ temp = insert(node.right, data); node.right = temp; temp.parent = node; } /* return the (unchanged) node pointer */ return node; } } }
true
e50152d595a7414bebfcc6e4ed269950401bc12e
Java
ekoindia/mshiko-android
/app/src/main/java/in/co/eko/fundu/utils/UserVerification.java
UTF-8
374
2
2
[]
no_license
package in.co.eko.fundu.utils; /* * Created by Bhuvnesh */ import android.content.Context; public class UserVerification { private Context context; public UserVerification(Context context) { this.context = context; } public boolean isMobileVerified(){ return true; } public boolean isUserLogin() { return true; } }
true
61239f9d40a7f436bff2dd7e87412cd06572e713
Java
weitat95/mastersDissertation
/qardio_source/cfr_dec/com/google/firebase/iid/zzm.java
UTF-8
311
1.507813
2
[]
no_license
/* * Decompiled with CFR 0.147. */ package com.google.firebase.iid; import com.google.firebase.iid.zzk; final class zzm implements Runnable { private final zzk zznzg; zzm(zzk zzk2) { this.zznzg = zzk2; } @Override public final void run() { this.zznzg.zzcjd(); } }
true
46649afb555e7ef4b53baefe137f156ce4c5abf5
Java
shengwuer/GitRepository
/spring-course2/ch06-aop-aspectj/src/main/java/com/lypowernode/ba09/SomeServiceImpl.java
UTF-8
812
3.046875
3
[]
no_license
package com.lypowernode.ba09; public class SomeServiceImpl implements SomeService { @Override public void doSome(String name, int age) { // 给方法增加一个功能 ,在方法执行前增加时间 System.out.println("========目标方法doSome()======"); } @Override public String doOther(String name, int age) { System.out.println("========目标方法doOther()======"); return "abcd"; } @Override public String doFirst(String name, int age) { return null; } @Override public void doSecond() { System.out.println(10/0); System.out.println("执行业务方doSecond()"); } @Override public void doThird() { System.out.println("(目标方法)执行业务方法doThird()"); } }
true
5fb68811912478c5fd7abbd40da13900f939179c
Java
hotire/spring-data-jpa
/src/main/java/com/googlecode/hotire/springdatajpa/query/specification/ContentService.java
UTF-8
429
2.078125
2
[]
no_license
package com.googlecode.hotire.springdatajpa.query.specification; import java.util.List; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor public class ContentService { private final ContentRepository contentRepository; public List<Content> getContents(String name) { return contentRepository.findAll(ContentSpecs.withName(name)); } }
true
d8510b67ae3c07e0b0f68d54a1b057e89986d3e1
Java
agat-prog/conecta4
/src/usantatecla/connect4/controllers/RedoController.java
UTF-8
298
2.1875
2
[]
no_license
package usantatecla.connect4.controllers; import usantatecla.connect4.models.Session; public class RedoController extends Controller { RedoController(Session session) { super(session); } void redo() { this.session.redo(); } boolean redoable() { return this.session.redoable(); } }
true
01697f8eb8922bea58d59f9d1022ca4c2043b01a
Java
cglewis/cattle
/code/iaas/cluster-logic/src/main/java/io/cattle/iaas/cluster/process/ClusterHostMapCreateHandler.java
UTF-8
1,324
2.125
2
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package io.cattle.iaas.cluster.process; import io.cattle.iaas.cluster.service.ClusterManager; import io.cattle.platform.core.model.ClusterHostMap; import io.cattle.platform.core.model.Host; import io.cattle.platform.engine.handler.HandlerResult; import io.cattle.platform.engine.handler.ProcessPostListener; import io.cattle.platform.engine.process.ProcessInstance; import io.cattle.platform.engine.process.ProcessState; import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic; import io.cattle.platform.util.type.Priority; import javax.inject.Inject; import javax.inject.Named; @Named public class ClusterHostMapCreateHandler extends AbstractObjectProcessLogic implements ProcessPostListener, Priority { @Inject ClusterManager clusterManager; @Override public String[] getProcessNames() { return new String[] { "clusterhostmap.create" }; } @Override public HandlerResult handle(ProcessState state, ProcessInstance process) { Long clusterId = ((ClusterHostMap) state.getResource()).getClusterId(); Host cluster = objectManager.loadResource(Host.class, clusterId); clusterManager.updateClusterServerConfig(state, cluster); return null; } @Override public int getPriority() { return Priority.DEFAULT; } }
true
35ee847f5603691f5e035c9ab48c182db82b94d7
Java
piotrdopierala/CodeWars
/src/test/java/kyu7/ExesAndOhs/mySolutionTest.java
UTF-8
905
2.53125
3
[]
no_license
package kyu7.ExesAndOhs; import org.junit.Test; import static org.junit.Assert.*; public class mySolutionTest { @Test public void testSomething1() { assertEquals(true, mySolution.getXO("xxxooo")); } @Test public void testSomething2() { assertEquals(true, mySolution.getXO("xxxXooOo")); } @Test public void testSomething3() { assertEquals(false, mySolution.getXO("xxx23424esdsfvxXXOOooo")); } @Test public void testSomething4() { assertEquals(false, mySolution.getXO("xXxxoewrcoOoo")); } @Test public void testSomething5() { assertEquals(false, mySolution.getXO("XxxxooO")); } @Test public void testSomething6() { assertEquals(true, mySolution.getXO("zssddd")); } @Test public void testSomething7() { assertEquals(false, mySolution.getXO("Xxxxertr34")); } }
true