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
8e278fcd9513ec6fd785fcba70ae79543e81a5a8
Java
roshniiee/backUp
/DemoJDBC/src/test/PrepareStmtDemo.java
UTF-8
210
1.804688
2
[]
no_license
package test; public class PrepareStmtDemo { public static void main(String asr[]) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); }catch(Exception e) { System.out.println(e); } } }
true
464219f5c803e42c70e3053c316ebc073930e316
Java
ildar66/WSAD_iBank_EJB_store
/2003_05_23/WSAD_iBankEJB/CMP_Entity/ejbModule/itso/ejb35/cmp/EJSCMPBankAccountHomeBean.java
UTF-8
4,481
2.09375
2
[]
no_license
package itso.ejb35.cmp; import com.ibm.ejs.container.*; import com.ibm.ejs.persistence.*; import com.ibm.ejs.EJSException; import javax.ejb.*; import java.rmi.RemoteException; /** * EJSCMPBankAccountHomeBean * @generated */ public class EJSCMPBankAccountHomeBean extends EJSHome { /** * EJSCMPBankAccountHomeBean * @generated */ public EJSCMPBankAccountHomeBean() throws java.rmi.RemoteException { super(); } /** * create * @generated */ public itso.ejb35.cmp.BankAccount create(java.lang.String accID, java.math.BigDecimal argBalance) throws javax.ejb.CreateException, java.rmi.RemoteException { BeanO beanO = null; itso.ejb35.cmp.BankAccount _EJS_result = null; boolean createFailed = false; try { beanO = super.createBeanO(); itso.ejb35.cmp.BankAccountBean bean = (itso.ejb35.cmp.BankAccountBean) beanO.getEnterpriseBean(); bean.ejbCreate(accID, argBalance); _EJS_result = (itso.ejb35.cmp.BankAccount) super.postCreate(beanO, keyFromBean(bean)); bean.ejbPostCreate(accID, argBalance); } catch (javax.ejb.CreateException ex) { createFailed = true; throw ex; } catch (java.rmi.RemoteException ex) { createFailed = true; throw ex; } catch (Throwable ex) { createFailed = true; throw new CreateFailureException(ex); } finally { if (createFailed) { super.createFailure(beanO); } } return _EJS_result; } /** * findAccountsWithBalanceBetween * @generated */ public java.util.Enumeration findAccountsWithBalanceBetween(java.math.BigDecimal anAmount1, java.math.BigDecimal anAmount2) throws javax.ejb.FinderException, java.rmi.RemoteException { return super.getEnumeration(((itso.ejb35.cmp.EJSFinderBankAccountBean)persister).findAccountsWithBalanceBetween(anAmount1, anAmount2)); } /** * findByPrimaryKey * @generated */ public itso.ejb35.cmp.BankAccount findByPrimaryKey(itso.ejb35.cmp.BankAccountKey primaryKey) throws javax.ejb.FinderException, java.rmi.RemoteException { return ((itso.ejb35.cmp.EJSJDBCPersisterCMPBankAccountBean) persister).findByPrimaryKey(primaryKey); } /** * findAccountsWithBalanceGreaterThan * @generated */ public java.util.Enumeration findAccountsWithBalanceGreaterThan(java.math.BigDecimal anAmount) throws javax.ejb.FinderException, java.rmi.RemoteException { return super.getEnumeration(((itso.ejb35.cmp.EJSFinderBankAccountBean)persister).findAccountsWithBalanceGreaterThan(anAmount)); } /** * findAll * @generated */ public java.util.Enumeration findAll() throws javax.ejb.FinderException, java.rmi.RemoteException { return super.getEnumeration(((itso.ejb35.cmp.EJSFinderBankAccountBean)persister).findAll()); } /** * create * @generated */ public itso.ejb35.cmp.BankAccount create(java.lang.String accID) throws javax.ejb.CreateException, java.rmi.RemoteException { BeanO beanO = null; itso.ejb35.cmp.BankAccount _EJS_result = null; boolean createFailed = false; try { beanO = super.createBeanO(); itso.ejb35.cmp.BankAccountBean bean = (itso.ejb35.cmp.BankAccountBean) beanO.getEnterpriseBean(); bean.ejbCreate(accID); _EJS_result = (itso.ejb35.cmp.BankAccount) super.postCreate(beanO, keyFromBean(bean)); bean.ejbPostCreate(accID); } catch (javax.ejb.CreateException ex) { createFailed = true; throw ex; } catch (java.rmi.RemoteException ex) { createFailed = true; throw ex; } catch (Throwable ex) { createFailed = true; throw new CreateFailureException(ex); } finally { if (createFailed) { super.createFailure(beanO); } } return _EJS_result; } /** * findAccountsWithBalanceGreater * @generated */ public java.util.Enumeration findAccountsWithBalanceGreater(java.math.BigDecimal anAmount) throws javax.ejb.FinderException, java.rmi.RemoteException { return super.getEnumeration(((itso.ejb35.cmp.EJSFinderBankAccountBean)persister).findAccountsWithBalanceGreater(anAmount)); } /** * keyFromBean * @generated */ public Object keyFromBean(javax.ejb.EntityBean generalEJB) { itso.ejb35.cmp.BankAccountBean tmpEJB = (itso.ejb35.cmp.BankAccountBean) generalEJB; itso.ejb35.cmp.BankAccountKey keyClass = new itso.ejb35.cmp.BankAccountKey(); keyClass.accID = tmpEJB.accID; return keyClass; } /** * keyFromFields * @generated */ public itso.ejb35.cmp.BankAccountKey keyFromFields(java.lang.String f0) { itso.ejb35.cmp.BankAccountKey keyClass = new itso.ejb35.cmp.BankAccountKey(); keyClass.accID = f0; return keyClass; } }
true
3ec65cf03366bab94d62ee750b73657261e54d1b
Java
Erlyberly/BootlegTerraria
/core/src/no/erlyberly/bootlegterraria/render/light/LightInfo.java
UTF-8
5,448
2.8125
3
[]
no_license
package no.erlyberly.bootlegterraria.render.light; import com.badlogic.gdx.math.Vector2; import no.erlyberly.bootlegterraria.util.Vector2Int; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class LightInfo { private final HashMap<Vector2Int, Float> litFrom; // where this light is lit from private LightLevel currLL; //the current calculated light level (including skylight) private LightLevel emitting; //How much brightness this tile is emitting (NOT including skylight) private final Vector2 posf; private final Vector2Int posi; private boolean skylight; //if this light is lit by the sky LightInfo(final Vector2Int pos) { if (pos == null) { throw new IllegalArgumentException("Position cannot be null"); } currLL = LightLevel.LVL_0; litFrom = new HashMap<>(30); posf = new Vector2(pos.x, pos.y); posi = pos; skylight = false; } LightInfo(final int blockX, final int blockY) { this(new Vector2Int(blockX, blockY)); } /** * Setting the {@code srcBrt} to {@link LightLevel#LVL_0} is the same as {@link #remove(Vector2Int, boolean)} * * @param src * The source of the light * @param srcBrt * The brightness of the source light * @param skylight * If this light is a skylight or not */ public void put(final Vector2Int src, final LightLevel srcBrt, final boolean skylight) { if (srcBrt == LightLevel.LVL_0) { throw new IllegalArgumentException("Cannot set the light to 0, please use the remove method"); } float brightness; //place at this light levels location if (posi.equals(src)) { brightness = srcBrt.getLvl(); if (skylight) { //mark this tile as a light info tile this.skylight = true; // brightness = LightLevel.max().getLvl(); } else { //take a note of what this tile would be emitting if it wasn't a skylight emitting = srcBrt; if (this.skylight) { //do not update the brightness if it is already skylight (as skylight should always overwrite // tile light) return; } // brightness = srcBrt.getLvl(); } } else { brightness = srcBrt.getLvl() - posf.dst(src.x, src.y); // brightness = (skylight ? LightLevel.LVL_8 : srcBrt).getLvl() - posf.dst(src.x, src.y); // if (brightness == 3.8377223) { // System.out.println("---\nposi = " + posi); // System.out.println("src = [" + src + "], srcBrt = [" + srcBrt + "], skylight = [" + skylight + "]"); // System.out.println("litFrom MAX = " + litFrom.values().stream().max(Float::compareTo)); // System.out.println("litFrom = " + litFrom.values()); // } } //No light when brightness is less than 0 (this point is out of the light radius) if (brightness <= 0) { return; } litFrom.put(src, brightness); calculateLightLevel(); } /** * Remove a light from the set of objects that light this tile * * @param src * The source to remove * @param skylight * If the removed light is skylight */ public void remove(final Vector2Int src, final boolean skylight) { litFrom.remove(src); if (posi.equals(src)) { // if (!this.skylight && skylight) { // return; // } if (skylight /*&& this.skylight*/) { //this was a skylight, but now it's not this.skylight = false; } else /*if (!skylight)*/ { //this location is no longer emitting light emitting = LightLevel.LVL_0; } } calculateLightLevel(); } /** * Calculate the brightness of this based on the objects that shine on it */ private void calculateLightLevel() { //if nothing is shining of it the light level must be 0 if (litFrom.isEmpty()) { currLL = LightLevel.LVL_0; } else if (skylight) { currLL = LightLevel.max(); } else { currLL = LightLevel.valueOf(Collections.max(litFrom.values())); } } public LightLevel getLightLevel() { return currLL; } public Map<Vector2Int, Float> litFrom() { return litFrom; } Vector2 getPosf() { return posf; } Vector2Int getPosi() { return posi; } public boolean isSkylight() { return skylight; } public LightLevel getEmitting() { return emitting; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof LightInfo)) { return false; } final LightInfo info = (LightInfo) o; return posi.equals(info.posi); } @Override public int hashCode() { return posi.hashCode(); } @Override public String toString() { return "LightInfo{" + "posi=" + posi + ", currLL=" + currLL + ", emitting=" + emitting + ", skylight=" + skylight + ", lit from " + litFrom.size() + " different places" + '}'; } }
true
36559f76679227d54dcbc5838fb9017788640e04
Java
dhinojosa/tdd20151207
/basic-tdd/src/main/java/com/example/library/BookCheckoutParser.java
UTF-8
986
2.96875
3
[]
no_license
package com.example.library; import java.time.LocalDate; import java.time.format.DateTimeParseException; public class BookCheckoutParser { private static final String PROVIDED_CHECKOUT_DATE_IS_INVALID_MSG = "Provided Checkout Date is invalid: [%s]"; public static BookCheckout parseLine(String data) { if (data.isEmpty()) throw new IllegalArgumentException ("Provided data is invalid: []"); String[] items = data.split("~"); if (items.length < 3) { throw new IllegalArgumentException (String.format("Expected 3 Items, but got %d: [%s]", items.length, data)); } LocalDate parsedDate = null; String dateString = items[2]; try { parsedDate= LocalDate.parse(dateString); } catch (DateTimeParseException dpe) { throw new IllegalArgumentException (String.format( PROVIDED_CHECKOUT_DATE_IS_INVALID_MSG, dateString),dpe); } return new BookCheckout (items[0], items[1], parsedDate); } }
true
edd025d65898bd04e47398f4f64eb15910ea9c9d
Java
Ajaykamani/Full-stack-Java
/pixogram microservices-2/userservice/src/main/java/com/pixogram/userservice/repository/UserRepository.java
UTF-8
434
1.890625
2
[]
no_license
package com.pixogram.userservice.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.pixogram.userservice.entity.User; @Repository public interface UserRepository extends JpaRepository<User, Integer> { List<User> findByuserName(String username); List<User> findByUserNameContaining(String username); }
true
da4e94256580ed35513a4c692d0e9df7c158c8d5
Java
notorious95/todo-list-android
/app/src/main/java/com/dziura/patryk/todolist/SettingsActivity.java
UTF-8
1,671
2.265625
2
[]
no_license
package com.dziura.patryk.todolist; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.preference.PreferenceManager; public class SettingsActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener { private String mSelectedTheme = "blue"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupSharedPreferences(); if (mSelectedTheme.equals("green")) setTheme(R.style.AppTheme); else setTheme(R.style.AppTheme2); setContentView(R.layout.activity_settings); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_theme_key))) { mSelectedTheme = sharedPreferences.getString(key, getString(R.string.pref_theme_value_blue)); Intent i = getBaseContext().getPackageManager() .getLaunchIntentForPackage( getBaseContext().getPackageName() ); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(i); } } private void setupSharedPreferences(){ SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSelectedTheme = sharedPreferences.getString(getString(R.string.pref_theme_key), getString(R.string.pref_theme_value_blue)); sharedPreferences.registerOnSharedPreferenceChangeListener(this); } }
true
ac8e25e4d051134e021d2759c4eeba9b305dc1da
Java
dnhem27/ExpenseReimbursementSystem_Team3
/src/test/java/HelpDeskTests.java
UTF-8
4,404
2.484375
2
[]
no_license
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import java.sql.Timestamp; import org.junit.Test; import org.mockito.Mock; import com.teamthree.dao.TicketDaoImpl; import com.teamthree.dao.UserDaoImpl; import com.teamthree.models.Ticket; import com.teamthree.models.User; import com.teamthree.service.HelpDesk; public class HelpDeskTests { @Mock private UserDaoImpl userDao; @Mock private TicketDaoImpl ticketDao; @Test public void testTryLogIn() { userDao = mock(UserDaoImpl.class); HelpDesk spyHelpDesk = spy(new HelpDesk(userDao, ticketDao)); // Log in with valid information test when(spyHelpDesk.findUser("bob23")).thenReturn(new User("bob23", "password4", "05/07/1907", "employee", "Bob", "Jenkins")); boolean loggedIn = spyHelpDesk.tryLogIn("bob23", "password4"); assertTrue(loggedIn); // Log in with wrong password test when(spyHelpDesk.findUser("bob23")).thenReturn(new User("bob23", "password4", "05/07/1907", "employee", "Bob", "Jenkins")); loggedIn = spyHelpDesk.tryLogIn("bob23", "password_321111"); assertTrue( ! loggedIn); // Log in with user that does not exist in system when(spyHelpDesk.findUser("derrick24")).thenReturn(null); loggedIn = spyHelpDesk.tryLogIn("derrick24", "12345678"); assertTrue( ! loggedIn); } @Test public void testCreateNewUser() { userDao = mock(UserDaoImpl.class); // Create user when username does not exist when(userDao.addUser("bob55", "password1", "01/01/2000", "employee", "Bob", "Jenkins")).thenReturn(true); HelpDesk hD = new HelpDesk(userDao, ticketDao); assertTrue(hD.createNewUser("bob55", "password1", "01/01/2000", "employee", "Bob", "Jenkins")); // Add user when user does exist when(userDao.addUser( "bob55", "password1", "01/01/2000", "employee", "Bob", "Jenkins" )).thenReturn(false); hD = new HelpDesk(userDao, ticketDao); assertFalse(hD.createNewUser("bob55", "password1", "01/01/2000", "employee", "Bob", "Jenkins")); // Attempt add user with a blank field of any type when(userDao.addUser( "bob55", "password1", "01/01/2000", "", "Bob", "Jenkins" )).thenReturn(false); hD = new HelpDesk(userDao, ticketDao); assertFalse(hD.createNewUser("bob55", "password1", "01/01/2000", "", "Bob", "Jenkins")); } @Test public void testGetTicketByID() { // Get a ticket by ID when it exists ticketDao = mock(TicketDaoImpl.class); when(ticketDao.getTicketFromID(10)).thenReturn(new Ticket(10,"Pending",400.22,null,"Spanish restaurant","bob23","Food")); HelpDesk hd = new HelpDesk(null, ticketDao); Ticket ticketThatExists = hd.getTicketByID(10); assertTrue(ticketThatExists != null); assertTrue(ticketThatExists.getId() == 10); // Try to get a ticket when negative id is specified ticketDao = mock(TicketDaoImpl.class); when(ticketDao.getTicketFromID(-10)).thenReturn(null); hd = new HelpDesk(null, ticketDao); Ticket ticketDoesNotExist1 = hd.getTicketByID(-10); assertTrue(ticketDoesNotExist1 == null); // Try to get a ticket by ID when it does not exist ticketDao = mock(TicketDaoImpl.class); when(ticketDao.getTicketFromID(20)).thenReturn(null); hd = new HelpDesk(null, ticketDao); Ticket ticketThatDoesNotExist2 = hd.getTicketByID(20); assertTrue(ticketThatDoesNotExist2 == null); } @Test public void testGenerateTicket() { ticketDao = mock(TicketDaoImpl.class); // Successful ticket generation when(ticketDao.addTicket(eq("Pending"), eq(800.00), any(Timestamp.class), eq("Fuel"), eq("bob23"), eq("Travel"))).thenReturn(true); HelpDesk hd = new HelpDesk(userDao, ticketDao); assertTrue(hd.generateTicket("bob23", 800.0,"Fuel", "Travel")); } @Test public void testIsUsernameAvailable() { userDao = mock(UserDaoImpl.class); when(userDao.getUserFromUsername("bob23")).thenReturn(new User("bob23","password","01/01/1900","employee","Bob","Jenkins")); HelpDesk hD = new HelpDesk(userDao, null); assertFalse(hD.isUsernameAvailable("bob23")); when(userDao.getUserFromUsername("bob6000")).thenReturn(null); hD = new HelpDesk(userDao, null); assertTrue(hD.isUsernameAvailable("bob6000")); } }
true
bf1881b671ebe080923c454eedc212c4ad11afd0
Java
hoachen/android-gl-transition
/gltrans/src/main/java/com/av/gltrans/gles/transition/AngularTransition.java
UTF-8
1,303
2.796875
3
[]
no_license
package com.av.gltrans.gles.transition; import com.av.gltrans.gles.graphics.uniform.FloatUniform; import static com.av.gltrans.gles.graphics.uniform.FloatUniform.uniform1f; public class AngularTransition extends Transition { private float startingAngle = 90f; private FloatUniform startingAngleUniform = uniform1f("startingAngle", false); public AngularTransition() { super("angular", SOURCE, 1000L); autoInit(startingAngleUniform); } @Override public void onUpdateUniforms() { super.onUpdateUniforms(); startingAngleUniform.setValue(startingAngle); } public static final String SOURCE = "#define PI 3.141592653589\n" + "uniform float startingAngle; // = 90;\n" + "vec4 transition (vec2 uv) {\n" + " float offset = startingAngle * PI / 180.0;\n" + " float angle = atan(uv.y - 0.5, uv.x - 0.5) + offset;\n" + " float normalizedAngle = (angle + PI) / (2.0 * PI);\n" + " normalizedAngle = normalizedAngle - floor(normalizedAngle);\n" + " return mix(\n" + " getFromColor(uv),\n" + " getToColor(uv),\n" + " step(normalizedAngle, progress)\n" + " );\n" + "}"; }
true
e888d9d90e055ac56441af39c69494d1920dfe02
Java
hanqingsong/testproject
/src/main/java/leetcode/sort/Code01_SelectionSort.java
UTF-8
1,606
4.125
4
[]
no_license
package leetcode.sort; import java.util.Arrays; /** * @author hanqingsong * @version 1.0 * @date 2022/1/16 */ public class Code01_SelectionSort { /** * 选择排序的思想是: * 给定一个数组arr,其长度为n; * 第一次从 arr[0] 到 arr[n-1] 中选取一个最值(按照需求,可以是最大值,可以是最小值,下同)与arr[0]进行交换; * 第二次从arr[1] 到 arr[n-1] 中选取一个最值与arr[1]进行交换; * 以此类推,直到arr[n-2]到arr[n-1]中选出最值交换后即完成排序。(只剩下一个元素,前面的都是比它小(或者大)的)。 * * 时间复杂度: * o(n^2) * * 稳定性: * 选择排序是不稳定的排序算法 */ public static void main(String[] args) { int[] arr = new int[]{2, 5, 93, 8, 2, 3, 100}; System.out.println("arr=" + Arrays.toString(arr)); int maxIndex; // 最大值索引 for (int i = 0; i < arr.length; i++) { maxIndex= i; // 找到后面最大值的索引 for (int j = i; j < arr.length; j++) { if (arr[j] > arr[maxIndex]) { maxIndex = j; } } // 判断交换数据 if (arr[i] != arr[maxIndex]) { swap(arr, i, maxIndex); } } System.out.println("排序后 arr=" + Arrays.toString(arr)); } public static void swap(int[] arr, int i, int j) { int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }
true
423f9cbf62cd002d340ca8e9d48fabf431624651
Java
Eleanore2018/youqugou
/youqugou-service-buyer/src/main/java/cn/itcast/core/service/OrderServiceImpl.java
UTF-8
16,279
1.953125
2
[]
no_license
package cn.itcast.core.service; import cn.itcast.common.util.IdWorker; import cn.itcast.core.dao.good.GoodsDao; import cn.itcast.core.dao.item.ItemCatDao; import cn.itcast.core.dao.item.ItemDao; import cn.itcast.core.dao.log.PayLogDao; import cn.itcast.core.dao.order.OrderDao; import cn.itcast.core.dao.order.OrderItemDao; import cn.itcast.core.dao.seller.SellerDao; import cn.itcast.core.entity.PageResult; import cn.itcast.core.pojo.Cart; import cn.itcast.core.pojo.good.Goods; import cn.itcast.core.pojo.item.Item; import cn.itcast.core.pojo.item.ItemCat; import cn.itcast.core.pojo.log.PayLog; import cn.itcast.core.pojo.order.*; import cn.itcast.core.pojo.seller.Seller; import cn.itcast.core.pojogroup.OrderItemVo; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @Service @Transactional public class OrderServiceImpl implements OrderService { @Autowired private OrderDao orderDao; @Autowired private RedisTemplate redisTemplate; @Autowired private IdWorker idWorker; @Autowired private ItemDao itemDao; @Autowired private OrderItemDao orderItemDao; @Autowired private PayLogDao payLogDao; @Autowired private SellerDao sellerDao; //张静 @Autowired private GoodsDao goodsDao; //张静 @Autowired private ItemCatDao itemCatDao; @Override public void insertOrder(Order order) { List<Cart> carts = (List<Cart>) redisTemplate.boundHashOps("cart").get(order.getUserId()); double totalPrice = 0; List<Long> orderIds = new ArrayList<>(); for (Cart cart : carts) { // 生成订单id long orderId = idWorker.nextId(); order.setOrderId(orderId); orderIds.add(orderId); // 设置订单状态 0 未支付 1 已支付 2... order.setStatus("0"); // 创建时间 order.setCreateTime(new Date()); // 更新时间 order.setUpdateTime(new Date()); // 商家id order.setSellerId(cart.getSellerId()); // 订单总金额 double payment = 0; for (OrderItem orderItem : cart.getOrderItems()) { Item item = itemDao.selectByPrimaryKey(orderItem.getItemId()); // 生成订单项id long orderItemId = idWorker.nextId(); orderItem.setId(orderItemId); // 设置订单id作为外键 orderItem.setOrderId(orderId); // 设置商品id orderItem.setGoodsId(item.getGoodsId()); // 设置订单标题 orderItem.setTitle(item.getTitle()); // 设置价格 orderItem.setPrice(item.getPrice()); // 设置图片 orderItem.setPicPath(item.getImage()); // 设置商家id orderItem.setSellerId(item.getSellerId()); //设置状态 张静 orderItem.setStatus("0"); // 小计 orderItem.setTotalFee(new BigDecimal(orderItem.getPrice().doubleValue() * orderItem.getNum())); // 保存订单项数据 orderItemDao.insertSelective(orderItem); payment += orderItem.getTotalFee().doubleValue(); } // 设置订单总金额 order.setPayment(new BigDecimal(payment)); totalPrice += payment; // 保存订单 orderDao.insertSelective(order); } // 生成日志 PayLog payLog = new PayLog(); // 生成支付订单id long outTradeNo = idWorker.nextId(); payLog.setOutTradeNo(String.valueOf(outTradeNo)); // 支付订单生成时间 payLog.setCreateTime(new Date()); // 设置支付订单总金额 单位(分) payLog.setTotalFee((long) (totalPrice * 100)); // 设置支付用户 payLog.setUserId(order.getUserId()); // 设置支付状态 payLog.setTradeState("0"); // 设置订单id集合(字符串) payLog.setOrderList(orderIds.toString().replace("[", "").replace("]", "")); // 支付类型 payLog.setPayType("1"); // 保存支付订单 payLogDao.insertSelective(payLog); redisTemplate.boundHashOps("payLog").put(order.getUserId(), payLog); } //查询所有订单功能,分页显示 //张静 2018-12-28 @Override public PageResult search(String status, String name, Integer pageNo, Integer pageSize) { //查询订单 OrderQuery query = new OrderQuery(); OrderQuery.Criteria criteria = query.createCriteria(); if (!"".equals(status)) { criteria.andStatusEqualTo(status); } criteria.andUserIdEqualTo(name); PageHelper.startPage(pageNo, pageSize); //查询当前用户的订单 List<Order> orderList = orderDao.selectByExample(query); if (orderList != null && orderList.size() > 0) { for (Order order : orderList) { order.setOrderIdStr(String.valueOf(order.getOrderId())); //查询卖家店铺 Seller seller = sellerDao.selectByPrimaryKey(order.getSellerId()); order.setBuyerNick(seller.getNickName()); //查询当前用户订单详情 OrderItemQuery itemQuery = new OrderItemQuery(); itemQuery.createCriteria().andOrderIdEqualTo(order.getOrderId()); List<OrderItem> orderItems = orderItemDao.selectByExample(itemQuery); if (orderItems != null && orderItems.size() > 0) { for (OrderItem orderItem : orderItems) { //获取商品名称 Goods goods = goodsDao.selectByPrimaryKey(orderItem.getGoodsId()); orderItem.setSpecStr(orderItem.getTitle().replace(goods.getGoodsName(), "")); orderItem.setGoodsName(goods.getGoodsName()); orderItem.setIdStr(String.valueOf(orderItem.getId())); } } order.setOrderItemList(orderItems); } } //查询订单数 Page<Order> p = (Page<Order>) orderList; long total = p.getTotal(); List<Order> result = p.getResult(); return new PageResult(total, result); } //查询指定订单 张静 2018-12-29 @Override public OrderItemVo selectOrderItemById(Long id) { OrderItemVo vo = new OrderItemVo(); OrderItem orderItem = orderItemDao.selectByPrimaryKey(id); orderItem.setIdStr(String.valueOf(orderItem.getId())); //获取商品名称 Goods goods = goodsDao.selectByPrimaryKey(orderItem.getGoodsId()); orderItem.setSpecStr(orderItem.getTitle().replace(goods.getGoodsName(), "")); orderItem.setGoodsName(goods.getGoodsName()); vo.setOrderItem(orderItem); Order order = orderDao.selectByPrimaryKey(orderItem.getOrderId()); vo.setAddr(order.getReceiverAreaName()); vo.setCongignTime(order.getConsignTime()); vo.setCreateTime(order.getCreateTime()); vo.setPaymentTime(order.getPaymentTime()); vo.setOrderIdStr(String.valueOf(orderItem.getOrderId())); vo.setPaymentType(order.getPaymentType() == "0" ? "微信" : "货到付款"); return vo; } //支付指定的订单 张静 12月29日 @Override public void toPay(Long id) { Order order = orderDao.selectByPrimaryKey(id); // 生成日志 PayLog payLog = new PayLog(); // 生成支付订单id long outTradeNo = idWorker.nextId(); payLog.setOutTradeNo(String.valueOf(outTradeNo)); // 支付订单生成时间 payLog.setCreateTime(new Date()); // 设置支付订单总金额 单位(分) double totalPrice = order.getPayment().doubleValue(); payLog.setTotalFee((long) (totalPrice * 100)); // 设置支付用户 payLog.setUserId(order.getUserId()); // 设置支付状态 payLog.setTradeState("0"); // 设置订单id集合(字符串) List<Long> list = new ArrayList<>(); list.add(order.getOrderId()); payLog.setOrderList(list.toString().replace("[", "").replace("]", "")); // 支付类型 payLog.setPayType("1"); // 保存支付订单 payLogDao.insertSelective(payLog); redisTemplate.boundHashOps("payLog").put(order.getUserId(), payLog); } /*查询所有订单 张静 2018-12-30*/ @Override public PageResult searchOrder(Integer pageNum, Integer pageSize, Order order) { PageHelper.startPage(pageNum, pageSize); PageHelper.orderBy("order_id desc"); OrderQuery orderQuery = new OrderQuery(); OrderQuery.Criteria criteria = orderQuery.createCriteria(); if (null != order.getOrderIdStr() && !"".equals(order.getOrderIdStr().trim())) { criteria.andOrderIdEqualTo(Long.parseLong(order.getOrderIdStr().trim())); } if (null != order.getStatus() && !"".equals(order.getStatus().trim())) { criteria.andStatusEqualTo(order.getStatus()); } //如果sellerid不为空,表示查询商户自己的数据,否则是运营商查询,查询所有商品数据 张静 2018-12-30 if (order.getSellerId() != null) { criteria.andSellerIdEqualTo(order.getSellerId()); } Page<Order> page = (Page<Order>) orderDao.selectByExample(orderQuery); List<Order> result = page.getResult(); if (null != result && result.size() > 0) { for (Order o : result) { o.setOrderIdStr(o.getOrderId().toString()); } } return new PageResult(page.getTotal(), page.getResult()); } //查询指定订单 张静 2018-12-30 @Override public List<OrderItem> selectOrderById(Long id) { OrderItemQuery query = new OrderItemQuery(); query.createCriteria().andOrderIdEqualTo(id); List<OrderItem> orderItems = orderItemDao.selectByExample(query); if (null != orderItems && orderItems.size() > 0) { for (OrderItem orderItem : orderItems) { orderItem.setIdStr(orderItem.getId().toString()); } } return orderItems; } //更新指定id的订单(发货) 张静 2018-12-30 @Override public void updateOrderById(Order order) { order.setStatus("4"); orderDao.updateByPrimaryKeySelective(order); } /** * 查询商家订单统计 * Author: Mr Liu * Date: 2019/1/2 08:25 */ @Override public List<Map<String, Object>> getSalesByCategory(String sellerId, Date startDate, Date endDate) { SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); List<Map<String, Object>> pieChart = new ArrayList<>(); OrderQuery orderQuery = new OrderQuery(); OrderQuery.Criteria criteria = orderQuery.createCriteria(); criteria.andSellerIdEqualTo(sellerId).andStatusEqualTo("1").andUpdateTimeBetween(startDate, endDate); try { long nowTime = format1.parse(format1.format(new Date())).getTime(); if (endDate.getTime() < nowTime) { if (redisTemplate.opsForValue().get(startDate+sellerId) == null) { pieChart = getOrderStats(orderQuery, startDate, endDate); // 如果是已过去的时间,将其查询出来并存至缓存库中 redisTemplate.opsForValue().set(startDate+sellerId, pieChart); } else { pieChart = (List<Map<String, Object>>) redisTemplate.opsForValue().get(startDate+sellerId); } } else if (endDate.getTime() >= nowTime && startDate.getTime() <= nowTime) { pieChart = getOrderStats(orderQuery, startDate, endDate); } else { pieChart = null; } } catch (ParseException e) { e.printStackTrace(); } return pieChart; } @Override public List<Map<String, Object>> getSalesByCategory2Operator(Date startDate, Date endDate) { SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); List<Map<String, Object>> pieChart = new ArrayList<>(); OrderQuery orderQuery = new OrderQuery(); OrderQuery.Criteria criteria = orderQuery.createCriteria(); criteria.andStatusEqualTo("1").andUpdateTimeBetween(startDate, endDate); try { long nowTime = format1.parse(format1.format(new Date())).getTime(); if (endDate.getTime() < nowTime) { if (redisTemplate.opsForValue().get(startDate) == null) { pieChart = getOrderStats(orderQuery, startDate, endDate); // 如果是已过去的时间,将其查询出来并存至缓存库中 redisTemplate.opsForValue().set(startDate, pieChart); } else { pieChart = (List<Map<String, Object>>) redisTemplate.opsForValue().get(startDate); } } else if (endDate.getTime() >= nowTime && startDate.getTime() <= nowTime) { pieChart = getOrderStats(orderQuery, startDate, endDate); } else { pieChart = null; } } catch (ParseException e) { e.printStackTrace(); } return pieChart; } @Override public List<Order> selectAllOrder() { return orderDao.selectByExample(null); } /** * 商家订单统计抽取出来的类 * Author : Mr Liu * Date : 2019-01-08 20:12 */ private List<Map<String, Object>> getOrderStats(OrderQuery orderQuery, Date startDate, Date endDate) throws ParseException { List<Map<String, Object>> pieChart = new ArrayList<>(); OrderStat orderStat = new OrderStat(); List<Order> orders = orderDao.selectByExample(orderQuery); List<OrderStat> orderStats = new ArrayList<>(); // 遍历订单项,取出payment和goodsId存至orderStats中 for (Order order : orders) { OrderItemQuery orderItemQuery = new OrderItemQuery(); orderItemQuery.createCriteria().andOrderIdEqualTo(order.getOrderId()); List<OrderItem> orderItems = orderItemDao.selectByExample(orderItemQuery); for (OrderItem orderItem : orderItems) { orderStat.setPayment(orderItem.getTotalFee().doubleValue()); orderStat.setGoodsId(orderItem.getGoodsId()); orderStats.add(orderStat); } } Set<Long> category1Ids = new HashSet<>(); // 遍历orderStats,通过goodsId查询出商品所属的一级分类 for (OrderStat stat : orderStats) { Long category1Id = goodsDao.selectcategory1IdByPrimaryKey(stat.getGoodsId()); stat.setCategory1Id(category1Id); category1Ids.add(category1Id); } // 遍历一级分类 for (Long category1Id : category1Ids) { Map<String, Object> map = new HashMap<>(); ItemCat itemCat = itemCatDao.selectByPrimaryKey(category1Id); Double payments = 0.0; for (OrderStat stat : orderStats) { if (stat.getCategory1Id() == category1Id) { payments += stat.getPayment(); } } // 将一级分类的名字作为name,一级分类这段时间的订单总金额作为value存入map中 map.put("value", payments); map.put("name", itemCat.getName()); pieChart.add(map); } return pieChart; } }
true
2f00ad1eb9ae74bb5407663f764e83ac7f3ced88
Java
gayoung3010/project-mate
/project/mate/src/main/java/com/kh/mate/erp/model/vo/EmpBoard.java
UTF-8
798
1.90625
2
[]
no_license
package com.kh.mate.erp.model.vo; import java.io.Serializable; import java.util.Date; import java.util.List; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor public class EmpBoard implements Serializable{ private int boardNo; private String category; private String title; private String content; private String empId; private Date regDate; private int enabled; private List<EmpBoardImage> empBoardImageList; private int readCount; //boardInfo 추가 private int boardInfoNo; private int productNo; private int amount; //상품명 지점명 추가 private String productName; private String empName; private int stock; }
true
108e6088f88c612592fba59e278422f5870b7807
Java
wmfs/hakken
/hakken-android-client/app/src/main/java/uk/co/vurt/hakken/syncadapter/SyncAdapter.java
UTF-8
24,978
1.953125
2
[ "Apache-2.0" ]
permissive
package uk.co.vurt.hakken.syncadapter; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AuthenticatorException; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SyncResult; import android.database.Cursor; import android.database.sqlite.SQLiteConstraintException; import android.net.ParseException; import android.net.Uri; import android.os.Bundle; import android.os.RemoteException; import android.util.Log; import org.apache.http.auth.AuthenticationException; import org.json.JSONException; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import uk.co.vurt.hakken.Constants; import uk.co.vurt.hakken.authenticator.AuthenticatorActivity; import uk.co.vurt.hakken.client.NetworkUtilities; import uk.co.vurt.hakken.client.json.JobDefinitionHandler; import uk.co.vurt.hakken.client.json.TaskDefinitionHandler; import uk.co.vurt.hakken.domain.JSONUtil; import uk.co.vurt.hakken.domain.job.DataItem; import uk.co.vurt.hakken.domain.job.JobDefinition; import uk.co.vurt.hakken.domain.job.Submission; import uk.co.vurt.hakken.domain.job.SubmissionStatus; import uk.co.vurt.hakken.domain.task.TaskDefinition; import uk.co.vurt.hakken.processor.JobProcessor; import uk.co.vurt.hakken.providers.Dataitem; import uk.co.vurt.hakken.providers.Job; import uk.co.vurt.hakken.providers.Task; public class SyncAdapter extends AbstractThreadedSyncAdapter { private static final String TAG = "SyncAdapter"; private static final String LAST_UPDATED_KEY = "uk.co.vurt.hakken.syncadapter.lastUpdated"; private static final boolean NOTIFY_AUTH_FAILURE = true; private final AccountManager accountManager; private final Context context; public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); this.context = context; accountManager = AccountManager.get(context); } private void storeTaskDefinition(ContentProviderClient provider, TaskDefinition definition) { if (definition != null) { Log.d(TAG, "Adding a definition to database: " + definition); ContentValues values = new ContentValues(); values.put(Task.Definitions._ID, definition.getId()); values.put(Task.Definitions.NAME, definition.getName()); values.put(Task.Definitions.DESCRIPTION, definition.getDescription()); //Serialise the object as json, rather than individually storing pages etc. values.put(Task.Definitions.JSON, JSONUtil.getInstance().toJson(definition)); //We need to see if the definition already exists, if it does do an update otherwise do an insert Uri definitionUri = ContentUris.withAppendedId(Task.Definitions.CONTENT_URI, definition.getId()); Cursor cur = null; try { cur = provider.query(definitionUri, null, null, null, null); if (cur.moveToFirst()) { Log.d(TAG, "Updating task definition " + definition.getId()); provider.update(definitionUri, values, null, null); } else { Log.d(TAG, "Inserting new definition " + definition.getId()); provider.insert(Task.Definitions.CONTENT_URI, values); } cur.close(); cur = null; } catch (RemoteException re) { Log.e(TAG, "RemoteException", re); } finally { if (cur != null) { cur.close(); cur = null; } } } else { Log.d(TAG, "Null definition"); } } private void storeDataItem(ContentProviderClient provider, DataItem dataItem, JobDefinition job) { if (dataItem.getValue() != null && !"null".equals(dataItem.getValue())) { Log.d(TAG, "Storing a dataitem for a job."); ContentValues values = new ContentValues(); values.put(Dataitem.Definitions.JOB_ID, job.getId()); values.put(Dataitem.Definitions.PAGENAME, dataItem.getPageName()); values.put(Dataitem.Definitions.NAME, dataItem.getName()); values.put(Dataitem.Definitions.TYPE, dataItem.getType()); values.put(Dataitem.Definitions.VALUE, dataItem.getValue()); values.put(Dataitem.Definitions.SUBMIT, "false"); try { provider.insert(Dataitem.Definitions.CONTENT_URI, values); } catch (SQLiteConstraintException e) { try { //already present so do an update instead Cursor diCursor = provider.query(Dataitem.Definitions.CONTENT_URI, new String[]{Dataitem.Definitions._ID, Dataitem.Definitions.VALUE}, Dataitem.Definitions.PAGENAME + " = ?" + " AND " + Dataitem.Definitions.NAME + " = ?" + " AND " + Dataitem.Definitions.TYPE + " = ?", new String[]{values.getAsString(Dataitem.Definitions.PAGENAME), values.getAsString(Dataitem.Definitions.NAME), values.getAsString(Dataitem.Definitions.TYPE)}, Dataitem.Definitions.DEFAULT_SORT_ORDER); if (diCursor != null) { diCursor.moveToFirst(); //only update if the value has changed. if (!dataItem.getValue().equals(diCursor.getString(1))) { ContentValues value = new ContentValues(); value.put(Dataitem.Definitions.VALUE, dataItem.getValue()); provider.update(ContentUris.withAppendedId(Dataitem.Definitions.CONTENT_URI, diCursor.getLong(0)), value, null, null); } diCursor.close(); diCursor = null; } } catch (RemoteException re) { Log.e(TAG, "RemoteException", re); } } catch (RemoteException re) { Log.e(TAG, "RemoteException", re); } values = null; } } @Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { String authToken = null; try { authToken = accountManager.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, NOTIFY_AUTH_FAILURE); submitCompletedJobs(account, authToken, provider); syncTaskDefinitions(account, authToken, provider); syncJobsFromServer(account, authToken, provider); logSyncDateTime(); } catch (Exception e) { handleException(e, authToken, syncResult); } } private void logSyncDateTime() { Log.e("CK TAG", "logSyncDateTime"); ContentValues values = new ContentValues(); values.remove("SYNC_DATE_TIME"); values.put("SYNC_DATE_TIME", new Date().toString()); } private synchronized void submitCompletedJobs(Account account, String authToken, ContentProviderClient provider) throws AuthenticatorException, IOException, RemoteException { Log.d(TAG, "submitCompletedJobs() called."); //Find which jobs have been completed. Cursor jobCursor = provider.query(Job.Definitions.CONTENT_URI, new String[]{Job.Definitions._ID, Job.Definitions.REMOTE_ID, Job.Definitions.TASK_DEFINITION_ID}, Job.Definitions.STATUS + " = ?", new String[]{"COMPLETED"}, null); if (jobCursor != null) { jobCursor.moveToFirst(); //for each completed job: while (!jobCursor.isAfterLast()) { Long jobId = jobCursor.getLong(0); Log.d(TAG, "creating submission for job " + jobId); Submission submission = new Submission(); submission.setJobId(jobId); submission.setRemoteId(jobCursor.getString(1)); String taskDefinitionName = "unknown"; Cursor taskDefCursor = provider.query(Uri.withAppendedPath(Task.Definitions.CONTENT_URI, String.valueOf(jobCursor.getLong(2))), new String[]{Task.Definitions.NAME}, null, null, null); if (taskDefCursor != null) { taskDefCursor.moveToFirst(); taskDefinitionName = taskDefCursor.getString(0); } taskDefCursor.close(); taskDefCursor = null; submission.setTaskDefinitionName(taskDefinitionName); submission.setUsername(account.name); // retrieve dataitems for them and combine into a submission Cursor diCursor = provider.query(Dataitem.Definitions.CONTENT_URI, new String[]{Dataitem.Definitions.PAGENAME, Dataitem.Definitions.NAME, Dataitem.Definitions.TYPE, Dataitem.Definitions.VALUE, Dataitem.Definitions.SUBMIT}, Dataitem.Definitions.JOB_ID + " = ?", new String[]{"" + jobId}, null); if (diCursor != null) { diCursor.moveToFirst(); while (!diCursor.isAfterLast()) { // Only submit items where submit status is set to true Log.d(TAG, "Submit status for : " + diCursor.getString(1) + " " + diCursor.getString(4)); if (diCursor.getString(4).equals("true")) { DataItem dataItem = new DataItem(diCursor.getString(0), diCursor.getString(1), diCursor.getString(2), diCursor.getString(3)); submission.addDataItem(dataItem); } diCursor.moveToNext(); } diCursor.close(); diCursor = null; } //send completed job to server SubmissionStatus status = NetworkUtilities.submitData(context, account, submission); //if successful, delete completed job and dataitems. if (status != null) { if (status.isValid()) { Log.d(TAG, "Deleting old dataitems"); provider.delete(Dataitem.Definitions.CONTENT_URI, Dataitem.Definitions.JOB_ID + " = ?", new String[]{"" + submission.getJobId()}); Log.d(TAG, "Deleting job: " + Uri.withAppendedPath(Job.Definitions.CONTENT_URI, "" + submission.getJobId())); provider.delete(Uri.withAppendedPath(Job.Definitions.CONTENT_URI, "" + submission.getJobId()), null, null); } else { Log.d(TAG, "Submitting job " + Uri.withAppendedPath(Job.Definitions.CONTENT_URI, "" + submission.getJobId()) + " failed."); ContentValues values = new ContentValues(); values.put(Job.Definitions.STATUS, "SERVER_ERROR"); values.put(Job.Definitions.SERVER_ERROR, status.getMessage()); provider.update(Uri.withAppendedPath(Job.Definitions.CONTENT_URI, "" + submission.getJobId()), values, null, null); } } jobCursor.moveToNext(); } jobCursor.close(); jobCursor = null; } } private synchronized void syncTaskDefinitions(Account account, String authToken, ContentProviderClient provider) throws AuthenticatorException, IOException, RemoteException, AuthenticationException, ParseException, JSONException { Log.d(TAG, "syncTaskDefintions() called."); List<Long> oldDefinitionIds = new ArrayList<>(); Cursor definitionCursor = provider.query(Task.Definitions.CONTENT_URI, new String[] {Task.Definitions._ID}, null, null, null); if (definitionCursor != null) { while (definitionCursor.moveToNext()) { oldDefinitionIds.add(definitionCursor.getLong(0)); } } //insert again TaskDefinitionAdapter taskAdapter = new TaskDefinitionAdapter(provider); NetworkUtilities.fetchTaskDefinitions(context, account, new Date(getLastUpdatedDate(account)), taskAdapter); //delete any definitions not added by latest sync for (Long oldDefinitionId : oldDefinitionIds) { if (!taskAdapter.getAddedDefinitionIds().contains(oldDefinitionId)) { provider.delete(Uri.withAppendedPath(Task.Definitions.CONTENT_URI, "" + oldDefinitionId), null, null); } } } private synchronized void syncJobsFromServer(Account account, String authToken, ContentProviderClient provider) throws AuthenticatorException, IOException, RemoteException, AuthenticationException, ParseException, JSONException { List<JobDefinitionId> oldJobIds = new ArrayList<>(); Cursor jobCursor = provider.query(Job.Definitions.CONTENT_URI, Job.Definitions.ALL, null, null, null); if (jobCursor != null) { jobCursor.moveToFirst(); while (!jobCursor.isAfterLast()) { boolean adhoc = jobCursor.getInt(JobProcessor.COLUMN_INDEX_JOB_ADHOC) > 0; long oldJobId = jobCursor.getLong(JobProcessor.COLUMN_INDEX_JOB_ID); if (!adhoc) { Log.d(TAG, "Marking old job: " + oldJobId); oldJobIds.add(new JobDefinitionId( jobCursor.getLong(JobProcessor.COLUMN_INDEX_JOB_TASKDEFINITION_ID), jobCursor.getString(JobProcessor.COLUMN_INDEX_JOB_REMOTE_ID))); } else { Log.d(TAG, "skipping adhoc job: " + oldJobId); } jobCursor.moveToNext(); } jobCursor.close(); jobCursor = null; } JobDefinitionAdapter jobAdapter = new JobDefinitionAdapter(provider); NetworkUtilities.fetchJobs(context, account, new Date(getLastUpdatedDate(account)), jobAdapter); long newLastUpdated = System.currentTimeMillis(); oldJobIds.removeAll(jobAdapter.getAddedJobIds()); for (JobDefinitionId jobToDeleteId : oldJobIds) { // provider.delete(ContentUris.withAppendedId(Job.Definitions.CONTENT_URI, jobToDeleteId), null, null); Log.d(TAG, "Deleting " + jobToDeleteId); provider.delete(Job.Definitions.CONTENT_URI, Job.Definitions.TASK_DEFINITION_ID + " = ? and " + Job.Definitions.REMOTE_ID + " = ?", new String[]{String.valueOf(jobToDeleteId.taskDefinitionId), jobToDeleteId.remoteId}); } setLastUpdatedDate(account, newLastUpdated); } private void handleException(Exception e, String authtoken, SyncResult syncResult) { if (e instanceof AuthenticatorException) { syncResult.stats.numParseExceptions++; Log.e(TAG, "AuthenticatorException", e); } else if (e instanceof IOException) { Log.e(TAG, "IOException", e); syncResult.stats.numIoExceptions++; } else if (e instanceof AuthenticationException) { accountManager.invalidateAuthToken(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, authtoken); // The numAuthExceptions require user intervention and are // considered hard errors. // We automatically get a new hash, so let's make SyncManager retry // automatically. syncResult.stats.numIoExceptions++; Log.e(TAG, "AuthenticationException", e); } else if (e instanceof RemoteException) { syncResult.stats.numIoExceptions++; Log.e(TAG, "RemoteException", e); } else { syncResult.stats.numIoExceptions++; Log.e(TAG, "Unhandled Exception", e); } } private long getLastUpdatedDate(Account account) { String lastUpdatedString = accountManager.getUserData(account, LAST_UPDATED_KEY); if (lastUpdatedString != null && lastUpdatedString.length() > 0) { return Long.parseLong(lastUpdatedString); } else { return 0; } } private void setLastUpdatedDate(Account account, long lastUpdated) { accountManager.setUserData(account, LAST_UPDATED_KEY, Long.toString(lastUpdated)); } private static class JobDefinitionId { private Long taskDefinitionId; private String remoteId; JobDefinitionId(Long taskDefinitionId, String remoteId) { this.taskDefinitionId = taskDefinitionId; this.remoteId = remoteId; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((remoteId == null) ? 0 : remoteId.hashCode()); result = prime * result + ((taskDefinitionId == null) ? 0 : taskDefinitionId.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JobDefinitionId other = (JobDefinitionId) obj; if (remoteId == null) { if (other.remoteId != null) return false; } else if (!remoteId.equals(other.remoteId)) return false; if (taskDefinitionId == null) { if (other.taskDefinitionId != null) return false; } else if (!taskDefinitionId.equals(other.taskDefinitionId)) return false; return true; } public String toString() { return remoteId + " (taskDefinitionId " + taskDefinitionId + ")"; } } private class TaskDefinitionAdapter implements TaskDefinitionHandler { private ContentProviderClient provider; private List<Long> addedDefinitionIds; public TaskDefinitionAdapter(ContentProviderClient provider) { this.provider = provider; addedDefinitionIds = new ArrayList<>(); } @Override public void handle(TaskDefinition newTask) { addedDefinitionIds.add(newTask.getId()); storeTaskDefinition(provider, newTask); } public List<Long> getAddedDefinitionIds() { return addedDefinitionIds; } } private class JobDefinitionAdapter implements JobDefinitionHandler { private ContentProviderClient provider; private List<JobDefinitionId> addedJobIds; public JobDefinitionAdapter(ContentProviderClient provider) { this.provider = provider; addedJobIds = new ArrayList<>(); } @Override public void handle(JobDefinition job) { Log.d(TAG, "Adding a job to database: " + job); JobDefinitionId newJobId = new JobDefinitionId(job.getTaskDefinitionId(), job.getRemoteId()); addedJobIds.add(newJobId); //retrieve job (if it exists) try { String whereClause = Job.Definitions.REMOTE_ID + " = ? AND " + Job.Definitions.TASK_DEFINITION_ID + " = ?"; String[] whereArgs = new String[]{job.getRemoteId(), "" + job.getTaskDefinitionId()}; Log.d(TAG, "RemoteID: " + job.getRemoteId() + " Task Def Id: " + job.getTaskDefinitionId()); Cursor jobCursor = provider.query(Job.Definitions.CONTENT_URI, new String[]{Job.Definitions._ID, Job.Definitions.MODIFIED, Job.Definitions.STATUS}, whereClause, whereArgs, null); ContentValues values = new ContentValues(); values.put(Job.Definitions.REMOTE_ID, job.getRemoteId()); values.put(Job.Definitions.NAME, job.getName()); values.put(Job.Definitions.TASK_DEFINITION_ID, job.getTaskDefinitionId()); values.put(Job.Definitions.CREATED, job.getCreated().getTime()); if (job.getDue() != null) { values.put(Job.Definitions.DUE, job.getDue().getTime()); } else { Log.e(TAG, "Job has no due date!"); } values.put(Job.Definitions.STATUS, job.getStatus()); values.put(Job.Definitions.NOTES, "null".equals(job.getNotes()) ? "" : job.getNotes()); Log.e(TAG, "CK_TAG DESCRIPTION: " + job.getDescription()); values.put(Job.Definitions.DESCRIPTION, "null".equals(job.getDescription()) ? "" : job.getDescription()); if (job.getGroup() != null) { values.put(Job.Definitions.GROUP, job.getGroup()); } // if job on device & device job isn't modified, then update job (to allow for changes from other sources) // if job not on device, then create it on device boolean storeDataItems = false; boolean resetStatus = false; long internalId = -1; Log.d(TAG, "jobCursor: " + jobCursor); Log.d(TAG, "count: " + jobCursor.getCount()); if (jobCursor != null && jobCursor.getCount() > 0) { // job exists, so check to see if we can update it. jobCursor.moveToFirst(); Log.d(TAG, "_id: " + jobCursor.getLong(0)); Log.d(TAG, "modified: " + jobCursor.getInt(1)); Log.d(TAG, "status: " + jobCursor.getString(2)); internalId = jobCursor.getLong(0); boolean modified = jobCursor.getInt(1) > 0; String status = jobCursor.getString(2); jobCursor.close(); jobCursor = null; if (!modified && !"SERVER_ERROR".equals(status)) { //update job Log.d(TAG, "Updating job " + newJobId); values.put(Job.Definitions.STATUS, "UPDATING"); int count = provider.update(ContentUris.withAppendedId(Job.Definitions.CONTENT_URI, internalId), values, whereClause, whereArgs); Log.d(TAG, "Updated " + count + " rows"); resetStatus = true; storeDataItems = true; } } else { // job doesn't exist, so insert it. //storeTaskDefinition(provider, newJob.getDefinition()); //create job Log.d(TAG, "Inserting new job " + newJobId); Uri providerUri = provider.insert(Job.Definitions.CONTENT_URI, values); Log.d(TAG, "Inserted job as " + providerUri); storeDataItems = true; // set the id to the last part of the provider uri // TODO: improve this Long jobId = Long.valueOf(providerUri.toString().substring( providerUri.toString().lastIndexOf("/") + 1)); Log.i(TAG, "New job id=" + jobId); internalId = jobId; job.setId(jobId); } if (storeDataItems) { for (DataItem item : job.getDataItems()) { storeDataItem(provider, item, job); } if (resetStatus) { values = new ContentValues(); values.put(Job.Definitions.STATUS, job.getStatus()); provider.update(ContentUris.withAppendedId(Job.Definitions.CONTENT_URI, internalId), values, null, null); } } } catch (RemoteException re) { Log.e(TAG, "Unable to store job definition.", re); } } public List<JobDefinitionId> getAddedJobIds() { return addedJobIds; } } }
true
361464599eb67dfe4318058a4111d14d3c244b9e
Java
f981545521/iblog2
/iblog-common/src/main/java/cn/acyou/iblog/utility/XmlUtil.java
UTF-8
14,370
2.46875
2
[]
no_license
package cn.acyou.iblog.utility; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; /** * DOM4j XML 工具类 */ public final class XmlUtil { /** * 使用的查询子孙节点的路径 */ private static final String SELECT_PATH = ".//"; /** * 默认编码 */ private static final String DEFAULT_ENCODING = "UTF-8"; private XmlUtil() { } /** * 描述 取得当前节点特定子节点的正文,只取第一个 * * @param element 当前XML节点 * @param fieldCode 正文内容 * @return */ public static String getSonFieldContent(final Element element, final String fieldCode) { if (element == null) { return null; } String content = null; Element ele = element.element(fieldCode); if (ele != null) { content = ele.getText(); } return content; } /** * 描述 取得当前节点特定子孙节点的正文,只取第一个 * * @param element 操作的xml元素 * @param fieldCode 栏位名称 * @return */ public static Element getDesFieldElement(final Element element, final String fieldCode) { Element tagertElement = null; List<Element> list = (List<Element>) element.selectNodes(SELECT_PATH + fieldCode); if (list.size() > 0) { tagertElement = list.get(0); } return tagertElement; } /** * 描述 取得当前节点特定子孙节点的正文,只取第一个 * * @param text 传入报文 * @param fieldCode 标签代码 * @return 标签内容 * @throws DocumentException */ public static String getDesFieldText(final String text, final String fieldCode) throws DocumentException { Element rootEle = DocumentHelper.parseText(text).getRootElement(); Element desFieldEle = getDesFieldElement(rootEle, fieldCode); if (desFieldEle != null) { return desFieldEle.getText(); } else { return null; } } /** * 描述 取得当前节点特定子孙节点的正文,制定个数 * * @param text 传入报文 * @param fieldCode 标签代码 * @param index 处理的元素索引 * @return 标签内容 * @throws DocumentException */ public static String getDesFieldTextByIndex(final String text, final String fieldCode, final int index) throws DocumentException { Element rootEle = DocumentHelper.parseText(text).getRootElement(); List<Element> eleList = (List<Element>) rootEle.selectNodes(SELECT_PATH + fieldCode); if (eleList.size() > index) { return eleList.get(index).getText(); } else { return null; } } /** * 描述 取得子孙节点集合 * * @param element 操作的xml元素 * @param fieldCode 栏位名称 * @return 正文内容 */ public static List<Element> getDesFieldElementList(final Element element, final String fieldCode) { return element.selectNodes(SELECT_PATH + fieldCode); } /** * 描述 取得当前节点下所有拥有当前属性的元素 * * @param element 当前元素 * @param fieldCode 查找属性名称 * @return */ public static List<Element> getEleListByAttr(final Element element, final String fieldCode) { // 返回数据 List<Element> eleList = new ArrayList<Element>(); // 查找并循环添加 List<Attribute> attrList = element.selectNodes(SELECT_PATH + "@" + fieldCode); for (Attribute attr : attrList) { eleList.add(attr.getParent()); } // 返回 return eleList; } /** * 描述 取得当前节点下所有拥有当前属性的元素 * * @param msgText 当前元素 * @param path 查找属性名称 * @return */ public static List<Element> getEleListByPath(final String msgText, final String path) { // 返回数据 List<Element> eleList = new ArrayList<Element>(); try { Document document; document = DocumentHelper.parseText(msgText); eleList = document.selectNodes(path); } catch (DocumentException e) { e.printStackTrace(); } // 返回 return eleList; } /** * 描述 一次性增加多个子节点 * * @param fatherEle 父亲节点 * @param sonEleList 要增加的子节点元素 */ public static void addElements(final Element fatherEle, final List<Element> sonEleList) { for (Element ele : sonEleList) { fatherEle.add((Element) ele.clone()); } } /** * 描述 增加子元素 * * @param fatherEle 父亲节点 * @param sonEleName 儿子节点名 * @param sonEleContent 儿子节点内容 * @return 儿子节点 */ public static Element addElement(final Element fatherEle, final String sonEleName, final String sonEleContent) { // 创建子节点 Element ele = DocumentHelper.createElement(sonEleName); if (StringUtils.isNotBlank(sonEleContent)) { ele.setText(sonEleContent); } // 关联 fatherEle.add(ele); // 返回 return ele; } /** * 描述 最后最后一级的子节点,如果传入数据为空不增加 * * @param fatherEle 父亲节点 * @param sonEleName * @param sonEleContent * @return */ public static Element addFinalSonElement(final Element fatherEle, final String sonEleName, final String sonEleContent) { // 创建子节点 Element ele = null; // 增加 if (StringUtils.isNotBlank(sonEleContent)) { ele = DocumentHelper.createElement(sonEleName); ele.setText(sonEleContent); // 关联 fatherEle.add(ele); } // 返回 return ele; } /** * 描述 取得XMl字符串中的指定路径字符 * * @param text * @param url * @return */ public static String getUrlElementText(final String text, final String url) { // 返回值 String resultText = null; // 转化XML Element busiElement; try { busiElement = DocumentHelper.parseText(text).getRootElement(); List<Element> eleList = busiElement.selectNodes(url); if (eleList.size() > 0) { resultText = ((Element) busiElement.selectNodes(url).get(0)).getText(); } } catch (DocumentException e) { e.printStackTrace(); } // 返回 return resultText; } /** * 描述 * * @param doc * @param url * @return */ public static String getUrlElementText(Document doc, final String url) { Node node = doc.selectSingleNode(url); if (node == null) { return null; } return node.getText(); } /** * 描述 格式化xml字符串 * * @param xmlText xml字符串 * @return 格式化后的字符 * @throws Exception */ public static String formatXml(final String xmlText) throws Exception { // 返回字符串 String reText; try { reText = formatXml(xmlText, DEFAULT_ENCODING); } catch (Exception e) { throw new Exception(e.getMessage()); } // 返回 return reText; } /** * 描述 格式化xml字符串 * * @param xmlText xml字符串 * @param inEncoding 字符编码 * @return 格式化后的字符 * @throws Exception */ public static String formatXml(final String xmlText, final String inEncoding) throws Exception { String encoding = inEncoding; // 返回字符串 String reText; if (StringUtils.isBlank(encoding)) { encoding = DEFAULT_ENCODING; } // 转化 try { // 将字符串格式转换成document对象 Document document = DocumentHelper.parseText(xmlText); // 注意,用这种方式来创建指定格式的format OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(encoding); // 创建String输出流 StringWriter out = new StringWriter(); // 包装String流 XMLWriter writer = new XMLWriter(out, format); // 将当前的document对象写入底层流out中 writer.write(document); writer.close(); reText = out.toString(); } catch (Exception e) { String errTagMsg = "数据格式化失败!"; throw new Exception(errTagMsg); } // 返回 return reText; } /** * 描述 复制XML元素的值到对应的对象属性当中 * * @param obj 配置对象 * @param ele XML元素 * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException */ public static void copyEleToAttr(final Object obj, final Element ele) throws IllegalArgumentException, IllegalAccessException, InstantiationException, ClassNotFoundException { // 获取f对象对应类中的所有属性域 Field[] fields = obj.getClass().getDeclaredFields(); for (int i = 0, len = fields.length; i < len; i++) { // 对于每个属性,获取属性名 String fieldName = fields[i].getName(); fields[i].setAccessible(true); /** * String属性直接进行赋值,如果是复杂类,进行下一步赋值 */ if (fields[i].getType().equals(String.class)) { String eleContent = XmlUtil.getSonFieldContent(ele, fieldName); if (eleContent != null && !eleContent.equals("")) { fields[i].set(obj, eleContent); } } else if (fields[i].getType().equals(List.class)) { String eleName = fieldName.substring(0, fieldName.length() - 4); List<Element> eleList = ele.elements(eleName); List<Object> field = (List<Object>) fields[i].get(obj); // 取得泛型类型 Type fc = fields[i].getGenericType(); ParameterizedType pt = (ParameterizedType) fc; Class driveClass = (Class) pt.getActualTypeArguments()[0]; try { for (Element singleEle : eleList) { Object singObjct = driveClass.newInstance(); // 判断是否是字符串 if (driveClass.equals(String.class)) { singObjct = singleEle.getText(); } else { copyEleToAttr(singObjct, singleEle); } field.add(singObjct); } } catch (Exception e) { for (Element singleEle : eleList) { String eleContent = singleEle.getTextTrim(); if (eleContent != null && !eleContent.equals("")) { field.add(eleContent); } } } } else { Object fieldObject = fields[i].get(obj); Element fieldEle = ele.element(fieldName); if (fieldObject != null && fieldEle != null) { copyEleToAttr(fieldObject, fieldEle); } } } } /** * 描述 复制对应的对象属性当到XML元素的值中 * * @param obj 配置对象 * @param ele XML元素 * @throws IllegalArgumentException * @throws IllegalAccessException */ public static void copyAttrToEle(final Object obj, final Element ele) throws IllegalArgumentException, IllegalAccessException { // 获取f对象对应类中的所有属性域 Field[] fields = obj.getClass().getDeclaredFields(); for (int i = 0, len = fields.length; i < len; i++) { // 对于每个属性,获取属性名 String fieldName = fields[i].getName(); fields[i].setAccessible(true); // 过滤不处理的对象 if (Modifier.isStatic(fields[i].getModifiers())) { continue; } /** * String属性直接进行赋值,如果是复杂类,进行下一步赋值 */ if (fields[i].getType().equals(String.class)) { XmlUtil.addFinalSonElement(ele, fieldName, (String) fields[i].get(obj)); } else if (fields[i].getType().equals(List.class)) { List<Object> fieldList = (List<Object>) fields[i].get(obj); for (Object object : fieldList) { if (object.getClass().equals(String.class)) { XmlUtil.addElement(ele, fieldName, (String) object); } else { copyAttrToEle(object, XmlUtil.addElement(ele, fieldName, null)); } } } else { Object fieldObject = fields[i].get(obj); if (fieldObject != null) { Element fieldEle = XmlUtil.addElement(ele, fieldName, null); copyAttrToEle(fields[i].get(obj), fieldEle); } } } } }
true
129fb7bf3f8a94c1921dc1bc60046cf03e3f57a5
Java
renchsan/Java-Projects
/CST3613/ComparableTriangle.java
UTF-8
903
3.984375
4
[]
no_license
/* Matthew Rencher * CST3613 * ComparableTriangle * * Use project01 and Triangle class to design ComparableTriangle * that implements compareTo method which compares area of two Triangle objects * */ public abstract class ComparableTriangle extends Triangle implements Cloneable, Comparable<Triangle> { // Construct a Triangle with specific properties public ComparableTriangle(double side1, double side2, double side3) { super(side1, side2, side3); } @Override public int compareTo(ComparableTriangle o) { if (getArea() > o.getArea()) return 1; else if (getArea() < o.getArea()) return -1; else return 0; } @Override public String toString() { return super.toString() + " Area: " + getArea(); } public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e){ return null; } } }
true
829d874c4f98b0de422326c34c1843975718648b
Java
kumar-kondiker/RoomDatabaseApp
/app/src/main/java/com/kumar/androidarchitecture/NoteDao.java
UTF-8
594
2.03125
2
[]
no_license
package com.kumar.androidarchitecture; import java.util.List; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.Query; import androidx.room.Update; @Dao public interface NoteDao { @Insert public void insert(Note note); @Update public void update(Note note); @Delete public void delete(Note note); @Query("DELETE FROM notes_table") public void removeNotes(); @Query("SELECT * FROM notes_table ORDER BY proirity DESC") LiveData<List<Note>> getAllNotes(); }
true
507d9ee4cd0c7cd0dab002e97d16195aac18c85b
Java
praveen8959/IntraBankPaymentTransferSystem
/src/main/java/com/norway/mastercard/ibpts/model/AccountDetails.java
UTF-8
884
2.078125
2
[]
no_license
package com.norway.mastercard.ibpts.model; import java.math.BigDecimal; import java.time.LocalDateTime; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; /** * The AccountDetails is a model which is reused in account controller by multiple operations, and used in service class. * Holds the account information and transaction details. */ @Builder @Getter @JsonInclude(value = Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class AccountDetails { private int accountId; private BigDecimal balance; private BigDecimal amount; private String currencyCode; private TransactionType type; private LocalDateTime transactionDate; }
true
b45d1cbd7736d24bb94c9a3f23c52bc0a5de71be
Java
ometa/codepath-week4-project
/app/src/main/java/com/codepath/apps/twitterclient/lib/PreferenceManager.java
UTF-8
2,629
2.5625
3
[ "Apache-2.0" ]
permissive
package com.codepath.apps.twitterclient.lib; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import com.codepath.apps.twitterclient.models.User; /** * Thanks to https://yakivmospan.wordpress.com/2014/03/11/best-practice-sharedpreferences/ */ public class PreferenceManager { private static final String ROOT_KEY = "Settings"; private static PreferenceManager sInstance; private final SharedPreferences mPref; private PreferenceManager(Context context) { mPref = context.getSharedPreferences(ROOT_KEY, 0); } public static synchronized void initializeInstance(Context context) { if (sInstance == null) { sInstance = new PreferenceManager(context); } } public static synchronized PreferenceManager getInstance() { if (sInstance == null) { throw new IllegalStateException(PreferenceManager.class.getSimpleName() + " is not initialized, call initializeInstance(..) method first."); } return sInstance; } // setters public void set(String key, String value) { mPref.edit().putString(key, value).commit(); } public void set(String key, long value) { mPref.edit().putLong(key, value).commit(); } public final static String PREFIX = "current_user_"; public void set(User user) { Log.d("prefs", "saving user data: " + user.toString()); mPref.edit().putString(PREFIX + "screen_name", user.getScreenName()); mPref.edit().putString(PREFIX + "name", user.getName()); mPref.edit().putLong(PREFIX + "uid", user.getUid()); mPref.edit().putString(PREFIX + "profile_image_url", user.getProfileImageUrl()); mPref.edit().putString(PREFIX + "profile_image_url_https", user.getProfileImageUrlHttps()); } // getters public long getLong(String key) { return mPref.getLong(key, 0); } public String getString(String key) { return mPref.getString(key, null); } // general function public void remove(String key) { mPref.edit().remove(key).commit(); } public boolean clear() { return mPref.edit().clear().commit(); } public void removeUser() { Log.d("prefs", "clearing user data"); SharedPreferences.Editor e = mPref.edit(); e.remove(PREFIX + "screen_name"); e.remove(PREFIX + "name"); e.remove(PREFIX + "uid"); e.remove(PREFIX + "profile_image_url"); e.remove(PREFIX + "profile_image_url_https"); e.commit(); } }
true
1d9b2bb51e6e1d88c92d04af6b835459b98252d7
Java
VarunAyyappan/Student2
/Advanced/jrJava/aboutString/AboutString4.java
UTF-8
900
4.25
4
[]
no_license
package jrJava.aboutString; public class AboutString4 { public static void main(String[] args) { // trim(): will trim the preceding and trailing spaces (But, the ones in the middle) // replace(): will replace old with new one. // Both operations will create new String objects. So, they are expensive ops. String text = " Hel lo "; // has two preceding spaces and one trailing space. String trimmed = text.trim(); System.out.println(trimmed); String replaced = trimmed.replace(" ", ""); System.out.println(replaced); // Do more of your own experiments. // You can chain the method calls as followings. // Each method call will return newly created String object. // So, the whole operating is expensive. The following will create // total of three string objects. text = text.trim().replace(" ", "").substring(2); System.out.println(text); } }
true
bb05080ddf7d809c39cc8983127f35366a1de35b
Java
vert-x/jca-adaptor
/ra/src/main/java/org/vertx/java/resourceadapter/VertxResourceAdapter.java
UTF-8
6,147
1.671875
2
[ "Apache-2.0" ]
permissive
/* * IronJacamar, a Java EE Connector Architecture implementation * Copyright 2013, Red Hat Inc, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.vertx.java.resourceadapter; import org.vertx.java.resourceadapter.inflow.VertxActivation; import org.vertx.java.resourceadapter.inflow.VertxActivationSpec; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import javax.resource.ResourceException; import javax.resource.spi.ActivationSpec; import javax.resource.spi.BootstrapContext; import javax.resource.spi.Connector; import javax.resource.spi.ResourceAdapter; import javax.resource.spi.ResourceAdapterInternalException; import javax.resource.spi.TransactionSupport; import javax.resource.spi.endpoint.MessageEndpointFactory; import javax.resource.spi.work.WorkManager; import javax.transaction.xa.XAResource; /** * VertxResourceAdapter is the Resource Adapter used to interact with a Vert.x cluster. * * It uses a distributed event bus from Vert.x to send message, and receives message by registering a Vert.x Handler. * * @version $Revision: $ */ @Connector( reauthenticationSupport = false, displayName = {"Vert.x Resource Adapter"}, description = {"VertxResourceAdapter is the Resource Adapter used to interact with a Vert.x cluster."}, eisType = "vertx", transactionSupport = TransactionSupport.TransactionSupportLevel.NoTransaction) public class VertxResourceAdapter implements ResourceAdapter, java.io.Serializable { /** * serialVersionUID */ private static final long serialVersionUID = 1130617878526175034L; /** The logger */ private static Logger log = Logger.getLogger(VertxResourceAdapter.class.getName()); /** The activations by activation spec */ private ConcurrentHashMap<VertxActivationSpec, VertxActivation> activations; private WorkManager workManager; /** * Default constructor */ public VertxResourceAdapter() { this.activations = new ConcurrentHashMap<VertxActivationSpec, VertxActivation>(); } /** * This is called during the activation of a message endpoint. * * @param endpointFactory A message endpoint factory instance. * @param spec An activation spec JavaBean instance. * @throws ResourceException generic exception */ public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException { VertxActivation activation = new VertxActivation(this, endpointFactory, (VertxActivationSpec)spec); activations.put((VertxActivationSpec)spec, activation); activation.start(); log.finest("endpointActivation()"); } /** * This is called when a message endpoint is deactivated. * * @param endpointFactory A message endpoint factory instance. * @param spec An activation spec JavaBean instance. */ public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) { VertxActivation activation = activations.remove(spec); if (activation != null) activation.stop(); log.finest("endpointDeactivation()"); } /** * This is called when a resource adapter instance is bootstrapped. * * @param ctx A bootstrap context containing references * @throws ResourceAdapterInternalException indicates bootstrap failure. */ public void start(BootstrapContext ctx) throws ResourceAdapterInternalException { log.finest("sets up configuration."); this.workManager = ctx.getWorkManager(); } public WorkManager getWorkManager() { return workManager; } /** * This is called when a resource adapter instance is undeployed or * during application server shutdown. * * It will stop all Vert.x embedded platform. * */ public void stop() { log.finest("stop()"); this.workManager = null; this.activations.clear(); VertxPlatformFactory.instance().clear(); // it seems after stop() is called, // there are still some background threads running on vert.x // waiting for 1 second try { Thread.sleep(1000); } catch (InterruptedException e) { ; } } /** * This method is called by the application server during crash recovery. * * @param specs An array of ActivationSpec JavaBeans * @throws ResourceException generic exception * @return An array of XAResource objects */ public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException { log.finest("getXAResources()"); return null; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return super.hashCode(); } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; VertxResourceAdapter other = (VertxResourceAdapter) obj; return super.equals(other); } }
true
88946d32c4118c8f0578f689155ebe0b8a43fae6
Java
syedahaider97/Uniprocessor-Scheduling-Algortihms
/Process.java
UTF-8
2,338
3.484375
3
[]
no_license
public class Process { private String processName; private int timeRequired; //Time needed till completion private int timeEntered; //Time the process was "created" private int timeRunning = 1; //Used to measure consecutive iterations private int level = 0; //Used to keep track of queue level (feedback only) //Constructor used to create processes when parsing files public Process(String name, int required, int enter) { processName = name; timeRequired = required; timeEntered = enter; } //Copy Constructor public Process(Process p) { processName = p.getName(); timeRequired = p.getTimeRequired(); timeEntered = p.getTimeEntered(); timeRunning = p.getTimeRunning(); } /* * Getter and Setter methods */ public String getName() { return processName; } public int getTimeEntered() { return timeEntered; } public int getTimeRequired() { return timeRequired; } public int getTimeRunning() { return timeRunning; } public int getLevel() { return level; } public void setLevel(int newLevel) { level = newLevel; } public void resetTimeRunning() { timeRunning = 1; } public void increment(){ timeRunning++; } public void decrement() { timeRequired--; } /* * For printing if necessary */ public String toString() { return "Process [processName=" + processName + ", timeRequired=" + timeRequired + ", timeEntered=" + timeEntered + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((processName == null) ? 0 : processName.hashCode()); result = prime * result + timeEntered; result = prime * result + timeRequired; return result; } /* * Check to see if two processes are equal to each other */ public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Process other = (Process) obj; if (processName == null) { if (other.processName != null) return false; } else if (!processName.equals(other.processName)) return false; if (timeEntered != other.timeEntered) return false; if (timeRequired != other.timeRequired) return false; return true; } }
true
d69f11fab1b0d40b38a6e7a709990b712b3abb06
Java
pisceslj/InvoiceRecognition
/src/datamodels/InvoiceResult.java
UTF-8
872
2.234375
2
[]
no_license
package datamodels; /** * Created by SPREADTRUM\jiannan.liu on 17-3-31. */ public class InvoiceResult { private InvoiceInfo invoiceInfo; private String sign; //纳税人识别号 private String taxpayerNumber; public InvoiceResult(String sign, InvoiceInfo invoiceInfo) { this.sign = sign; this.invoiceInfo = invoiceInfo; } public String getTaxpayerNumber() { return taxpayerNumber; } public void setTaxpayerNumber(String taxpayerNumber) { this.taxpayerNumber = taxpayerNumber; } public InvoiceInfo getInvoiceInfo() { return invoiceInfo; } public void setInvoiceInfo(InvoiceInfo invoiceInfo) { this.invoiceInfo = invoiceInfo; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
true
2d096629bfd52754d92016a7464ade594e511e9a
Java
apptology/AltFuelFinder
/src/com/newrelic/agent/android/analytics/AnalyticsController.java
UTF-8
1,921
1.710938
2
[]
no_license
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.newrelic.agent.android.analytics; import java.util.Map; import java.util.Set; // Referenced classes of package com.newrelic.agent.android.analytics: // AnalyticsEvent, AnalyticsEventCategory, AnalyticAttribute, EventManager public interface AnalyticsController { public abstract boolean addEvent(AnalyticsEvent analyticsevent); public abstract boolean addEvent(String s, AnalyticsEventCategory analyticseventcategory, String s1, Set set); public abstract boolean addEvent(String s, Set set); public abstract AnalyticAttribute getAttribute(String s); public abstract EventManager getEventManager(); public abstract int getMaxEventBufferTime(); public abstract int getMaxEventPoolSize(); public abstract int getSessionAttributeCount(); public abstract Set getSessionAttributes(); public abstract int getSystemAttributeCount(); public abstract Set getSystemAttributes(); public abstract int getUserAttributeCount(); public abstract Set getUserAttributes(); public abstract boolean incrementAttribute(String s, float f); public abstract boolean incrementAttribute(String s, float f, boolean flag); public abstract boolean recordEvent(String s, Map map); public abstract boolean removeAllAttributes(); public abstract boolean removeAttribute(String s); public abstract boolean setAttribute(String s, float f); public abstract boolean setAttribute(String s, float f, boolean flag); public abstract boolean setAttribute(String s, String s1); public abstract boolean setAttribute(String s, String s1, boolean flag); public abstract void setMaxEventBufferTime(int i); public abstract void setMaxEventPoolSize(int i); }
true
2280524acaebdb53d4c72012798a4cc8a744ad45
Java
ehidalgo1/colegio
/src/main/java/com/colegio/entity/Ramo.java
UTF-8
944
2.1875
2
[]
no_license
package com.colegio.entity; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the ramo database table. * */ @Entity @NamedQuery(name="Ramo.findAll", query="SELECT r FROM Ramo r") public class Ramo implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="ID_RAMO") private Long idRamo; private String nombre; private String token; public Ramo() { } public Ramo(Long idRamo, String nombre, String token) { super(); this.idRamo = idRamo; this.nombre = nombre; this.token = token; } public Long getIdRamo() { return this.idRamo; } public void setIdRamo(Long idRamo) { this.idRamo = idRamo; } public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getToken() { return this.token; } public void setToken(String token) { this.token = token; } }
true
8d07073ffe463932fa8bd49a1df4ecf8d0819495
Java
richixws/microservicio-atm
/src/main/java/com/example/springboot/atm/controller/AtmController.java
UTF-8
5,346
2.234375
2
[]
no_license
package com.example.springboot.atm.controller; import java.net.URI; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.example.springboot.atm.dto.BankingDto; import com.example.springboot.atm.dto.CreditDto; import com.example.springboot.atm.model.Atm; import com.example.springboot.atm.service.IAtmService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @RestController @RequestMapping("/atm") public class AtmController { @Autowired private IAtmService service; // LISTAR TODAS LAS OPERACIONES @GetMapping("/findAll") public Flux<Atm> findAll() { return service.findAll(); } // LISTAR UNA OPERACIÓN POR SU ID @GetMapping("/findById/{id}") public Mono<Atm> findById(@PathVariable("id") String id) { return service.findById(id); } // CREAR UNA OPERACIÓN @PostMapping("/create") public Mono<ResponseEntity<Atm>> create(@RequestBody Atm atm) { return service.save(atm).map(a -> ResponseEntity.created(URI.create("/atm/".concat(a.getId()))) .contentType(MediaType.APPLICATION_JSON).body(a)); } // ACTUALIZAR UNA OPERACIÓN @PutMapping("/update/{id}") public Mono<ResponseEntity<Atm>> update(@PathVariable("id") String id, @RequestBody Atm atm) { return service.update(atm, id) .map(a -> ResponseEntity.created(URI.create("/atm/".concat(a.getId()))) .contentType(MediaType.APPLICATION_JSON).body(a)) .defaultIfEmpty(ResponseEntity.notFound().build()); } // ELIMINAR UNA OPERACIÓN @DeleteMapping("/delete/{id}") public Mono<ResponseEntity<Void>> delete(@PathVariable String id) { return service.findById(id).flatMap(a -> { return service.delete(a).then(Mono. just(new ResponseEntity<Void>(HttpStatus.NO_CONTENT))); }).defaultIfEmpty(new ResponseEntity<Void>(HttpStatus.NOT_FOUND)); } // REALIZAR UN DEPOSITO(PAGO) A UNA CUENTA CRÉDITO DESDE UNA CUENTA BANCARIA @PutMapping("/depositCreditFromBanking/{amount}/{accountO}/{accountD}") public Mono<Atm> depositCreditFromBanking(@PathVariable String amount, @PathVariable String accountO, @PathVariable String accountD) { return service.depositAccountBToAccountC(Double.parseDouble(amount), accountO, accountD); } @PutMapping("/depositBankingFromCredit/{amount}/{accountO}/{accountD}") public Mono<Atm> depositBankingFromCredit(@PathVariable String amount, @PathVariable String accountO, @PathVariable String accountD) { return service.retiroAccountCToAccountB(Double.parseDouble(amount), accountO, accountD); } // ------------------- Métodos Banking Client ------------------> // -------------------------------------------------------------- @GetMapping("/findAllBankingClients") public Flux<BankingDto> findAllBankingProducts() { return service.findAllBankingProducts(); } @GetMapping("/findByBankingId/{id}") public Mono<BankingDto> findByBankingId(@PathVariable("id") String id) { return service.findBankingById(id); } @GetMapping("/findByNumAccountB/{numAccount}") public Mono<BankingDto> findByNumAccountB(@PathVariable("numAccount") String numAccount) { return service.findByNumAccountB(numAccount); } @PutMapping("/depositB/{amount}/{numAccount}") public Mono<BankingDto> depositB(@PathVariable("amount") String amount, @PathVariable("numAccount") String numAccount) { return service.depositB(Double.parseDouble(amount), numAccount); } @PutMapping("/retiroB/{amount}/{numAccount}") public Mono<BankingDto> retiroB(@PathVariable("amount") String amount, @PathVariable("numAccount") String numAccount) { return service.retiroB(Double.parseDouble(amount), numAccount); } // ------------------- Métodos Credit Client ------------------> // -------------------------------------------------------------- @GetMapping("/findAllCreditClients") public Flux<CreditDto> findAllCreditProducts() { return service.findAllCreditProducts(); } @GetMapping("/findByCreditId/{id}") public Mono<CreditDto> findByCreditId(@PathVariable("id") String id) { return service.findCreditById(id); } @GetMapping("/findByNumAccountC/{numberAccount}") public Mono<CreditDto> findByNumAccountC(@PathVariable("numberAccount") String numberAccount) { return service.findByNumAccountC(numberAccount); } @PutMapping("/depositC/{amount}/{numberAccount}") public Mono<CreditDto> depositC(@PathVariable("amount") String amount, @PathVariable("numberAccount") String numberAccount) { return service.depositC(Double.parseDouble(amount), numberAccount); } @PutMapping("/retiroC/{amount}/{numberAccount}") public Mono<CreditDto> retiroC(@PathVariable("amount") String amount, @PathVariable("numberAccount") String numberAccount) { return service.retiroC(Double.parseDouble(amount), numberAccount); } }
true
e004e8d61fdec8a4c627f02aecd88f491d3e1561
Java
swaadheenta/Competitive-Programming
/Java Template/Solution.java
UTF-8
699
2.90625
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.io.*; import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); if (System.getProperty("ONLINE_JUDGE") == null) { try { System.setOut(new PrintStream(new FileOutputStream("output.txt"))); sc = new Scanner(new File("input.txt")); } catch (Exception e) { } } int t = sc.nextInt(); while (t-- > 0) { System.out.println("Hello World"); } } }
true
c1a4266ef265d65497b9ecf66701576b84201b6b
Java
plutext/JAXB-classes-for-XSL-FO
/src/main/java/org/plutext/jaxb/xslfo/TableOmitHeaderAtBreakType.java
UTF-8
1,252
2.296875
2
[]
no_license
package org.plutext.jaxb.xslfo; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for table_omit_header_at_break_Type. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="table_omit_header_at_break_Type"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="true"/> * &lt;enumeration value="false"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "table_omit_header_at_break_Type") @XmlEnum public enum TableOmitHeaderAtBreakType { @XmlEnumValue("true") TRUE("true"), @XmlEnumValue("false") FALSE("false"); private final String value; TableOmitHeaderAtBreakType(String v) { value = v; } public String value() { return value; } public static TableOmitHeaderAtBreakType fromValue(String v) { for (TableOmitHeaderAtBreakType c: TableOmitHeaderAtBreakType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
true
759e730808eafcca52ea2e2d1075566b735d1ff4
Java
Tellsea/spring-framework-5.2.8.RELEASE
/spring-tellsea/src/main/java/cn/tellsea/ordered/OrderedOne.java
UTF-8
316
1.96875
2
[ "Apache-2.0" ]
permissive
package cn.tellsea.ordered; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; /** * @author Tellsea * @date 2020-8-18 */ @Configuration public class OrderedOne implements Ordered { @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE; } }
true
4b5ddc947a60eaccc62c721275d1f71b25480379
Java
jolly336/network-stats
/library/src/main/java/com/nelson/stats/db/NetworkCallDatabase.java
UTF-8
365
2.046875
2
[]
no_license
package com.nelson.stats.db; import android.arch.persistence.room.Database; import android.arch.persistence.room.RoomDatabase; @Database(entities = {NetworkCallEntity.class}, version = NetworkCallDBManager.DB_VERSION, exportSchema = true) public abstract class NetworkCallDatabase extends RoomDatabase { public abstract NetworkCallDao getNetworkCallDao(); }
true
beb4ca0bd7deae81b55a3f5559c04dba4e8ea952
Java
cifsccec/OverseasAuditPlatform
/src/com/tonik/dao/ITestTargetDAO.java
UTF-8
627
1.789063
2
[]
no_license
package com.tonik.dao; import java.util.List; import com.tonik.model.TestTarget; public interface ITestTargetDAO extends IDAO { public List<TestTarget> getTestTargets(); public TestTarget getTestTarget(Long testTargetId); public void saveTestTarget(TestTarget testTarget); public void removeTestTarget(TestTarget testTarget); public List<TestTarget> getTestTargetPaging(int pageIndex, int pageSize, String strQuery, String strStraTime, String strEndTime); public int getTestTargetTotal(String strQuery, String strStraTime, String strEndTime); List<Object[]> getTestTargetByTest(Long id); }
true
15ac37074355c1eb4b28d7597a362b76442530a2
Java
HeLiangCheng/study-java
/java-multithread/src/main/java/com/hlc/study/java/concurrent/day02/demo02/MyQueue.java
UTF-8
2,390
3.8125
4
[]
no_license
package com.hlc.study.java.concurrent.day02.demo02; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicInteger; /** *@ClassName MyQueue *@Description todo *@Author Liang *@Date 2019/1/11 15:43 *@Version 1.0 使用wait和notfiy来模拟Queue Queue:是一个先进先出特性的对象列 首先需要有一个集合盛装数据,指明集合的上限和下限 **/ public class MyQueue { private AtomicInteger listcapacity = new AtomicInteger(10); //初始为10 private static volatile LinkedList<String> list = new LinkedList<String>(); private Object lock =new Object(); public MyQueue(){ } public MyQueue(int capacity) { if(capacity<Integer.MAX_VALUE) { listcapacity.set(capacity); } } public void put(String val) { try { synchronized (lock) { if (list.size() < listcapacity.intValue()) { list.add(val); listcapacity.incrementAndGet(); System.out.println("添加一条数据,唤醒消费者"); lock.notify(); } lock.wait(); } }catch (Exception ex){ ex.printStackTrace(); } } public String take() { synchronized (lock){ if(list.size()<=0){ try { lock.wait(); }catch (Exception ex){ ex.printStackTrace(); } } String value = list.poll(); listcapacity.decrementAndGet(); System.out.println("消费一条数据,唤醒生产者"); lock.notify(); return value; } } public static void main(String[] args){ final MyQueue queue =new MyQueue(10); Thread t1=new Thread(new Runnable() { public void run() { for (int i = 0; i < 50; i++) { queue.put("t1-" + i); } } }); Thread t2=new Thread(new Runnable() { public void run() { while(true){ Object obj=queue.take(); System.out.println(" --> "+obj.toString()); } } }); t1.start(); t2.start(); } }
true
5d22b85782121e70beb601df5f622340f1f76d90
Java
ytfgu-xp/JSD2012
/src/main/java/io/BRDemo.java
UTF-8
1,096
3.328125
3
[]
no_license
package io; import com.sun.org.apache.xpath.internal.objects.XNull; import java.io.*; /** *缓冲字符输入流 * java.io.BufferedReader * 内部维护一个缓冲区可以块读文本数据,并且可以按行读取字符串 * * */ public class BRDemo { public static void main(String[] args) throws IOException { FileInputStream fis=new FileInputStream("./src/main/java/io/BRDemo.java"); InputStreamReader isr=new InputStreamReader(fis); BufferedReader bf=new BufferedReader(isr);//缓冲流,块读 String line; /* * BufferedReader提供的方法 * String readLine() * 读取一行字符串,读取到换行符停止,并将换行符之前的内容以一个字符串形式返回(不含有最后的换行符) * 如果此行为空行,那只有换行符,则返回值为空字符串 * 如果此方法返回值为null说明流读取到了末尾 * * */ while((line=bf.readLine())!=null){ System.out.println(line); } bf.close(); } }
true
1e809b31e23883967f9cd9265b7076ea56542936
Java
dlucas1/chpl-api
/chpl/chpl-service/src/main/java/gov/healthit/chpl/dao/statistics/DeveloperStatisticsDAO.java
UTF-8
839
2
2
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
package gov.healthit.chpl.dao.statistics; import java.util.List; import gov.healthit.chpl.domain.DateRange; import gov.healthit.chpl.domain.statistics.CertifiedBodyStatistics; public interface DeveloperStatisticsDAO { public Long getTotalDevelopers(DateRange dateRange); // 2014 public Long getTotalDevelopersWith2014Listings(DateRange dateRange); public Long getTotalDevelopersWithActive2014Listings(DateRange dateRange); public List<CertifiedBodyStatistics> getTotalDevelopersByCertifiedBodyWithListingsEachYear(DateRange dateRange); public List<CertifiedBodyStatistics> getTotalDevelopersByCertifiedBodyWithListingsInEachCertificationStatusAndYear(DateRange dateRange); // 2015 public Long getTotalDevelopersWith2015Listings(DateRange dateRange); public Long getTotalDevelopersWithActive2015Listings(DateRange dateRange); }
true
d1f77ea529101daf07c04b4454536399dfe65d24
Java
fit666/MyHotel
/HeroHotel/src/main/java/com/hero/hotel/service/CommentService.java
UTF-8
473
1.820313
2
[]
no_license
package com.hero.hotel.service; import com.hero.hotel.pojo.Comment; import java.util.List; import javax.servlet.http.HttpSession; public interface CommentService { //分页查找所有评论 public List<Comment> findAll(Integer PageNum ); //查找总条数 public Integer findTotal(); //添加评论 public Boolean addComment(Comment comment,HttpSession session); public List<Comment> findAllNow(); Boolean deleteComment(Integer id); }
true
5297a364918570e5028219992f79e4d6367f24a6
Java
janderson-js/Curso-JSP-JDEVTreinamento
/curso-jsp/src/main/java/Servlets/ServletGenericUtil.java
UTF-8
979
2.234375
2
[]
no_license
package Servlets; import java.io.Serializable; import dao.DAOUsuarioRepository; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import model.ModelLogin; public class ServletGenericUtil extends HttpServlet implements Serializable{ private static final long serialVersionUID = 1L; private DAOUsuarioRepository daoUser = new DAOUsuarioRepository(); public Long getUserLogado(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String usuariologado = (String) session.getAttribute("usuario"); return daoUser.consultarUsuarioLogado(usuariologado).getId(); } public ModelLogin getUserLogadoObj(HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String usuariologado = (String) session.getAttribute("usuario"); return daoUser.consultarUsuarioLogado(usuariologado); } }
true
13c26b932c382834af9a6b6861f4a9da67027d7c
Java
MEJIOMAH17/rocketbank-api
/reverse/Rocketbank_All_3.12.4_source_from_JADX/sources/ru/rocketbank/core/model/StatusResponseData.java
UTF-8
5,542
1.773438
2
[]
no_license
package ru.rocketbank.core.model; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import com.google.gson.annotations.SerializedName; import kotlin.jvm.internal.Intrinsics; import ru.rocketbank.core.events.EventHelper.IEvent; import ru.rocketbank.core.model.dto.ChangePin; import ru.rocketbank.core.network.model.leads.Document; /* compiled from: StatusResponseData1.kt */ public final class StatusResponseData implements Parcelable, IEvent { public static final Creator<StatusResponseData> CREATOR = new StatusResponseData$$special$$inlined$createParcel$1(); public static final Companion Companion = new Companion(); private DeliveryData delivery; @SerializedName("delivery_scheduled") private DeliveryScheduledData deliveryScheduled; @SerializedName("document_check") private Document documentCheck; @SerializedName("document_rejected") private Document documentRejected; private FormData form; private StatusResponseSubData go; private StatusResponseSubData password; private ChangePin pin; @SerializedName("pusher_token") private String pusherToken; @SerializedName(alternate = {"status"}, value = "sexy_api_status") private String status; private final String token; /* compiled from: StatusResponseData1.kt */ public static final class Companion { private Companion() { } } public final int describeContents() { return 0; } public StatusResponseData(Parcel parcel) { Intrinsics.checkParameterIsNotNull(parcel, "in"); this.pin = (ChangePin) parcel.readParcelable(ChangePin.class.getClassLoader()); String readString = parcel.readString(); Intrinsics.checkExpressionValueIsNotNull(readString, "`in`.readString()"); this.status = readString; readString = parcel.readString(); Intrinsics.checkExpressionValueIsNotNull(readString, "`in`.readString()"); this.pusherToken = readString; this.form = (FormData) parcel.readParcelable(FormData.class.getClassLoader()); this.deliveryScheduled = (DeliveryScheduledData) parcel.readParcelable(DeliveryScheduledData.class.getClassLoader()); this.go = (StatusResponseSubData) parcel.readParcelable(StatusResponseSubData.class.getClassLoader()); this.password = (StatusResponseSubData) parcel.readParcelable(StatusResponseSubData.class.getClassLoader()); this.documentCheck = (Document) parcel.readParcelable(Document.class.getClassLoader()); this.documentRejected = (Document) parcel.readParcelable(Document.class.getClassLoader()); parcel = parcel.readString(); Intrinsics.checkExpressionValueIsNotNull(parcel, "`in`.readString()"); this.token = parcel; } public final String getToken() { return this.token; } public final String getStatus() { return this.status; } public final void setStatus(String str) { Intrinsics.checkParameterIsNotNull(str, "<set-?>"); this.status = str; } public final String getPusherToken() { return this.pusherToken; } public final void setPusherToken(String str) { Intrinsics.checkParameterIsNotNull(str, "<set-?>"); this.pusherToken = str; } public final ChangePin getPin() { return this.pin; } public final void setPin(ChangePin changePin) { this.pin = changePin; } public final FormData getForm() { return this.form; } public final void setForm(FormData formData) { this.form = formData; } public final DeliveryScheduledData getDeliveryScheduled() { return this.deliveryScheduled; } public final void setDeliveryScheduled(DeliveryScheduledData deliveryScheduledData) { this.deliveryScheduled = deliveryScheduledData; } public final StatusResponseSubData getGo() { return this.go; } public final void setGo(StatusResponseSubData statusResponseSubData) { this.go = statusResponseSubData; } public final StatusResponseSubData getPassword() { return this.password; } public final void setPassword(StatusResponseSubData statusResponseSubData) { this.password = statusResponseSubData; } public final Document getDocumentCheck() { return this.documentCheck; } public final void setDocumentCheck(Document document) { this.documentCheck = document; } public final Document getDocumentRejected() { return this.documentRejected; } public final void setDocumentRejected(Document document) { this.documentRejected = document; } public final DeliveryData getDelivery() { return this.delivery; } public final void setDelivery(DeliveryData deliveryData) { this.delivery = deliveryData; } public final void writeToParcel(Parcel parcel, int i) { Intrinsics.checkParameterIsNotNull(parcel, "dest"); parcel.writeParcelable(this.pin, 0); parcel.writeString(this.status); parcel.writeString(this.pusherToken); parcel.writeParcelable(this.form, i); parcel.writeParcelable(this.deliveryScheduled, 0); parcel.writeParcelable(this.go, i); parcel.writeParcelable(this.password, i); parcel.writeParcelable(this.documentCheck, i); parcel.writeParcelable(this.documentRejected, i); parcel.writeString(this.token); } }
true
2cb70181304dc14e99fa9955ce25634db2db205a
Java
vhctrungnq/mlmn
/MLMN-core/ejbModule/vn/com/vhc/sts/cni/converter/SMSCZTEConverter.java
UTF-8
4,634
2.046875
2
[]
no_license
package vn.com.vhc.sts.cni.converter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Hashtable; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import vn.com.vhc.sts.cni.STS_BasicConverter; import vn.com.vhc.sts.util.exceptions.STS_ConvertException; /** * HN_FDA_Performance_Statistics_Rerport: from 2009-09-19 00 to 2009-09-19 01 * Site : VMS_HN_FDA * -------------------------------------------------------------------------------------- * 001 succSubmitMsToMs : 106137 (the success value of MO from MS to MS) * 002 failSubmitMsToMs : 1762 (the fail value of MO from MS to MS) * 003 succSubmitMsToEsme : 4392 (the success value of MO from MS to ESME) * 004 failSubmitMsToEsme : 3 (the fail value of MO from MS to ESME) * 005 moSuccRatio : 98.43% (MO success Ratio:the value = [001+003]/[001+002+003+004]*100%) * 006 succSubmitEsmeToMs : 11550 (the success value of AO from ESME to MS) * 007 failureSubmitEsmeToMs : 0 (the fail value of AO from ESME to MS) * 008 succSubmitEsmeToEsme : 0 (the success value of AO from ESME to ESME) * 009 failureSubmitEsmeToEsme : 0 (the fail value of AO from ESME to ESME) * ................................................. * */ public class SMSCZTEConverter extends STS_BasicConverter { private static Logger logger = Logger.getLogger(SMSCZTEConverter.class.getName()); private final Pattern indexPattern = Pattern.compile("[0-9]{3} "); public SMSCZTEConverter() { } public void convertFile(File file, String direcPath, Hashtable<Byte, String> params) throws STS_ConvertException { prepareParams(params); makeDirectory(direcPath); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(file)); File outFile = new File(direcPath, file.getName()); writer = new BufferedWriter(new FileWriter(outFile)); // Append header to file List<String> list = getFileHeaderInfo(); for (String s : list) { writer.write(commentChar + s); writer.newLine(); } String fullTime = getTimeFromFileName(file.getName(), "[0-9]{10}"); String time = fullTime.substring(0, fullTime.length() - 2); String hour = fullTime.substring(time.length(), fullTime.length()); String site = ""; String header = "SMSCID" + separator + "TIME" + separator + "HOUR" + separator + "SITE"; String value = nodeName + separator + time + separator + hour; String line = ""; String[] temp = null; Matcher m = null; while ((line = reader.readLine()) != null) { if (line.trim().length() == 0) { continue; } if (line.startsWith("Site")) { site = line.substring(line.indexOf(":") + 1, line.length()); value += separator + site.trim(); } m = indexPattern.matcher(line); if (m.find()) { temp = line.split(" "); if (temp.length > 3) { if (header.length() > 0) { header += separator; } header += temp[1].trim(); if (value.length() > 0) { value += separator; } value += temp[3].trim(); } } } writer.write(commentChar + header.toUpperCase()); writer.newLine(); writer.write(value); } catch (IOException ioe) { throw new STS_ConvertException(ioe.getMessage(), "VMSC2-0306", ioe); } finally { if (reader != null) { try { reader.close(); writer.close(); } catch (IOException e) { logger.warn("Close IO stream failure"); } } } logger.info("Convert file: " + file.getName() + " success"); } }
true
df8780f6bd37989092419f6bfaa1aec01f195de3
Java
clarysabel/itstool
/src/main/java/com/openenglish/itstool/entity/Input.java
UTF-8
2,243
2.140625
2
[]
no_license
package com.openenglish.itstool.entity; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.Where; @Entity @Table(name = "inputs", catalog = "orion") @SQLDelete(sql="UPDATE customer SET deleted = 'true' WHERE id = ?") @Where(clause="deleted = 'false'") public class Input implements Serializable { private static final long serialVersionUID = -2559719551056552128L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "input_id") private Integer inputId; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "operation_id") private Operation operation; @Column(name="name") private String name; @Column(name="type") private String type; @Column(name="display_name") private String displayName; @Column(name="deleted") private Boolean deleted; public Input() { } public Input(Integer inputId, Operation operation, String name, String type, String displayName, Boolean deleted) { super(); this.inputId = inputId; this.operation = operation; this.name = name; this.type = type; this.displayName = displayName; this.deleted = deleted; } public Integer getInputId() { return inputId; } public void setInputId(Integer inputId) { this.inputId = inputId; } public Operation getOperation() { return operation; } public void setOperation(Operation operation) { this.operation = operation; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public Boolean getDeleted() { return deleted; } public void setDeleted(Boolean deleted) { this.deleted = deleted; } }
true
df8b5bd11c074afde82d07ecca3c584f96eba689
Java
SujinJeong/SSAFY_ALGO_STUDY
/src/donggil/Week2/boj_7576.java
UTF-8
2,239
2.96875
3
[]
no_license
package donggil.Week2; import java.io.*; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class boj_7576 { private static final int[] dir_x = {-1, 0, 1, 0}; private static final int[] dir_y = {0, -1, 0, 1}; private static class TomatoInfo { int row; int col; int day; public TomatoInfo(int row, int col, int day) { this.row = row; this.col = col; this.day = day; } } public static void main(String[] arg) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringBuilder sb = new StringBuilder(); Queue<TomatoInfo> Q = new LinkedList<>(); StringTokenizer stk = new StringTokenizer(br.readLine()); int M = Integer.parseInt(stk.nextToken()); int N = Integer.parseInt(stk.nextToken()); int[][] WareHouse = new int[N][M]; int answer = 0, blankCnt = 0, tomatoCnt = 0; for(int i = 0; i < N; i++) { stk = new StringTokenizer(br.readLine()); for(int j = 0; j < M; j++) { WareHouse[i][j] = Integer.parseInt(stk.nextToken()); if(WareHouse[i][j] == 1) { Q.add(new TomatoInfo(i, j, answer)); } else if(WareHouse[i][j] == -1) { blankCnt++; } } } while(!Q.isEmpty()) { TomatoInfo tomato = Q.poll(); answer = tomato.day; tomatoCnt++; for(int i = 0; i < 4; i++) { int nr = tomato.row + dir_x[i]; int nc = tomato.col + dir_y[i]; if(nr < 0 || nc < 0 || nr >= N || nc >= M) continue; if(WareHouse[nr][nc] == 0) { WareHouse[nr][nc] = 1; Q.add(new TomatoInfo(nr, nc, tomato.day + 1)); } } } if(tomatoCnt == (M * N) - blankCnt) sb.append(answer); else sb.append(-1); bw.write(String.valueOf(sb)); bw.close(); br.close(); } }
true
998b2e178e69d8784bc610c818722ae60c6e1be0
Java
MAortize/viajesBack
/src/main/java/co/edu/usbcali/viajesusb/service/UsuarioService.java
UTF-8
523
1.875
2
[]
no_license
package co.edu.usbcali.viajesusb.service; import java.sql.SQLException; import co.edu.usbcali.viajesusb.domain.Usuario; import co.edu.usbcali.viajesusb.dto.UsuarioDTO; public interface UsuarioService { public Usuario findByIdentificacionLike(String identificacion) throws SQLException; public void guardarUsuario(UsuarioDTO usuarioDTO) throws SQLException; public void actualizarUsuario(UsuarioDTO usuarioDTO) throws SQLException; public void eliminarUsuario(UsuarioDTO usuarioDTO) throws SQLException; }
true
de66dd6d513d7d740e64e19e3e719490cc030188
Java
immaulik/Pubg-master_Latest
/app/src/main/java/com/example/pubgtournament/Adapters/joinedResultAdapter.java
UTF-8
2,272
2.03125
2
[]
no_license
package com.example.pubgtournament.Adapters; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.pubgtournament.Activities.ResultContests; import com.example.pubgtournament.Activities.SoloMatchInfo; import com.example.pubgtournament.Models.Transaction; import com.example.pubgtournament.R; import java.util.List; /** * Created by Darshan Soni on 30-Jun-19. */ public class joinedResultAdapter extends RecyclerView.Adapter<joinedResultAdapter.transactionViewHolder> { ResultContests resultContests; List<Transaction> transactionList; public joinedResultAdapter(ResultContests resultContests, List<Transaction> transactionList) { this.resultContests=resultContests; this.transactionList=transactionList; } @NonNull @Override public transactionViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater layoutInflater=LayoutInflater.from(resultContests); View view= layoutInflater.inflate(R.layout.joinedresultitemfile,viewGroup,false); return new transactionViewHolder(view); } @Override public void onBindViewHolder(@NonNull transactionViewHolder holder, int i) { Transaction transaction=transactionList.get(i); holder.joinedUserTextView.setText(transaction.getPubgName()); holder.joinedUserKillsTextView.setText(transaction.getUsersKill()); holder.joinedUserKillsPrizeTextView.setText(transaction.getKillPayment()); } @Override public int getItemCount() { return transactionList.size(); } public class transactionViewHolder extends RecyclerView.ViewHolder{ TextView joinedUserTextView,joinedUserKillsTextView,joinedUserKillsPrizeTextView; public transactionViewHolder(@NonNull View itemView) { super(itemView); joinedUserTextView=itemView.findViewById(R.id.joined_user_name); joinedUserKillsTextView=itemView.findViewById(R.id.joined_user_kill); joinedUserKillsPrizeTextView=itemView.findViewById(R.id.joined_user_kill_prize); } } }
true
53a7db16da30aef9dd17d46da8829f889c21eabe
Java
slizaa/slizaa-rcp-workbench
/plugins/org.slizaa.neo4j.queryresult.ui/src/org/slizaa/neo4j/queryresult/ui/internal/action/CleanQueryResultHandler.java
UTF-8
760
1.71875
2
[]
no_license
package org.slizaa.neo4j.queryresult.ui.internal.action; import org.eclipse.e4.core.di.annotations.CanExecute; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.model.application.ui.basic.MPart; import org.eclipse.e4.ui.workbench.modeling.EPartService; import org.slizaa.neo4j.queryresult.ui.internal.QueryResultViewPart; public class CleanQueryResultHandler { @Execute public void execute(EPartService ePartService) { MPart part = ePartService.findPart("org.slizaa.neo4j.queryresult.ui.QueryResultViewPart"); QueryResultViewPart queryResultViewPart = (QueryResultViewPart) part.getObject(); queryResultViewPart.clean(); } @CanExecute public boolean canExecute() { return true; } }
true
fc194bb2c37ac5f8e4de7e5bd8eb049f7d3e04d4
Java
yangmouren0701/bookshop
/BookShop/src/main/java/com/lv/pojo/Cart.java
UTF-8
1,378
3.171875
3
[ "Apache-2.0" ]
permissive
package com.lv.pojo; import lombok.AllArgsConstructor; import lombok.Data; import java.util.HashMap; import java.util.Iterator; import java.util.Set; @Data @AllArgsConstructor public class Cart { private HashMap<Book,Integer> goods; private double totalPrice; public Cart() { goods = new HashMap<Book,Integer>(); totalPrice = 0.0; } /** * 添加商品进购物车的方法 * @param item * @param number * @return */ public boolean addGoodsInCart(Book item ,int number) { if(goods.containsKey(item)) { goods.put(item, goods.get(item)+number); } else { goods.put(item, number); } //重新计算购物车的总金额 calTotalPrice(); return true; } /** * 删除商品的方法 * @param item * @return */ public boolean removeGoodsFromCart(Book item) { goods.remove(item); //重新计算购物车的总金额 calTotalPrice(); return true; } /** * 统计购物车的总金额 * @return */ public double calTotalPrice() { double sum = 0.0; //获得键的集合 Set<Book> keys = goods.keySet(); //获得迭代器对象 Iterator<Book> it = keys.iterator(); while(it.hasNext()) { Book i = it.next(); sum += Double.parseDouble(i.getPrice())* goods.get(i); } //设置购物车的总金额 this.setTotalPrice(sum); return this.getTotalPrice(); } }
true
581b4b63768114d61161cb50a24224ce0d1c40e8
Java
nevenjakopcic/pios-backend
/src/main/java/hr/tvz/pios/scheduler/service/EquipmentService.java
UTF-8
3,754
2.375
2
[ "MIT" ]
permissive
package hr.tvz.pios.scheduler.service; import hr.tvz.pios.scheduler.dto.request.CreateEquipmentRequest; import hr.tvz.pios.scheduler.dto.request.CreateEquipmentTypeRequest; import hr.tvz.pios.scheduler.dto.response.EquipmentDto; import hr.tvz.pios.scheduler.exception.DuplicateValueException; import hr.tvz.pios.scheduler.exception.NoSuchTypeException; import hr.tvz.pios.scheduler.exception.NotFoundException; import hr.tvz.pios.scheduler.exception.UserAlreadyAssignedException; import hr.tvz.pios.scheduler.mapper.EquipmentDtoMapper; import hr.tvz.pios.scheduler.model.Equipment; import hr.tvz.pios.scheduler.model.EquipmentType; import hr.tvz.pios.scheduler.repository.EquipmentRepository; import hr.tvz.pios.scheduler.repository.EquipmentTypeRepository; import java.util.List; import java.util.stream.Collectors; import lombok.AllArgsConstructor; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class EquipmentService { private final EquipmentRepository equipmentRepository; private final EquipmentTypeRepository typeRepository; private final CurrentUserService currentUserService; public List<EquipmentDto> getEquipment(Boolean showOnlyUserEquipment, String name, Long type) { Long userId = null; if (Boolean.TRUE.equals(showOnlyUserEquipment)) { userId = currentUserService.getLoggedInUser().getId(); } return equipmentRepository.getEquipment(userId, name, type).stream() .map(EquipmentDtoMapper::map) .collect(Collectors.toList()); } public EquipmentDto createEquipment(CreateEquipmentRequest request) { Equipment equipment = Equipment.builder() .name(request.getName()) .type(typeRepository.findById(request.getTypeId()) .orElseThrow(() -> new NoSuchTypeException("Equipment type with id " + request.getTypeId() + " not found."))) .build(); try { equipment = equipmentRepository.save(equipment); } catch (DataIntegrityViolationException e) { throw new DuplicateValueException("Equipment with the name '" + request.getName() + "' already exists.", e); } return EquipmentDtoMapper.map(equipment); } public void assignToCurrentUser(Long equipmentId) { Equipment equipment = equipmentRepository.findById(equipmentId) .orElseThrow(() -> new NotFoundException("Equipment with id " + equipmentId + " not found.")); if (equipment.getUser() != null) { throw new UserAlreadyAssignedException("This equipment is already assigned to a user."); } equipment.setUser(currentUserService.getLoggedInUser()); equipmentRepository.save(equipment); } public void unassignFromUser(Long equipmentId) { Equipment equipment = equipmentRepository.findById(equipmentId) .orElseThrow(() -> new NotFoundException("Equipment with id " + equipmentId + " not found.")); if (equipment.getUser() != null) { currentUserService.validateIsLoggedInUserOrAdmin(equipment.getUser().getId(), "Not allowed to unassign other user from equipment."); } equipment.setUser(null); equipmentRepository.save(equipment); } public List<EquipmentType> getAllTypes() { return typeRepository.findAll(); } public EquipmentType createType(CreateEquipmentTypeRequest request) { EquipmentType type = EquipmentType.builder() .name(request.getName()).build(); return typeRepository.save(type); } }
true
986815bdc824cbdf27d2f0f5a3403d88c3de7033
Java
guoop/springboot_pau_hzcx
/pau-rest/src/main/java/com/soft/ware/rest/config/WebConfig.java
UTF-8
5,644
1.71875
2
[ "Apache-2.0" ]
permissive
package com.soft.ware.rest.config; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import com.alibaba.druid.support.spring.stat.DruidStatInterceptor; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.soft.ware.rest.config.properties.RestProperties; import com.soft.ware.rest.modular.auth.filter.AuthFilter; import com.soft.ware.rest.modular.auth.filter.AuthHandlerMethodArgumentResolver; import com.soft.ware.rest.modular.auth.security.DataSecurityAction; import com.soft.ware.rest.modular.auth.security.impl.Base64SecurityAction; import org.springframework.aop.support.JdkRegexpMethodPointcut; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.List; /** * web配置 * @author paulo * @date 2017-08-23 15:48 */ @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Bean @ConditionalOnProperty(prefix = RestProperties.REST_PREFIX, name = "auth-open", havingValue = "true", matchIfMissing = true) public AuthFilter jwtAuthenticationTokenFilter() { return new AuthFilter(); } @Bean public DataSecurityAction dataSecurityAction() { return new Base64SecurityAction(); } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.setAllowCredentials(true); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); return new CorsFilter(source); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { super.addArgumentResolvers(argumentResolvers); argumentResolvers.add(new AuthHandlerMethodArgumentResolver()); //argumentResolvers.add(new PageHandlerMethodArgumentResolver()); } /** * druidServlet注册 */ @Bean public ServletRegistrationBean druidServletRegistration() { ServletRegistrationBean registration = new ServletRegistrationBean(new StatViewServlet()); registration.addUrlMappings("/druid/*"); return registration; } /** * druid监控 配置URI拦截策略 */ @Bean public FilterRegistrationBean druidStatFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); //添加过滤规则. filterRegistrationBean.addUrlPatterns("/*"); //添加不需要忽略的格式信息. filterRegistrationBean.addInitParameter( "exclusions", "/static/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid,/druid/*"); //用于session监控页面的用户名显示 需要登录后主动将username注入到session里 filterRegistrationBean.addInitParameter("principalSessionName", "username"); return filterRegistrationBean; } /** * druid数据库连接池监控 */ @Bean public DruidStatInterceptor druidStatInterceptor() { return new DruidStatInterceptor(); } @Bean public JdkRegexpMethodPointcut druidStatPointcut() { JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut(); String patterns = "com.soft.ware.modular.*.service.*"; //可以set多个 druidStatPointcut.setPatterns(patterns); return druidStatPointcut; } /** * 定义 StringRedisTemplate ,指定序列化和反序列化的处理类 * @param factory * @return */ @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); //序列化 值时使用此序列化方法 template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }
true
87751ae2076317d1e1a387598baf7e42113ef679
Java
meister4ever/quigon
/TreasureHuntBuilder/src/test/java/TreasureHuntTest.java
UTF-8
5,596
2.28125
2
[]
no_license
import creation.Game; import creation.GameBuilderImp; import org.junit.Test; import static org.junit.Assert.assertEquals; @SuppressWarnings("CPD-START") public class TreasureHuntTest { GameBuilderImp gameBuilderImp; Game treasureHunt; public void gameMoveToSouth(){ gameBuilderImp = new TreasureHuntBuilder(); treasureHunt = gameBuilderImp.build(); TreasureHuntConstants wsConstants = new TreasureHuntConstants(); String openDoorWCCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorWC; assertEquals(treasureHunt.receiveCommands(openDoorWCCommand), TreasureHuntConstants.movedToCenter); String openBoxCCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.boxC; assertEquals(treasureHunt.receiveCommands(openBoxCCommand), TreasureHuntConstants.openBox); String pickKeySCommand = TreasureHuntConstants.pick + " " + TreasureHuntConstants.keyS; assertEquals(treasureHunt.receiveCommands(pickKeySCommand), TreasureHuntConstants.pickKey); String unlockDoorCSCommand = TreasureHuntConstants.unlock + " " + TreasureHuntConstants.doorCS; assertEquals(treasureHunt.receiveCommands(unlockDoorCSCommand), TreasureHuntConstants.doorUnlocked); String openDoorCSCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorCS; assertEquals(treasureHunt.receiveCommands(openDoorCSCommand), TreasureHuntConstants.movedToSouth); String openTrunkSCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.trunkS; assertEquals(treasureHunt.receiveCommands(openTrunkSCommand), TreasureHuntConstants.openTrunk); String pickAntidote1Command = TreasureHuntConstants.pick + " " + TreasureHuntConstants.antidote1; assertEquals(treasureHunt.receiveCommands(pickAntidote1Command), TreasureHuntConstants.pickAntidote); } public void gameTestDropKey() { String dropKeySCommand = TreasureHuntConstants.drop + " " + TreasureHuntConstants.keyS; assertEquals(treasureHunt.receiveCommands(dropKeySCommand), TreasureHuntConstants.dropKey); String pickKeyECommand = TreasureHuntConstants.pick + " " + TreasureHuntConstants.keyE; assertEquals(treasureHunt.receiveCommands(pickKeyECommand), TreasureHuntConstants.pickKey); String openDoorSCCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorSC; assertEquals(treasureHunt.receiveCommands(openDoorSCCommand), TreasureHuntConstants.movedToCenter); String unlockDoorCECommand = TreasureHuntConstants.unlock + " " + TreasureHuntConstants.doorCE; assertEquals(treasureHunt.receiveCommands(unlockDoorCECommand), TreasureHuntConstants.doorUnlocked); String openDoorCECommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorCE; assertEquals(treasureHunt.receiveCommands(openDoorCECommand), TreasureHuntConstants.movedToEast); String openTrunkECommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.trunkE; assertEquals(treasureHunt.receiveCommands(openTrunkECommand), TreasureHuntConstants.openTrunk); String openBoxECommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.boxE; assertEquals(treasureHunt.receiveCommands(openBoxECommand), TreasureHuntConstants.openBox); String dropKeyECommand = TreasureHuntConstants.drop + " " + TreasureHuntConstants.keyE; assertEquals(treasureHunt.receiveCommands(dropKeyECommand), TreasureHuntConstants.dropKey); } public void gameTestKeys() { String pickKeyNCommand = TreasureHuntConstants.pick + " " + TreasureHuntConstants.keyN; assertEquals(treasureHunt.receiveCommands(pickKeyNCommand), TreasureHuntConstants.pickKey); String openDoorECCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorEC; assertEquals(treasureHunt.receiveCommands(openDoorECCommand), TreasureHuntConstants.movedToCenter); String unlockDoorCNCommand = TreasureHuntConstants.unlock + " " + TreasureHuntConstants.doorCN; assertEquals(treasureHunt.receiveCommands(unlockDoorCNCommand), TreasureHuntConstants.doorUnlocked); String openDoorCNCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorCN; assertEquals(treasureHunt.receiveCommands(openDoorCNCommand), TreasureHuntConstants.movedToNorth); String openTrunkNCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.trunkN; assertEquals(treasureHunt.receiveCommands(openTrunkNCommand), TreasureHuntConstants.openPoisonTrunk); String useAntidoteCommand = TreasureHuntConstants.use + " " + TreasureHuntConstants.antidote1; assertEquals(treasureHunt.receiveCommands(useAntidoteCommand), TreasureHuntConstants.healed); String pickTreasureCommand = TreasureHuntConstants.pick + " " + TreasureHuntConstants.treasure; assertEquals(treasureHunt.receiveCommands(pickTreasureCommand), TreasureHuntConstants.pickTreasure); String openDoorNCCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorNC; assertEquals(treasureHunt.receiveCommands(openDoorNCCommand), TreasureHuntConstants.movedToCenter); } @Test public void gameTestTreasureHunt() { gameMoveToSouth(); gameTestDropKey(); gameTestKeys(); String openDoorCWCommand = TreasureHuntConstants.open + " " + TreasureHuntConstants.doorCW; assertEquals(treasureHunt.receiveCommands(openDoorCWCommand), gameBuilderImp.winText); } }
true
0fd55a254e814fe9271aedc2fb5149cd582bdd62
Java
wanput24/Tubes_Progmob_Kelompok_7
/app/src/main/java/id/unud/ac/tubesObat/adapter/ItemListAdapter.java
UTF-8
2,766
2.25
2
[]
no_license
package id.unud.ac.tubesObat.adapter; 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 android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import java.util.ArrayList; import id.unud.ac.tubesObat.DetailActivity; import id.unud.ac.tubesObat.DetailTipsActivity; import id.unud.ac.tubesObat.Obat; import id.unud.ac.tubesObat.R; import id.unud.ac.tubesObat.Tips; public class ItemListAdapter extends RecyclerView.Adapter<ItemListAdapter.ListViewHolder> { private ArrayList<Tips> listTips; public ItemListAdapter(ArrayList<Tips> list){ this.listTips = list; } @NonNull @Override public ListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false); return new ListViewHolder(view); } @Override public void onBindViewHolder(@NonNull ItemListAdapter.ListViewHolder holder, int position) { Tips tips = listTips.get(position); // Glide.with(holder.itemView.getContext()) // .load(obat.getPhoto()) // .apply(new RequestOptions().override(55,55)) // .into(holder.imgPhoto); holder.tvName.setText(tips.getTitle()); holder.tvDesc.setText(tips.getDesc()); holder.itemView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { Toast.makeText(holder.itemView.getContext(), "Kamu memilih " + listTips.get(holder.getAdapterPosition()).getTitle(), Toast.LENGTH_SHORT).show(); Intent intent = new Intent(holder.itemView.getContext(), DetailTipsActivity.class); intent.putExtra("title", tips.getTitle()); intent.putExtra("desc", tips.getDesc()); intent.putExtra("desc2", tips.getDesc2()); holder.itemView.getContext().startActivity(intent); } }); } @Override public int getItemCount() { return listTips.size(); } public class ListViewHolder extends RecyclerView.ViewHolder{ // ImageView imgPhoto; TextView tvName, tvDesc; public ListViewHolder(@NonNull View itemView) { super(itemView); // imgPhoto = itemView.findViewById(R.id.img_item_photo); tvName = itemView.findViewById(R.id.tv_item_name); tvDesc = itemView.findViewById(R.id.tv_item_desc); } } }
true
d767723f1bd78714d8f11325e0e015864f42b7e3
Java
jalexrb/Chorus-RF-Laptimer-PC
/fuentes/ChorusRfLaptimer/src/com/chorusrflaptimer/util/ClipTest.java
UTF-8
1,330
2.96875
3
[ "MIT" ]
permissive
package com.chorusrflaptimer.util; import java.io.File; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineEvent; import javax.sound.sampled.LineListener; /** * An example of loading and playing a sound using a Clip. This complete class * isn't in the book ;) */ public class ClipTest { public static void main(String[] args) throws Exception { // specify the sound to play // (assuming the sound can be played by the audio system) File soundFile = new File("../sounds/voice.wav"); AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile); // load the sound into memory (a Clip) DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat()); Clip clip = (Clip) AudioSystem.getLine(info); clip.open(sound); // due to bug in Java Sound, explicitly exit the VM when // the sound has stopped. clip.addLineListener(new LineListener() { public void update(LineEvent event) { if (event.getType() == LineEvent.Type.STOP) { event.getLine().close(); System.exit(0); } } }); // play the sound clip clip.start(); } }
true
53df28274309d22ac50c64cc67d20cb71099401f
Java
bluce-clj/AndroidBLEUtil
/characteristic/u2a88/src/main/java/org/im97mori/ble/characteristic/u2a88/FatBurnHeartRateLowerLimitAndroid.java
UTF-8
2,822
2.5
2
[ "MIT" ]
permissive
package org.im97mori.ble.characteristic.u2a88; import android.bluetooth.BluetoothGattCharacteristic; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import org.im97mori.ble.ByteArrayCreater; import static org.im97mori.ble.constants.CharacteristicUUID.FAT_BURN_HEART_RATE_LOWER_LIMIT_CHARACTERISTIC; /** * Fat Burn Heart Rate Lower Limit (Characteristics UUID: 0x2A88) */ @SuppressWarnings({"WeakerAccess"}) public class FatBurnHeartRateLowerLimitAndroid extends FatBurnHeartRateLowerLimit implements Parcelable { /** * @see ByteArrayCreater */ public static final ByteArrayCreater<FatBurnHeartRateLowerLimitAndroid> CREATOR = new ByteArrayCreater<FatBurnHeartRateLowerLimitAndroid>() { /** * {@inheritDoc} */ @Override @NonNull public FatBurnHeartRateLowerLimitAndroid createFromParcel(@NonNull Parcel in) { return new FatBurnHeartRateLowerLimitAndroid(in); } /** * {@inheritDoc} */ @Override @NonNull public FatBurnHeartRateLowerLimitAndroid[] newArray(int size) { return new FatBurnHeartRateLowerLimitAndroid[size]; } /** * {@inheritDoc} */ @NonNull public FatBurnHeartRateLowerLimitAndroid createFromByteArray(@NonNull byte[] values) { BluetoothGattCharacteristic bluetoothGattCharacteristic = new BluetoothGattCharacteristic(FAT_BURN_HEART_RATE_LOWER_LIMIT_CHARACTERISTIC, 0, 0); bluetoothGattCharacteristic.setValue(values); return new FatBurnHeartRateLowerLimitAndroid(bluetoothGattCharacteristic); } }; /** * Constructor from {@link BluetoothGattCharacteristic} * * @param bluetoothGattCharacteristic Characteristics UUID: 0x2A88 */ public FatBurnHeartRateLowerLimitAndroid(@NonNull BluetoothGattCharacteristic bluetoothGattCharacteristic) { super(bluetoothGattCharacteristic.getValue()); } /** * Constructor from parameters * * @param fatBurnHeartRateLowerLimit Fat Burn Heart Rate Lower Limit */ public FatBurnHeartRateLowerLimitAndroid(int fatBurnHeartRateLowerLimit) { super(fatBurnHeartRateLowerLimit); } /** * Constructor from {@link Parcel} * * @param in Parcel */ private FatBurnHeartRateLowerLimitAndroid(@NonNull Parcel in) { //noinspection ConstantConditions super(in.createByteArray()); } /** * {@inheritDoc} */ @Override public int describeContents() { return 0; } /** * {@inheritDoc} */ @Override public void writeToParcel(@NonNull Parcel dest, int flags) { dest.writeByteArray(getBytes()); } }
true
7d99ea1a1647de3d5213e354558f0d680ac697ab
Java
YangFangXin/wenda
/src/main/java/service/LikeService.java
UTF-8
2,131
2.359375
2
[]
no_license
package service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import model.EntityType; import util.RedisKeyUtil; @Service public class LikeService { @Autowired private RedisDBForKeyService redisDBForKeyService; /* * 这里应该考虑事务 */ public long likeComment(int userId,int commentId) { String likeKey = RedisKeyUtil.getLikeKey(commentId, EntityType.COMMENT); String dislikeKey = RedisKeyUtil.getDislikeKey(commentId, EntityType.COMMENT); redisDBForKeyService.srem(dislikeKey, String.valueOf(userId)); return redisDBForKeyService.sadd(likeKey, String.valueOf(userId)); } public long dislikeComment(int userId,int commentId) { String likeKey = RedisKeyUtil.getLikeKey(commentId, EntityType.COMMENT); String dislikeKey = RedisKeyUtil.getDislikeKey(commentId, EntityType.COMMENT); redisDBForKeyService.srem(likeKey, String.valueOf(userId)); return redisDBForKeyService.sadd(dislikeKey, String.valueOf(userId)); } public long getCommentLikeCount(int commentId) { String key = RedisKeyUtil.getLikeKey(commentId, EntityType.COMMENT); return redisDBForKeyService.scard(key); } public void cancelLikeOrDisLike(int userId,int commentId) { String likeKey = RedisKeyUtil.getLikeKey(commentId, EntityType.COMMENT); String dislikeKey = RedisKeyUtil.getDislikeKey(commentId, EntityType.COMMENT); redisDBForKeyService.srem(likeKey, String.valueOf(userId)); redisDBForKeyService.srem(dislikeKey, String.valueOf(userId)); } public boolean isLikeComment(int userId,int commentId) { String key = RedisKeyUtil.getLikeKey(commentId, EntityType.COMMENT); if(redisDBForKeyService.sismember(key, String.valueOf(userId))) { return true; }else { return false; } } public boolean isDislikeComment(int userId,int commentId) { String key = RedisKeyUtil.getDislikeKey(commentId, EntityType.COMMENT); if(redisDBForKeyService.sismember(key, String.valueOf(userId))) { return true; }else { return false; } } }
true
1eee401a32cd950000766d2e328705678dd8a561
Java
shanthan1410/ShanthansWorksspace
/locatorsConcepts/src/locatorsConcepts/CSSSelector.java
UTF-8
364
2.234375
2
[]
no_license
package locatorsConcepts; public class CSSSelector { public static void main(String[] args) { // TODO Auto-generated method stub /* cssselector is 10 times faster than xpath i.e if you want to indentify * the element in a page the css can do 10 times fast rather than xpath * * class under the class can be done by css selector only * */ } }
true
d266e1aabc8bc459b40a7646529d8fc7bbb0d207
Java
snailCry/fitness_test
/src/main/java/com/qwwj/pojo/SysUser.java
UTF-8
1,774
2.1875
2
[]
no_license
package com.qwwj.pojo; import javax.persistence.*; @Table(name = "sys_user") public class SysUser { @Id private String id; /** * 用户名 */ private String username; private String password; private String nickname; private Integer age; private Integer sex; /** * @return id */ public String getId() { return id; } /** * @param id */ public void setId(String id) { this.id = id; } /** * 获取用户名 * * @return username - 用户名 */ public String getUsername() { return username; } /** * 设置用户名 * * @param username 用户名 */ public void setUsername(String username) { this.username = username; } /** * @return password */ public String getPassword() { return password; } /** * @param password */ public void setPassword(String password) { this.password = password; } /** * @return nickname */ public String getNickname() { return nickname; } /** * @param nickname */ public void setNickname(String nickname) { this.nickname = nickname; } /** * @return age */ public Integer getAge() { return age; } /** * @param age */ public void setAge(Integer age) { this.age = age; } /** * @return sex */ public Integer getSex() { return sex; } /** * @param sex */ public void setSex(Integer sex) { this.sex = sex; } }
true
9f5539e004cc4c4be6c03d893442b3b44a521b3b
Java
PARobotics4511/java-gauntlet
/classes/Epsilon.java
UTF-8
239
2.203125
2
[]
no_license
package javagauntlet.classes; /** * * @author brendon-boldt at https://github.com/brendon-boldt */ public class Epsilon { public final Integer finalVariable; public Epsilon(Integer arg) { finalVariable = arg; } }
true
1f12f9fc0ec7d4c225e4de302cf64ccbc606a6d3
Java
wanlong1234567/JavaOOP_day06
/day06_all/day06/MultiTypeDemo.java
GB18030
507
3.28125
3
[]
no_license
package oo.day06; //̬ʾ public class MultiTypeDemo { public static void main(String[] args) { Aoo o1 = new Boo(); // Boo o2 = (Boo)o1; //o1ָĶBoo Inter1 o3 = (Inter1)o1; //o1ָĶʵInter1ӿ //Coo o4 = (Coo)o1; //ClassCastExceptionת쳣 if(o1 instanceof Coo){ //false Coo o5 = (Coo)o1; } } } interface Inter1{ } class Aoo{ } class Boo extends Aoo implements Inter1{ } class Coo extends Aoo{ }
true
997c102cb69344c06538e982ba9e80a09f81ab63
Java
yimiaoxiehou/read-the-code-of-junit
/junit1.0/src/test/MathTest.java
UTF-8
676
2.25
2
[]
no_license
package test; import com.okada.junit.Assert; import com.okada.junit.TestCase; import com.okada.junit.TestRunner; import com.okada.junit.TestSuite; public class MathTest extends TestCase { public MathTest(String testMethodName) { super(testMethodName); } public void add() { Assert.assertEquals(1, 2); } public static TestSuite suite() { TestSuite testSuite = new TestSuite(); testSuite.addTest(new MathTest("ok"));// 该方法并不存在 testSuite.addTest(new MathTest("add")); return testSuite; } public static void main(String[] args) { TestRunner.main("test.MathTest"); } }
true
e26168310ff3ce013217b007acd157d6552e4ae4
Java
bjblack/anathema_3e
/Character_Equipment/src/main/java/net/sf/anathema/equipment/stats/ItemStatsSet.java
UTF-8
1,429
3.125
3
[]
no_license
package net.sf.anathema.equipment.stats; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; public class ItemStatsSet implements Iterable<IEquipmentStats> { public static ItemStatsSet withSingleStat (IEquipmentStats stats) { return from (stats); } public static ItemStatsSet from (IEquipmentStats... stats) { ItemStatsSet statsSet = new ItemStatsSet (); for (IEquipmentStats stat : stats) { statsSet.add (stat); } return statsSet; } private List<IEquipmentStats> list; public ItemStatsSet () { this (new ArrayList<> ()); } public ItemStatsSet (List<IEquipmentStats> statses) { this.list = statses; } public void add (IEquipmentStats stats) { list.add (stats); } public void adopt (ItemStatsSet statsSet) { list.addAll (statsSet.list); } @Override public Iterator<IEquipmentStats> iterator () { return list.iterator (); } public boolean hasOnlyOneStat () { return list.size () == 1; } public ItemStatsSet apply (Function<IEquipmentStats, IEquipmentStats> modifier) { Stream<IEquipmentStats> stats = list.stream (); List<IEquipmentStats> modifiedStats = stats.map (modifier).collect (Collectors.toList ()); return new ItemStatsSet (modifiedStats); } }
true
66fd2c8b82747e19958aeba30f474b63ed74a587
Java
car517/CSE2
/hw07/NumberStack.java
UTF-8
8,544
3.75
4
[]
no_license
///////////////////////// // Carlos Rosario // September 22 2014 // CSE 002 // NumberStack Java Program import java.util.Scanner; //import scanner public class NumberStack { // class static Scanner myScanner; //declare scanner public static void main(String[] args){ //add main method myScanner= new Scanner (System.in); //scanner input declaration while (true) { //while loop just to keep this running continuosly until user decides to break, the same function is done with for and do while loops below but it is commented so the program can run continuously, //for loops //for (boolean loop=true; loop=true;) { //Put this for future reference, does the same function as while(true). If I were to write three different programs for each type of loop this is what I would use for for loops System.out.print("Enter an integer between 0 and 9 inclusive (for loop) (Any other key to quit loop): "); //Gives user direction int input=0; //intializing user input if (!myScanner.hasNextInt()) { //if input is not an integer tell user and break System.out.println("You have not entered an integer"); break; } input= myScanner.nextInt(); //set user input as variable input if ( (input>=0) && (input<=9) ) { //set the range for(int i = 1; i <= input; i++) { //exterior for loop for what will happen with each number increment leading to user input int times = i; //initializing how many times code will repeat going down for each increment int length = (2 * i) - 1; //how many times will number get repeated in the same line, if number is 4, then 4 will get repeated (4*2)-1=7 times on same line String str = ""; String str2= ""; // Initializing string for repeating integers String space= ""; String space2=" "; // Initializing string for repeating space that will centralize everyloop for(int j = 0; j < length; j++) { //for loop for length, which will also be amount of times the dash will repeat str += i; str2 += "-"; //sets variables equal to how many times the dash and increment should repeat } if (i<input) { //for spacing of print, this algorithm will apply to every increment before user input only for (int p=0; p<(input-i); p++) { // for loop will loop as long as increments are less than input-i, if input is 5, then for number 4, it will be spaced once before code prints space += space2; //Total space } } for(int k = 0; k < times; k++) { //loop for how many lines variable space+str will repeat System.out.println(space+str); //print for space + str } System.out.println(space+str2); //total dashes repeated after every number increment } input=0; // reset input } //end of if statement else { System.out.println("You have not entered an integer within range"); break; //what will print if number is not in range } //} //end of for loop //While Loops //comments only placed where while loops are placed, use comments from above to understand what is going on with variables, if statements, etc //while (true) { // For future reference if I want to run three different programs System.out.print("Enter an integer between 0 and 9 inclusive (while loop) (Any other key to quit loop): "); //Direction for user input=0;//intialize variable if (!myScanner.hasNextInt()) { System.out.println("You have not entered an integer"); break; } input= myScanner.nextInt(); if ( (input>=0) && (input<=9) ) { int i = 1; while (i <= input) { //while i is less than or equal to input this will run int times = i; int length = (2 * i) - 1; String str = ""; String str2= ""; String space= ""; String space2=" "; int j = 0; while (j < length) { //while j is less than length variable this will run str += i; str2 += "-"; j++; } if (i<input) { int p=0; while (p<(input-i) ) { // while p is less than (input-i) this will run space += space2; p++; } } int k = 0; while (k < times) { //while k is less than times run this program System.out.println(space+str); k++; } System.out.println(space+str2); i++; } input=0; } //end of if statement else { System.out.println("You have not entered an integer within range"); break; } //} //end of while loop //Do while //do { //Same as above two, future reference if I would like to seperate these into three different programs System.out.print("Enter an integer between 0 and 9 inclusive (do while loop) (Any other key to quit loop) "); input=0; if (!myScanner.hasNextInt()) { System.out.println("You have not entered an integer"); break; } input= myScanner.nextInt(); if ( (input>=0) && (input<=9) ) { int i = 1; do { // "Do" what is below int times = i; int length = (2 * i) - 1; String str = ""; String str2= ""; String space= ""; String space2=" "; int j=0; do { // "Do" what is below str += i; str2 += "-"; j++; } while (j < length); //while j is less than length if (i<input) { int p=0; do { //"Do" what is below space += space2; p++; } while ( p<(input-i) ); //while p is less than input-i } int k = 0; do { //"Do" what is below System.out.println(space+str); k++; } while (k < times); // while k is less than times System.out.println(space+str2); i++; } while (i <= input); //while i is less than or equal to input input=0; } //end of if statement else { System.out.println("You have not entered an integer within range"); break; } //} while (true); ////Same as above, future reference if I would like to seperate these into three different programs }//end of entire loop } //end of main method } //end of class
true
88818b1d5c358ebfb5386c511ef6f7c8b93a03f0
Java
muchajan/ispok
/src/main/java/ispok/bo/Cashgame.java
UTF-8
5,109
2.265625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ispok.bo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; /** * * @author Jan Mucha <j.mucha@seznam.cz> */ @Entity public class Cashgame extends AbstractBusinessObject { @Column(nullable = false) private String name; @Column(nullable = true, length = 255, unique = false) private String info; @ManyToOne() private Office office; @Column(nullable = false) private float bigBlind; @Column(nullable = false) private float smallBlind; @Column(nullable = false) private float ante; @Column(nullable = false) private float minBuyin; @Column(nullable = false) private float maxBuyin; @Column(nullable = false) private float rake; @Column(nullable = false) private float maxRake; @Column(nullable = false) private int points; @Column(nullable = false) private int chillTime; @Column(nullable = false) private boolean enabled; /** * Get the value of enabled * * @return the value of enabled */ public boolean isEnabled() { return enabled; } /** * Set the value of enabled * * @param enabled new value of enabled */ public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getChillTime() { return chillTime; } public void setChillTime(int chillTime) { this.chillTime = chillTime; } /** * Get the value of info * * @return the value of info */ public String getInfo() { return info; } public Office getOffice() { return office; } public void setOffice(Office Office) { this.office = Office; } /** * Set the value of info * * @param info new value of info */ public void setInfo(String info) { this.info = info; } /** * Get the value of minBuyin * * @return the value of minBuyin */ public float getMinBuyin() { return minBuyin; } /** * Set the value of minBuyin * * @param minBuyin new value of minBuyin */ public void setMinBuyin(float minBuyin) { this.minBuyin = minBuyin; } /** * Get the value of ante * * @return the value of ante */ public float getAnte() { return ante; } /** * Set the value of ante * * @param ante new value of ante */ public void setAnte(float ante) { this.ante = ante; } /** * Get the value of points * * @return the value of points */ public int getPoints() { return points; } /** * Set the value of points * * @param points new value of points */ public void setPoints(int points) { this.points = points; } /** * Get the value of maxRake * * @return the value of maxRake */ public float getMaxRake() { return maxRake; } /** * Set the value of maxRake * * @param maxRake new value of maxRake */ public void setMaxRake(float maxRake) { this.maxRake = maxRake; } /** * Get the value of rake * * @return the value of rake */ public float getRake() { return rake; } /** * Set the value of rake * * @param rake new value of rake */ public void setRake(float rake) { this.rake = rake; } /** * Get the value of maxBuyin * * @return the value of maxBuyin */ public float getMaxBuyin() { return maxBuyin; } /** * Set the value of maxBuyin * * @param maxBuyin new value of maxBuyin */ public void setMaxBuyin(float maxBuyin) { this.maxBuyin = maxBuyin; } /** * Get the value of smallBlind * * @return the value of smallBlind */ public float getSmallBlind() { return smallBlind; } /** * Set the value of smallBlind * * @param smallBlind new value of smallBlind */ public void setSmallBlind(float smallBlind) { this.smallBlind = smallBlind; } /** * Get the value of bigBlind * * @return the value of bigBlind */ public float getBigBlind() { return bigBlind; } /** * Set the value of bigBlind * * @param bigBlind new value of bigBlind */ public void setBigBlind(float bigBlind) { this.bigBlind = bigBlind; } /** * Get the value of name * * @return the value of name */ public String getName() { return name; } /** * Set the value of name * * @param name new value of name */ public void setName(String name) { this.name = name; } }
true
a505c72a680e9bb2735b6c02e139987214d38012
Java
Prathu215/e-Portal
/Rest_SpringBoot/TabnerPortal/src/main/java/com/tabner/entities/Employee.java
UTF-8
2,080
2.578125
3
[]
no_license
package com.tabner.entities; import java.util.ArrayList; import java.util.List; /* * this is a simple pojo class to create objects for different employees present the payroll pdf */ public class Employee { private String name; private String id; private String rate; private String hours; private String earnings; private String expenses; private String gross; private List<String> taxes = new ArrayList<String> (); private List<String> deductions= new ArrayList<String> (); private List<String> netPay = new ArrayList<String> (); private String periodEnding; private String payDate; public String getPeriodEnding() { return periodEnding; } public void setPeriodEnding(String periodEnding) { this.periodEnding = periodEnding; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getHours() { return hours; } public void setHours(String hours) { this.hours = hours; } public String getEarnings() { return earnings; } public void setEarnings(String earnings) { this.earnings = earnings; } public String getExpenses() { return expenses; } public void setExpenses(String expenses) { this.expenses = expenses; } public String getGross() { return gross; } public void setGross(String gross) { this.gross = gross; } public List<String> getTaxes() { return taxes; } public void setTaxes(List<String> taxes) { this.taxes = taxes; } public List<String> getDeductions() { return deductions; } public void setDeductions(List<String> deductions) { this.deductions = deductions; } public List<String> getNetPay() { return netPay; } public void setNetPay(List<String> netPay) { this.netPay = netPay; } public String getPayDate() { return payDate; } public void setPayDate(String payDate) { this.payDate = payDate; } }
true
9356ed7bcae8706eda8226762842f7f21abd6492
Java
Ant1B2x/N7_IDM_Project
/fr.n7.simplePDL/src/simplepdl/impl/NeedImpl.java
UTF-8
9,925
1.835938
2
[]
no_license
/** */ package simplepdl.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import simplepdl.Need; import simplepdl.Resource; import simplepdl.SimplepdlPackage; import simplepdl.WorkDefinition; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Need</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link simplepdl.impl.NeedImpl#getNbResources <em>Nb Resources</em>}</li> * <li>{@link simplepdl.impl.NeedImpl#getResource <em>Resource</em>}</li> * <li>{@link simplepdl.impl.NeedImpl#getWorkdefinition <em>Workdefinition</em>}</li> * </ul> * * @generated */ public class NeedImpl extends MinimalEObjectImpl.Container implements Need { /** * The default value of the '{@link #getNbResources() <em>Nb Resources</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNbResources() * @generated * @ordered */ protected static final int NB_RESOURCES_EDEFAULT = 0; /** * The cached value of the '{@link #getNbResources() <em>Nb Resources</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNbResources() * @generated * @ordered */ protected int nbResources = NB_RESOURCES_EDEFAULT; /** * The cached value of the '{@link #getResource() <em>Resource</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getResource() * @generated * @ordered */ protected Resource resource; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected NeedImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return SimplepdlPackage.Literals.NEED; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getNbResources() { return nbResources; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNbResources(int newNbResources) { int oldNbResources = nbResources; nbResources = newNbResources; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SimplepdlPackage.NEED__NB_RESOURCES, oldNbResources, nbResources)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Resource getResource() { if (resource != null && resource.eIsProxy()) { InternalEObject oldResource = (InternalEObject)resource; resource = (Resource)eResolveProxy(oldResource); if (resource != oldResource) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, SimplepdlPackage.NEED__RESOURCE, oldResource, resource)); } } return resource; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Resource basicGetResource() { return resource; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetResource(Resource newResource, NotificationChain msgs) { Resource oldResource = resource; resource = newResource; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SimplepdlPackage.NEED__RESOURCE, oldResource, newResource); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setResource(Resource newResource) { if (newResource != resource) { NotificationChain msgs = null; if (resource != null) msgs = ((InternalEObject)resource).eInverseRemove(this, SimplepdlPackage.RESOURCE__NEEDS, Resource.class, msgs); if (newResource != null) msgs = ((InternalEObject)newResource).eInverseAdd(this, SimplepdlPackage.RESOURCE__NEEDS, Resource.class, msgs); msgs = basicSetResource(newResource, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SimplepdlPackage.NEED__RESOURCE, newResource, newResource)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public WorkDefinition getWorkdefinition() { if (eContainerFeatureID() != SimplepdlPackage.NEED__WORKDEFINITION) return null; return (WorkDefinition)eInternalContainer(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetWorkdefinition(WorkDefinition newWorkdefinition, NotificationChain msgs) { msgs = eBasicSetContainer((InternalEObject)newWorkdefinition, SimplepdlPackage.NEED__WORKDEFINITION, msgs); return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setWorkdefinition(WorkDefinition newWorkdefinition) { if (newWorkdefinition != eInternalContainer() || (eContainerFeatureID() != SimplepdlPackage.NEED__WORKDEFINITION && newWorkdefinition != null)) { if (EcoreUtil.isAncestor(this, newWorkdefinition)) throw new IllegalArgumentException("Recursive containment not allowed for " + toString()); NotificationChain msgs = null; if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); if (newWorkdefinition != null) msgs = ((InternalEObject)newWorkdefinition).eInverseAdd(this, SimplepdlPackage.WORK_DEFINITION__NEED, WorkDefinition.class, msgs); msgs = basicSetWorkdefinition(newWorkdefinition, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, SimplepdlPackage.NEED__WORKDEFINITION, newWorkdefinition, newWorkdefinition)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SimplepdlPackage.NEED__RESOURCE: if (resource != null) msgs = ((InternalEObject)resource).eInverseRemove(this, SimplepdlPackage.RESOURCE__NEEDS, Resource.class, msgs); return basicSetResource((Resource)otherEnd, msgs); case SimplepdlPackage.NEED__WORKDEFINITION: if (eInternalContainer() != null) msgs = eBasicRemoveFromContainer(msgs); return basicSetWorkdefinition((WorkDefinition)otherEnd, msgs); } return super.eInverseAdd(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case SimplepdlPackage.NEED__RESOURCE: return basicSetResource(null, msgs); case SimplepdlPackage.NEED__WORKDEFINITION: return basicSetWorkdefinition(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) { switch (eContainerFeatureID()) { case SimplepdlPackage.NEED__WORKDEFINITION: return eInternalContainer().eInverseRemove(this, SimplepdlPackage.WORK_DEFINITION__NEED, WorkDefinition.class, msgs); } return super.eBasicRemoveFromContainerFeature(msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SimplepdlPackage.NEED__NB_RESOURCES: return getNbResources(); case SimplepdlPackage.NEED__RESOURCE: if (resolve) return getResource(); return basicGetResource(); case SimplepdlPackage.NEED__WORKDEFINITION: return getWorkdefinition(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SimplepdlPackage.NEED__NB_RESOURCES: setNbResources((Integer)newValue); return; case SimplepdlPackage.NEED__RESOURCE: setResource((Resource)newValue); return; case SimplepdlPackage.NEED__WORKDEFINITION: setWorkdefinition((WorkDefinition)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case SimplepdlPackage.NEED__NB_RESOURCES: setNbResources(NB_RESOURCES_EDEFAULT); return; case SimplepdlPackage.NEED__RESOURCE: setResource((Resource)null); return; case SimplepdlPackage.NEED__WORKDEFINITION: setWorkdefinition((WorkDefinition)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case SimplepdlPackage.NEED__NB_RESOURCES: return nbResources != NB_RESOURCES_EDEFAULT; case SimplepdlPackage.NEED__RESOURCE: return resource != null; case SimplepdlPackage.NEED__WORKDEFINITION: return getWorkdefinition() != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (nbResources: "); result.append(nbResources); result.append(')'); return result.toString(); } } //NeedImpl
true
974d602f9a7ab541d49ae68c13f72fb2ec7658f9
Java
NesterovAndrey/FastenTest
/src/core/mapper/CollectionToPathMap.java
UTF-8
890
2.84375
3
[]
no_license
package core.mapper; import java.util.*; /** * Преобразует коллекцию в Map в качестве ключа испузуется путь * @param <T> */ public class CollectionToPathMap<T> implements IResultMapper<Map<String,Collection<T>>,Collection<T>>{ private final IPathExtractor<T> pathExtractor; public CollectionToPathMap(IPathExtractor<T> pathExtractor) { this.pathExtractor = pathExtractor; } @Override public Map<String, Collection<T>> map(Collection<T> data) { Map<String,Collection<T>> result=new HashMap<>(); data.stream().forEach((i)-> { String nextPaht=this.pathExtractor.getPath(i); Collection<T> queue=result.getOrDefault(nextPaht,new ArrayList<>()); queue.add(i); result.putIfAbsent(nextPaht,queue); }); return result; } }
true
da4beffa5c323da89f622ed6fa48c9eaf2ea3754
Java
edhm/ReadinfCMS
/src/main/java/Mapper/PermisoMapper.java
UTF-8
410
2.3125
2
[]
no_license
package Mapper; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; import com.ehm.ReadingCMS.Model.Permiso; public class PermisoMapper implements RowMapper<Permiso> { @Override public Permiso mapRow(ResultSet rs, int rowNum) throws SQLException { Permiso permiso = new Permiso(); permiso.setNombre(rs.getString("Permiso")); return null; } }
true
053860f385c86151dcb5028e2051e801056768fe
Java
noear/solon
/solon-projects-cloud/solon-cloud/local-solon-cloud-plugin/src/test/java/demo/controller/Event2.java
UTF-8
672
2.390625
2
[ "Apache-2.0" ]
permissive
package demo.controller; import org.noear.snack.ONode; import org.noear.solon.cloud.CloudEventHandler; import org.noear.solon.cloud.annotation.CloudEvent; import org.noear.solon.cloud.model.Event; /** * 云端事件(本地实现时,不支持ACK,不支持延时;最好还是引入消息队列的适配框架) */ @CloudEvent("demo.event2") public class Event2 implements CloudEventHandler { @Override public boolean handle(Event event) throws Throwable { System.out.println("云端事件打印: " + ONode.stringify(event)); if (event.times() > 2) { return true; } else { return false; } } }
true
34ce642480adadff51d3a4feb707ca1b9eb7eaee
Java
dengjiaping/shipinshenqi
/PineApple/src/com/lzc/pineapple/search/SearchFragment.java
UTF-8
7,815
1.898438
2
[]
no_license
package com.lzc.pineapple.search; import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.lzc.pineapple.MainActivity; import com.lzc.pineapple.R; import com.lzc.pineapple.db.LocalSearchCacheInfo; import com.lzc.pineapple.db.SearchDBHelper; import com.lzc.pineapple.entity.StartPageEntity; import com.lzc.pineapple.fragment.BaseTabFragment; import com.lzc.pineapple.util.Utils; import com.lzc.pineapple.volley.VolleyError; public class SearchFragment extends BaseTabFragment implements SearChListener,SearchDBListener, OnClickListener { private SearchDBHelper dbHelper; public static final String HOT_VIDEO_KEY_WORD = "HOT_VIDEO_KEY_WORD"; public static final int HOT_VIDEO_FRAME = 0; public static final int LOCAL_SEARCH_CACHE_FRAME = 1; private int fragmentType = HOT_VIDEO_FRAME; private ImageView search; private ImageView delete; private EditText editText; private TextView searchTextView; private MainActivity activity; private List<String> hotWords = new ArrayList<String>(); private Fragment fragment = null; public static final Fragment newInstance() { Fragment fragment = new SearchFragment(); Bundle bundle = new Bundle(); // bundle.putString(Constant.DEVICE_NAME_KEY, deviceName); fragment.setArguments(bundle); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.fragment_search, null); activity = (MainActivity) getActivity(); openSearchDBhelper(); initViews(view); setListener(); initValues(); changeFrame(fragmentType); return view; } @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); closeSearchDBHelper(); } @Override public void refreshCompleted(StartPageEntity response) { // TODO Auto-generated method stub super.refreshCompleted(response); hotWords = response.getvHotWords(); if(HOT_VIDEO_FRAME == fragmentType){ ((HotVideoFragment) fragment).updateHotWords(hotWords); } } @Override public void refreshError(VolleyError error) { // TODO Auto-generated method stub super.refreshError(error); } private void initValues(){ StartPageEntity entity = activity.getStartPageEntity(); if(entity != null){ hotWords = entity.getvHotWords(); } } private void initViews(View view) { searchTextView = (TextView) view.findViewById(R.id.search); delete = (ImageView) view.findViewById(R.id.image_delete); search = (ImageView) view.findViewById(R.id.image_search); editText = (EditText) view.findViewById(R.id.editext_content); editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH); } private void setListener() { searchTextView.setOnClickListener(this); search.setOnClickListener(this); editText.setOnClickListener(this); delete.setOnClickListener(this); } private void openSearchDBhelper() { dbHelper = new SearchDBHelper(this.getActivity()); dbHelper.open(); } private void closeSearchDBHelper() { dbHelper.close(); } @Override public void changeFragment(int type) { // TODO Auto-generated method stub changeFrame(type); } private void insertRecordToDataBase(String nowSearch) { // TODO Auto-generated method stub String createTime = Utils.getSysNowTime(); LocalSearchCacheInfo localSearchCacheInfo = new LocalSearchCacheInfo(); localSearchCacheInfo.setCreateTime(createTime); localSearchCacheInfo.setName(nowSearch); dbHelper.insertVideoDataToTable(localSearchCacheInfo); } private void changeFrame(int frameClass) { // if (fragmentType == frameClass) { // return; // } FragmentManager fm = getFragmentManager(); FragmentTransaction ft = null; if (fm != null) { ft = fm.beginTransaction(); } else { return; } switch (frameClass) { case HOT_VIDEO_FRAME: fragment = HotVideoFragment.newInstance(hotWords); ((HotVideoFragment) fragment).setSearchListener(this); ft.replace(R.id.fragment_content, fragment); break; case LOCAL_SEARCH_CACHE_FRAME: fragment = LocalSearchCacheFragment.newInstance(); ((LocalSearchCacheFragment) fragment).setSearchListener(this); ((LocalSearchCacheFragment) fragment).setSearchDBListener(this); ft.replace(R.id.fragment_content, fragment); break; } ft.commit(); fragmentType = frameClass; } @Override public void search(String nowSearch) { // TODO Auto-generated method stub insertRecordToDataBase(nowSearch); searchKeyState(nowSearch); } private void searchKeyState(String nowSearch) { if (!Utils.hasInternet(getActivity())) { Utils.showTips(getActivity(), getActivity().getResources().getString(R.string.none_network)); return; } VideoSearchedActivity.launch(getActivity(), nowSearch); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.search: search(); break; case R.id.image_search: break; case R.id.editext_content: String nowSearch = editText.getText().toString(); goToLocalSearchCache(); break; case R.id.image_delete: clearEditContent(); break; } } private void search(){ String nowSearch = editText.getText().toString(); if (nowSearch == null || nowSearch.trim().length() == 0) { // 输入的搜索内容无效 Utils.showTips(getActivity(),getActivity().getResources().getString(R.string.more_search_input_invalid)); return; } search(nowSearch); } private void goToLocalSearchCache(){ changeFragment(LOCAL_SEARCH_CACHE_FRAME); } private void clearEditContent(){ editText.setText(""); } @Override public Cursor getCacheCursor() { // TODO Auto-generated method stub return dbHelper.getVideoTopFive(); } @Override public void clearCache() { // TODO Auto-generated method stub dbHelper.clearVideoTable(); } }
true
39dcd8a61b0384860347b7ea14684e8261157b35
Java
Vav1lon/Pereposter
/pereposter/src/main/java/com/pereposter/control/SocialNetworkControl.java
UTF-8
2,072
2.1875
2
[]
no_license
package com.pereposter.control; import com.pereposter.control.social.SocialControl; import com.pereposter.entity.Post; import com.pereposter.entity.RestResponse; import com.pereposter.entity.internal.SocialUserAccount; import com.pereposter.utils.ServiceHelper; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Component("socialNetworkControl") @Transactional(propagation = Propagation.MANDATORY) public class SocialNetworkControl { @Autowired private ServiceHelper serviceHelper; @Autowired private SessionFactory sessionFactory; public RestResponse initializationSocialAccount(String id) { SocialUserAccount user = (SocialUserAccount) getSession().get(SocialUserAccount.class, Long.valueOf(id)); RestResponse result = null; if (user != null) { initializationUser(user); } else { result = new RestResponse("Not found Social account"); } return result; } public void initializationUser(SocialUserAccount account) { SocialControl service = serviceHelper.getSocialNetworkControl(account.getSocialNetwork()); Post post = service.findLastUserPost(account); if (post != null) { account.setLastPostId(post.getId()); account.setCreateDateLastPost(post.getCreatedDate()); account.setSocialUserId(post.getOwnerId()); //getSession().saveOrUpdate(account); } else { //TODO: пишем в лог что данной учетной записи не существует или пароль не верен //TODO: уведосить юзера что учетная запись не верна } } private Session getSession() { return sessionFactory.getCurrentSession(); } }
true
5f39845975381a9d54c1c0b3dec5541e08d5176a
Java
jberclaz/jass
/src/test/java/com/leflat/jass/server/ArtificialPlayerTests.java
UTF-8
7,238
2.515625
3
[ "MIT" ]
permissive
package com.leflat.jass.server; import com.leflat.jass.common.Announcement; import com.leflat.jass.common.BasePlayer; import com.leflat.jass.common.Card; import com.leflat.jass.common.Plie; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static com.leflat.jass.server.RulesTests.buildHand; import static org.junit.jupiter.api.Assertions.*; public class ArtificialPlayerTests { ArtificialPlayer player; Field playersPositionField, gameViewField, currentPlieField, handField; ArtificialPlayer otherPlayer; Map<Integer, Integer> playersPosition; GameView gameView; Plie currentPlie; List<Card> hand; @BeforeEach public void setUp() throws NoSuchFieldException, IllegalAccessException { player = new ArtificialPlayer(1, "name"); playersPositionField = ArtificialPlayer.class.getDeclaredField("playersPositions"); playersPositionField.setAccessible(true); gameViewField = ArtificialPlayer.class.getDeclaredField("gameView"); gameViewField.setAccessible(true); currentPlieField = ArtificialPlayer.class.getDeclaredField("currentPlie"); currentPlieField.setAccessible(true); handField = BasePlayer.class.getDeclaredField("hand"); handField.setAccessible(true); playersPosition = (Map<Integer, Integer>) playersPositionField.get(player); gameView = (GameView) gameViewField.get(player); hand = (List<Card>) handField.get(player); otherPlayer = new ArtificialPlayer(2, "Pischus"); } @Test public void test_set_player_info() { player.setPlayerInfo(otherPlayer); assertEquals(playersPosition.size(), 1); assertTrue(playersPosition.containsKey(2)); assertEquals(playersPosition.get(2), 1); } @Test public void test_draw_card() { for (int i = 0; i < 35; i++) { player.setCard(otherPlayer, i, new Card(0)); } var card = player.drawCard(); assertEquals(card, 35); } @Test public void test_player_order() throws IllegalAccessException { var thirdPlayer = new ArtificialPlayer(3, "GC"); var fourthPlayer = new ArtificialPlayer(0, "Mono"); player.setPlayerInfo(otherPlayer); player.setPlayerInfo(thirdPlayer); player.setPlayerInfo(fourthPlayer); assertEquals(playersPosition.size(), 3); assertEquals(playersPosition.get(0), 3); player.setPlayersOrder(Arrays.asList(3, 2, 0, 1)); assertEquals(playersPosition.get(3), 1); assertEquals(playersPosition.get(2), 2); assertEquals(playersPosition.get(0), 3); } @Test public void test_set_hand() throws PlayerLeftExpection, IllegalAccessException { player.setHand(buildHand(1, 4, 9, 10, 12, 20, 22, 30, 33)); assertEquals(hand.size(), 9); assertTrue(hand.contains(new Card(9))); currentPlie = (Plie) currentPlieField.get(player); assertEquals(currentPlie.getSize(), 0); } @Test public void test_choose_atout() throws PlayerLeftExpection { var thirdPlayer = new ArtificialPlayer(3, "GC"); var fourthPlayer = new ArtificialPlayer(0, "Mono"); player.setPlayerInfo(otherPlayer); player.setPlayerInfo(thirdPlayer); player.setPlayerInfo(fourthPlayer); player.setPlayersOrder(Arrays.asList(0, 1, 2, 3)); player.setHand(buildHand(1, 2, 10, 11, 20, 21, 29, 31, 28)); assertEquals(player.chooseAtout(true), Card.COLOR_NONE); assertEquals(player.chooseAtout(false), Card.COLOR_CLUB); player.setHand(buildHand(1, 2, 3, 4, 10, 20, 30, 31, 32)); assertEquals(player.chooseAtout(true), Card.COLOR_SPADE); } @Test public void test_played_card() throws PlayerLeftExpection, IllegalAccessException { Card.atout = Card.COLOR_DIAMOND; player.setPlayerInfo(otherPlayer); player.setHand(buildHand(1, 4, 9, 10, 12, 20, 22, 30, 33)); player.setPlayedCard(otherPlayer, new Card(2)); currentPlie = (Plie) currentPlieField.get(player); assertEquals(currentPlie.getSize(), 1); player.setPlayedCard(otherPlayer, new Card(11)); } @Test public void test_play() throws PlayerLeftExpection { var secondPlayer = new ArtificialPlayer(0, "Wein"); var fourthPlayer = new ArtificialPlayer(3, "Hhip"); player.setPlayerInfo(secondPlayer); player.setPlayerInfo(otherPlayer); player.setPlayerInfo(fourthPlayer); player.setPlayersOrder(Arrays.asList(1, 3, 0, 2)); var originalHand = buildHand(1, 4, 9, 10, 12, 20, 22, 30, 33); player.setHand(originalHand); player.setAtout(Card.COLOR_HEART, otherPlayer); var card = player.play(); assertEquals(8, hand.size()); assertFalse(hand.contains(card)); assertTrue(originalHand.contains(card)); } @Test public void test_get_announcements() throws PlayerLeftExpection { var secondPlayer = new ArtificialPlayer(0, "Wein"); var fourthPlayer = new ArtificialPlayer(3, "Hhip"); player.setPlayerInfo(secondPlayer); player.setPlayerInfo(otherPlayer); player.setPlayerInfo(fourthPlayer); player.setPlayersOrder(Arrays.asList(1, 3, 0, 2)); player.setHand(buildHand(1, 2, 3, 9, 10, 11, 20, 21, 23)); player.setAtout(Card.COLOR_HEART, otherPlayer); player.play(); assertEquals(8, hand.size()); var an = player.getAnnouncements(); assertEquals(2, an.size()); assertTrue(an.contains(new Announcement(Announcement.THREE_CARDS, new Card(3)))); assertTrue(an.contains(new Announcement(Announcement.THREE_CARDS, new Card(11)))); player.play(); an = player.getAnnouncements(); assertEquals(0, an.size()); } @Test public void test_set_announcements() throws PlayerLeftExpection, NoSuchFieldException, IllegalAccessException { player.setPlayerInfo(otherPlayer); player.setHand(buildHand(1, 2, 3, 9, 10, 11, 20, 21, 23)); player.setAnnouncements(otherPlayer, Collections.singletonList(new Announcement(Announcement.THREE_CARDS, new Card(33)))); Field cardsInGameField = GameView.class.getDeclaredField("cardsInGame"); Field cardsInHandsField = GameView.class.getDeclaredField("cardsInHands"); cardsInGameField.setAccessible(true); cardsInHandsField.setAccessible(true); var cardsInGame = (Map<Integer, Float[]>) cardsInGameField.get(gameView); var cardsInHands = (List<Card>[]) cardsInHandsField.get(gameView); assertEquals(24, cardsInGame.size()); assertEquals(3, cardsInHands[0].size()); assertTrue(cardsInHands[0].contains(new Card(33))); assertTrue(cardsInHands[0].contains(new Card(32))); assertTrue(cardsInHands[0].contains(new Card(31))); assertEquals(0, cardsInGame.get(34)[0]); assertEquals(0.5f, cardsInGame.get(34)[1]); assertEquals(0, cardsInGame.get(30)[0]); } }
true
59a7a0d53817af48189a51285ad3c4d6b842945a
Java
Pavithra0205/Collaboration
/NotificationDao.java
UTF-8
305
1.898438
2
[ "MIT" ]
permissive
package com.niit.dao; import java.util.List; import com.niit.model.Notification; public interface NotificationDao { void addNotification(Notification notification); List<Notification> getNotificationNotViewed(String email); Notification getNotificaiton(int id); void updateNotification(int id); }
true
21cd83a878e5b27bfbed8b09d5809dbb35b35f85
Java
Kashdeya/Tiny-Progressions
/src/main/java/com/kashdeya/tinyprogressions/recipes/FoodRecipes.java
UTF-8
10,846
2.0625
2
[]
no_license
package com.kashdeya.tinyprogressions.recipes; import com.kashdeya.tinyprogressions.handlers.ConfigHandler; import com.kashdeya.tinyprogressions.inits.TechFoods; import com.kashdeya.tinyprogressions.registry.recipes.ShapedRecipe; import com.kashdeya.tinyprogressions.registry.recipes.ShapelessRecipe; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraftforge.fml.common.registry.GameRegistry; public class FoodRecipes { public static IRecipe BSC_SUGAR_COOKIE; public static IRecipe BAMS_PIZZA; public static IRecipe JUICER, PEAR_JUICE, PEACH_JUICE, PEAR_JUICE2, PEACH_JUICE2; public static IRecipe APPLE_JUICE, CARROT_JUICE, POTATO_JUICE, BEET_JUICE, CACTUS_JUICE, SLIME_JUICE, WHEAT_JUICE, MELON_JUICE, PUMPKIN_JUICE; public static IRecipe APPLE_JUICE2, CARROT_JUICE2, POTATO_JUICE2, BEET_JUICE2, CACTUS_JUICE2, SLIME_JUICE2, WHEAT_JUICE2, MELON_JUICE2, PUMPKIN_JUICE2; public static IRecipe RASPBERRY_JUICE, BLUEBERRY_JUICE, BLACKBERRY_JUICE, MALOBERRY_JUICE; public static IRecipe RASPBERRY_JUICE2, BLUEBERRY_JUICE2, BLACKBERRY_JUICE2, MALOBERRY_JUICE2; public static IRecipe DIAMOND_APPLE, EMERALD_APPLE, IRON_APPLE, REDSTONE_APPLE; public static IRecipe GOLDEN_APPLE1, GOLDEN_APPLE2, GOLDEN_APPLE3, GOLDEN_APPLE4; public static IRecipe RAW_BACON, SUCC_PEARLS; public static IRecipe BACON_EGGS, BACON_EGGS_SANDWICH, BREAD_SLICE, BACON_SANDWICH, BEEF_SANDWICH, CHICKEN_SANDWICH, RABBIT_SANDWICH; public static void init() { // bsc cookie if (ConfigHandler.bsc_sugar_cookie){ BSC_SUGAR_COOKIE = new ShapedRecipe(new ItemStack(TechFoods.bsc_sugar_cookie, 8), "wsw", 'w', new ItemStack(Items.WHEAT), 's', new ItemStack(Items.SUGAR)); } // Bams Pizza if (ConfigHandler.bams_pizza){ BAMS_PIZZA = new ShapedRecipe(new ItemStack(TechFoods.bams_pizza), "bbb", " b ", " b ", 'b', new ItemStack(Items.BREAD)); } // SUCC THE PEARLS if (ConfigHandler.succ_juice && !ConfigHandler.succ_juice_bottle){ SUCC_PEARLS = new ShapelessRecipe(new ItemStack(TechFoods.succ_pearls), new ItemStack(Items.ENDER_PEARL), "juicer"); } if (ConfigHandler.succ_juice && ConfigHandler.succ_juice_bottle){ SUCC_PEARLS = new ShapelessRecipe(new ItemStack(TechFoods.succ_pearls), new ItemStack(Items.ENDER_PEARL), "juicer", "glassBottle"); } // Extra Drop w/o Bottles if (!ConfigHandler.extra_drop_bottle && ConfigHandler.extra_drops){ PEAR_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.pear_juice), "juicer", TechFoods.plump_pear); PEACH_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.peach_juice), "juicer", TechFoods.plump_peach); } // Extra Drops Bottles if (ConfigHandler.extra_drop_bottle && ConfigHandler.extra_drops){ PEAR_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.pear_juice), "juicer", TechFoods.plump_pear, "glassBottle"); PEACH_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.peach_juice), "juicer", TechFoods.plump_peach, "glassBottle"); } // Juices WO Bottles if (ConfigHandler.all_juices && ConfigHandler.JuiceBottles == false){ APPLE_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.apple_juice), "juicer", Items.APPLE); CARROT_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.carrot_juice), "juicer", Items.CARROT); POTATO_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.potatoe_juice), "juicer", Items.POTATO); BEET_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.beet_juice), "juicer", Items.BEETROOT); CACTUS_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.cactus_juice, 2), "juicer", Blocks.CACTUS); SLIME_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.slime_juice), "juicer", Items.SLIME_BALL); WHEAT_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.wheat_juice), "juicer", Items.WHEAT); MELON_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.melon_juice), "juicer", Items.MELON); PUMPKIN_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.pumpkin_juice, 2), "juicer", Blocks.PUMPKIN); } // Juice Bottles if (ConfigHandler.JuiceBottles && ConfigHandler.all_juices == false){ APPLE_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.apple_juice), "juicer", Items.APPLE, "glassBottle"); CARROT_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.carrot_juice), "juicer", Items.CARROT, "glassBottle"); POTATO_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.potatoe_juice), "juicer", Items.POTATO, "glassBottle"); BEET_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.beet_juice), "juicer", Items.BEETROOT, "glassBottle"); CACTUS_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.cactus_juice, 2), "juicer", Blocks.CACTUS, "glassBottle", "glassBottle"); SLIME_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.slime_juice), "juicer", Items.SLIME_BALL, "glassBottle"); WHEAT_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.wheat_juice), "juicer", Items.WHEAT, "glassBottle"); MELON_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.melon_juice), "juicer", Items.MELON, "glassBottle"); PUMPKIN_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.pumpkin_juice, 2), "juicer", Blocks.PUMPKIN, "glassBottle", "glassBottle"); } // Juices WO Bottles if (ConfigHandler.ExtraJuices && !ConfigHandler.ExtraJuicesBottles){ RASPBERRY_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.raspberry_juice), "juicer", "cropRaspberry"); BLUEBERRY_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.blueberry_juice), "juicer", "cropBlueberry"); BLACKBERRY_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.blackberry_juice), "juicer", "cropBlackberry"); MALOBERRY_JUICE = new ShapelessRecipe(new ItemStack(TechFoods.maloberry_juice), "juicer", "cropMaloberry"); } // Juice Bottles if (ConfigHandler.ExtraJuicesBottles && !ConfigHandler.ExtraJuices){ RASPBERRY_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.raspberry_juice), "juicer", "cropRaspberry", "glassBottle"); BLUEBERRY_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.blueberry_juice), "juicer", "cropBlueberry", "glassBottle"); BLACKBERRY_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.blackberry_juice), "juicer", "cropBlackberry", "glassBottle"); MALOBERRY_JUICE2 = new ShapelessRecipe(new ItemStack(TechFoods.maloberry_juice), "juicer", "cropMaloberry", "glassBottle"); } // Apples if (ConfigHandler.DiamondApple) { DIAMOND_APPLE = new ShapedRecipe(new ItemStack(TechFoods.diamond_apple), "ddd", "dad", "ddd", 'd', "gemDiamond", 'a', new ItemStack(Items.APPLE)); } if (ConfigHandler.EmeraldApple) { EMERALD_APPLE = new ShapedRecipe(new ItemStack(TechFoods.emerald_apple), "eee", "eae", "eee", 'e', "gemEmerald", 'a', new ItemStack(Items.APPLE)); } if (ConfigHandler.iron_apple) { IRON_APPLE = new ShapedRecipe(new ItemStack(TechFoods.iron_apple), "iii", "iai", "iii", 'i', "ingotIron", 'a', new ItemStack(Items.APPLE)); } if (ConfigHandler.redstone_apple) { REDSTONE_APPLE = new ShapedRecipe(new ItemStack(TechFoods.redstone_apple), "rrr", "rar", "rrr", 'r', "dustRedstone", 'a', new ItemStack(Items.APPLE)); } // Apple Pro if (ConfigHandler.ApplePro && ConfigHandler.NotchApple == false) { GOLDEN_APPLE1 = new ShapedRecipe(new ItemStack(Items.GOLDEN_APPLE), "ggg", "gag", "ggg", 'g', "nuggetGold", 'a', new ItemStack(Items.APPLE)); GOLDEN_APPLE2 = new ShapedRecipe(new ItemStack(TechFoods.golden_apple), "ggg", "gag", "ggg", 'g', "ingotGold", 'a', new ItemStack(Items.GOLDEN_APPLE)); GOLDEN_APPLE3 = new ShapedRecipe(new ItemStack(Items.GOLDEN_APPLE, 1, 1), "ggg", "gag", "ggg", 'g', "blockGold", 'a', TechFoods.golden_apple); } // Notch Apple if (ConfigHandler.NotchApple && ConfigHandler.ApplePro == false) { GOLDEN_APPLE4 = new ShapedRecipe(new ItemStack(Items.GOLDEN_APPLE, 1, 1), "ggg", "gag", "ggg", 'g', "blockGold", 'a', new ItemStack(Items.APPLE)); } // Extra Food if (ConfigHandler.CookedApple) { GameRegistry.addSmelting(Items.APPLE, new ItemStack(TechFoods.cooked_apple), 1.0F); } if (ConfigHandler.CookedMushrooms) { GameRegistry.addSmelting(Blocks.RED_MUSHROOM, new ItemStack(TechFoods.cooked_mushroom_red), 0.5F); GameRegistry.addSmelting(Blocks.BROWN_MUSHROOM, new ItemStack(TechFoods.cooked_mushroom_brown), 0.5F); } if (ConfigHandler.CookedBacon) { RAW_BACON = new ShapelessRecipe(new ItemStack(TechFoods.raw_bacon, 4), Items.PORKCHOP); GameRegistry.addSmelting(TechFoods.raw_bacon, new ItemStack(TechFoods.cooked_bacon), 0.5F); } if (ConfigHandler.FriedEgg) { GameRegistry.addSmelting(Items.EGG, new ItemStack(TechFoods.fried_egg), 0.5F); } if (ConfigHandler.MonsterJerky) { GameRegistry.addSmelting(Items.ROTTEN_FLESH, new ItemStack(TechFoods.monster_jerky), 0.5F); } if (ConfigHandler.ToastedBread) { GameRegistry.addSmelting(Items.BREAD, new ItemStack(TechFoods.toasted_bread), 0.5F); } if (ConfigHandler.CookedMushrooms) { GameRegistry.addSmelting(Items.SUGAR, new ItemStack(TechFoods.little_candy), 0.5F); } if (ConfigHandler.Sandwiches) { BACON_EGGS = new ShapelessRecipe(new ItemStack(TechFoods.bacon_eggs), TechFoods.cooked_bacon, TechFoods.fried_egg, TechFoods.fried_egg); BACON_EGGS_SANDWICH = new ShapelessRecipe(new ItemStack(TechFoods.bacon_eggs_sandwhich), TechFoods.bread_slice, TechFoods.bacon_eggs, TechFoods.bread_slice); BREAD_SLICE = new ShapelessRecipe(new ItemStack(TechFoods.bread_slice, 10), Items.BREAD); BACON_SANDWICH = new ShapelessRecipe(new ItemStack(TechFoods.bacon_sandwhich), TechFoods.bread_slice, TechFoods.cooked_bacon, TechFoods.cooked_bacon, TechFoods.bread_slice); BEEF_SANDWICH = new ShapelessRecipe(new ItemStack(TechFoods.beef_sandwhich), TechFoods.bread_slice, Items.COOKED_BEEF, TechFoods.bread_slice); CHICKEN_SANDWICH = new ShapelessRecipe(new ItemStack(TechFoods.chicken_sandwhich), TechFoods.bread_slice, Items.COOKED_CHICKEN, TechFoods.bread_slice); RABBIT_SANDWICH = new ShapelessRecipe(new ItemStack(TechFoods.rabbit_sandwhich), TechFoods.bread_slice, Items.COOKED_RABBIT, TechFoods.bread_slice); } // Juicer (Can not be turned off) JUICER = new ShapedRecipe(new ItemStack(TechFoods.juicer), "l", "s", 's', "stone", 'l', Blocks.STONE_BUTTON); } }
true
e54e0a0f8b152bc1a0c2fdd05115ee6f4102b74e
Java
cureseven/2016programing3
/Test1-2/src/Sample1.java
UTF-8
753
3.390625
3
[]
no_license
//dDQi-otd8 class Person{ protected String name; Person(String n){ name = n; } void show(){ System.out.println(name); } } class Vegetarian extends Person{ Vegetarian(String n){ super(n); } void show(){ System.out.println(name+":Vegetarian"); } } class NonVegetarian extends Person{ private String main_dish; NonVegetarian(String n,String m){ super(n); main_dish = m; } void show(){ System.out.println(name+":"+main_dish); } } class Sample1 { public static void main(String[] args) { Person[] p; p = new Person[3]; p[0].NonVegetarian("Alice","fish"); p[1].Vegetarian("Gupta"); p[2].NonVegetarian("Tom","Meat"); p[0].show(); p[1].show(); p[2].show(); } }
true
1be9e56fd4b14c5d9613aabf9e85f3fe6b5c93d7
Java
designredevops/cursilho
/src/main/java/com/sicpa/thymeleaf/poc/aqualis/utils/Mail.java
UTF-8
1,265
2.453125
2
[]
no_license
package com.sicpa.thymeleaf.poc.aqualis.utils; import java.util.Map; /** * Object used to prepare the email * @author lrosa1 * */ public class Mail { private String from; private String to; private String subject; private String text; private String templatePath; private Map<String, Object> model; public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getTo() { return to; } public void setTo(String to) { this.to = to; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getTemplatePath() { return templatePath; } public void setTemplatePath(String templatePath) { this.templatePath = templatePath; } public Map<String, Object> getModel() { return model; } public void setModel(Map<String, Object> model) { this.model = model; } @Override public String toString() { return "Mail [from=" + from + ", to=" + to + ", subject=" + subject + ", templatePath=" + templatePath + "]"; } }
true
7df249d1ebc182fbd7053422b28cc1157c7e35fc
Java
Mr-XiaoLiang/LAnimation
/library/src/main/java/xiaoliang/library/listener/LProgressListener.java
UTF-8
277
2.15625
2
[]
no_license
package xiaoliang.library.listener; /** * Created by liuj on 2016/8/31. * 进度监视器 */ public interface LProgressListener { /** * 进度监视器 * @param p 进度 * @param index 动作序号 */ void onProgressChange(float p,int index); }
true
fa7fe9bf79484e4b99157467e8368e7f1980e9a2
Java
jtuburon/wikijob
/src/main/java/uniandes/bigdata/taller02/WikiMapper.java
UTF-8
16,228
2.546875
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 uniandes.bigdata.taller02; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringEscapeUtils; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class WikiMapper extends Mapper<LongWritable, Text, Text, Text> { private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); private final static Pattern DATE_PATTERN = Pattern.compile("(\\d{4})\\|(\\d{1,2})\\|(\\d{1,2})"); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String country = context.getConfiguration().get(FilteringInputParams.COUNTRY_FILTER_PARAM); String fromDate = context.getConfiguration().get(FilteringInputParams.FROM_DATE_FILTER_PARAM); String toDate = context.getConfiguration().get(FilteringInputParams.TO_DATE_FILTER_PARAM); String article = value.toString(); Date startDate = null; Date endDate = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { startDate = df.parse(fromDate); endDate = df.parse(toDate); } catch (ParseException ex) { ex.printStackTrace(); } Matcher infoboxMatcher = FilteringPatterns.INFO_BOX_PATTERN.matcher(article); if (infoboxMatcher.find()) { String infoBox = infoboxMatcher.group(1); Pattern p = Pattern.compile("(birth_date)|(birth_place)|(death_date)|(death_place)"); Matcher m = p.matcher(infoBox); boolean isAPerson = m.find(); boolean children_added = false; boolean spouses_added = false; ArrayList<String> spouses = new ArrayList<>();; ArrayList<String> children = new ArrayList<>();; if (isAPerson) { String[] lines = infoBox.split("\n"); HashMap<String, String> map= new HashMap<>(); for (int i = 0; i < lines.length; i++) { String line = lines[i]; System.out.println("Line: "+ line); String[] line_vec = line.split("=", 2); if (line_vec.length == 2) { String l_key = line_vec[0]; String l_val = line_vec[1]; if (l_key.contains(FilteringPatterns.BIRTH_PLACE_TOKEN)) { if (l_val.contains(country)) { map.put(FilteringPatterns.BIRTH_PLACE_KEY, country); } } if (l_key.contains(FilteringPatterns.DEATH_PLACE_TOKEN)) { if (l_val.contains(country)) { map.put(FilteringPatterns.DEATH_PLACE_KEY, country); } } if(l_key.contains(FilteringPatterns.BIRTH_DATE_TOKEN)){ String birthDateString = extractDateAsString(l_val); if (birthDateString != null) { Date birthDate = convertToDate(birthDateString); if (birthDate != null) { if (birthDate.after(startDate) && birthDate.before(endDate)) { map.put(FilteringPatterns.BIRTH_DATE_KEY, birthDateString); } } } } if(l_key.contains(FilteringPatterns.DEATH_DATE_TOKEN)){ String deathDateString = extractDateAsString(l_val); if (deathDateString != null) { Date deathDate = convertToDate(deathDateString); if (deathDate != null) { if (deathDate.after(startDate) && deathDate.before(endDate)) { map.put(FilteringPatterns.DEATH_DATE_KEY, deathDateString); } } } } if(l_key.contains(FilteringPatterns.SPOUSE_TOKEN)){ map.put(FilteringPatterns.SPOUSE_KEY, ""); Matcher personMatcher = FilteringPatterns.SPOUSE_PATTERN_PERSON.matcher(l_val); while (personMatcher.find()) { String s_person = personMatcher.group("personinfo"); s_person = s_person.split("\\|")[0]; spouses.add(s_person); } } if(l_key.contains(FilteringPatterns.CHILDREN_TOKEN)){ map.put(FilteringPatterns.CHILDREN_KEY, ""); Matcher personMatcher = FilteringPatterns.CHILDREN_PATTERN_PERSON.matcher(l_val); while (personMatcher.find()) { String s_person = personMatcher.group("personinfo"); s_person = s_person.split("\\|")[0]; children.add(s_person); } } } } String person = extractPersonName(article); if(map.containsKey(FilteringPatterns.BIRTH_PLACE_KEY)){ context.write(new Text(person), new Text(FilteringPatterns.BIRTH_PLACE_KEY+ ":" + country)); if(map.containsKey(FilteringPatterns.BIRTH_DATE_KEY)){ context.write(new Text(person), new Text(FilteringPatterns.BIRTH_DATE_KEY+ ":" + map.get(FilteringPatterns.BIRTH_DATE_KEY))); } if(map.containsKey(FilteringPatterns.SPOUSE_KEY) && spouses.size()>0){ for (int i = 0; i < spouses.size(); i++) { String spouse = spouses.get(i); context.write(new Text(person), new Text(FilteringPatterns.SPOUSE_KEY + ":" + spouse)); } spouses_added=true; } if(map.containsKey(FilteringPatterns.CHILDREN_KEY) && children.size()>0){ for (int i = 0; i < children.size(); i++) { String child = children.get(i); context.write(new Text(person), new Text(FilteringPatterns.CHILDREN_KEY + ":" + child)); } children_added=true; } } if(map.containsKey(FilteringPatterns.DEATH_PLACE_KEY)){ context.write(new Text(person), new Text(FilteringPatterns.DEATH_PLACE_KEY+ ":" + country)); if(map.containsKey(FilteringPatterns.DEATH_DATE_KEY)){ context.write(new Text(person), new Text(FilteringPatterns.DEATH_DATE_KEY+ ":" + map.get(FilteringPatterns.DEATH_DATE_KEY))); } if (!spouses_added) { if (map.containsKey(FilteringPatterns.SPOUSE_KEY) && spouses.size() > 0) { for (int i = 0; i < spouses.size(); i++) { String spouse = spouses.get(i); context.write(new Text(person), new Text(FilteringPatterns.SPOUSE_KEY + ":" + spouse)); } } } if (!children_added) { if (map.containsKey(FilteringPatterns.CHILDREN_KEY) && children.size() > 0) { for (int i = 0; i < children.size(); i++) { String child = children.get(i); context.write(new Text(person), new Text(FilteringPatterns.CHILDREN_KEY + ":" + child)); } } } } /* Matcher birthPlaceMatcher = FilteringPatterns.BIRTH_PLACE_PATTERN.matcher(infoBox); if (birthPlaceMatcher.find()) { String birthPlaceValue = birthPlaceMatcher.group(); if (birthPlaceValue.contains(country)) { String person = extractPersonName(article); context.write(new Text(person), new Text("born_in: " + country)); Matcher birthDateMatcher = FilteringPatterns.BIRTH_DATE_PATTERN.matcher(infoBox); if (birthDateMatcher.find()) { String birthDateValue = birthDateMatcher.group(birthDateMatcher.groupCount()); String birthDateString = extractDateAsString(birthDateValue); if (birthDateString != null) { Date birthDate = convertToDate(birthDateString); if (birthDate != null) { if (birthDate.after(startDate) && birthDate.before(endDate)) { context.write(new Text(person), new Text("born_on: " + birthDateString)); } } } } Matcher spouseMatcher = FilteringPatterns.SPOUSE_PATTERN.matcher(infoBox); if (spouseMatcher.find()) { String info = spouseMatcher.group("spouseinfo"); Matcher personMatcher = FilteringPatterns.SPOUSE_PATTERN_PERSON.matcher(info); while (personMatcher.find()) { String s_person = personMatcher.group("personinfo"); s_person = s_person.split("\\|")[0]; context.write(new Text(person), new Text("married_with:" + s_person)); spouses_added = true; } } Matcher childrenMatcher = FilteringPatterns.CHILDREN_PATTERN.matcher(infoBox); if (childrenMatcher.find()) { String info = childrenMatcher.group("childreninfo"); Matcher personMatcher = FilteringPatterns.CHILDREN_PATTERN_PERSON.matcher(info); while (personMatcher.find()) { String s_person = personMatcher.group("personinfo"); s_person = s_person.split("\\|")[0]; context.write(new Text(person), new Text("son_or_daughter:" + s_person)); children_added = true; } } } } Matcher deathPlaceMatcher = FilteringPatterns.DEATH_PLACE_PATTERN.matcher(infoBox); if (deathPlaceMatcher.find()) { String deathPlaceValue = deathPlaceMatcher.group(); if (deathPlaceValue.contains(country)) { String person = extractPersonName(article); context.write(new Text(person), new Text("died_in: " + country)); Matcher deathDateMatcher = FilteringPatterns.DEATH_DATE_PATTERN.matcher(infoBox); if (deathDateMatcher.find()) { String deathDateValue = deathDateMatcher.group(deathDateMatcher.groupCount()); String deathDateString = extractDateAsString(deathDateValue); if (deathDateString != null) { Date deathDate = convertToDate(deathDateString); if (deathDate != null) { if (deathDate.after(startDate) && deathDate.before(endDate)) { context.write(new Text(person), new Text("born_on: " + deathDateString)); } } } } if (!spouses_added) { Matcher spouseMatcher = FilteringPatterns.SPOUSE_PATTERN.matcher(infoBox); if (spouseMatcher.find()) { String info = spouseMatcher.group("spouseinfo"); Matcher personMatcher = FilteringPatterns.SPOUSE_PATTERN_PERSON.matcher(info); while (personMatcher.find()) { String s_person = personMatcher.group("personinfo"); s_person = s_person.split("\\|")[0]; context.write(new Text(person), new Text("married_with:" + s_person)); spouses_added = true; } } } if (!children_added) { Matcher childrenMatcher = FilteringPatterns.CHILDREN_PATTERN.matcher(infoBox); if (childrenMatcher.find()) { String info = childrenMatcher.group("childreninfo"); Matcher personMatcher = FilteringPatterns.CHILDREN_PATTERN_PERSON.matcher(info); while (personMatcher.find()) { String s_person = personMatcher.group("personinfo"); s_person = s_person.split("\\|")[0]; context.write(new Text(person), new Text("son_or_daughter:" + s_person)); children_added = true; } } } } } */ } } } private String extractPersonName(String article) { Pattern p = Pattern.compile("<title>(.*)</title>"); Matcher m = p.matcher(article); if (m.find()) { String person_name = m.group(1); return person_name; } else { return null; } } private String extractDateAsString(String line) { Matcher m = DATE_PATTERN.matcher(line); if (m.find()) { String year = m.group(1); String month = m.group(2); String day = m.group(3); String dateVal = year + "-" + month + "-" + day; return dateVal; } return null; } private Date convertToDate(String dateString) { Date date; try { date = DATE_FORMAT.parse(dateString); return date; } catch (ParseException ex) { ex.printStackTrace(); } return null; } }
true
b4ff0014d9a90cca7fda8334583b43e18f887ab1
Java
GrigUP/test-project
/test_project/src/main/java/ru/grigorishin/database/impl/OrdersDAO.java
UTF-8
8,466
2.890625
3
[]
no_license
package ru.grigorishin.database.impl; import ru.grigorishin.database.AbstractDAO; import ru.grigorishin.entity.Order; import ru.grigorishin.exceprions.UncorrectTypeRuntimeException; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * DAO взаимодействия с таблицей "orders" из БД, определенной * в абстрактном родительском классе. */ public class OrdersDAO extends AbstractDAO { private final String tableName = "orders"; private final String joinClientsTableName = "clients"; private final String joinCatalogTableName = "products"; /** * Метод чтения из БД, определенной в абстрактном родительском * классе, строки с соответвующим значением id. * @param id * @return * Метод возвращает единственный Order объкет, если такой существует, * либо null. */ @Override public Order getById(int id) { Order order = null; String query = String.format("SELECT \n" + " %1$s.id,\n" + " %1$s.order_date,\n" + " %1$s.client_id,\n" + " %2$s.last_name,\n" + " %2$s.first_name,\n" + " %2$s.middle_name,\n" + " %1$s.product_id,\n" + " %3$s.product_name,\n" + " %3$s.product_price,\n" + " %1$s.quantity,\n" + " %3$s.product_price*%1$s.quantity as 'total price'\n" + " FROM\n" + " %1$s\n" + " JOIN\n" + " %2$s ON %1$s.client_id = %2$s.id\n" + " JOIN \n" + " %3$s ON %1$s.product_id = %3$s.id\n" + " WHERE orders.id=%4$d;", tableName, joinClientsTableName, joinCatalogTableName, id); try(Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query); ResultSet resultSet = statement.executeQuery()) { if(resultSet.next()) { order = builtOrderFromResultSet(resultSet); } } catch (SQLException ex) { ex.printStackTrace(); } return order; } /** * Метод чтения из БД, определенной в абстрактном родительском * классе, всех строк таблицы order с присоединенными таблицами client и products. * @return * Метод возвращает список Order объектов. Каждый объект списка соответсвует * строке комбинированной таблицы. */ @Override public List<Order> readAll() { List<Order> orderList = new ArrayList<>(); String query = String.format("SELECT \n" + " %1$s.id,\n" + " %1$s.order_date,\n" + " %1$s.client_id,\n" + " %2$s.last_name,\n" + " %2$s.first_name,\n" + " %2$s.middle_name,\n" + " %1$s.product_id,\n" + " %3$s.product_name,\n" + " %3$s.product_price,\n" + " %1$s.quantity,\n" + " %3$s.product_price*%1$s.quantity as 'total price'\n" + " FROM\n" + " %1$s\n" + " JOIN\n" + " %2$s ON %1$s.client_id = %2$s.id\n" + " JOIN \n" + " %3$s ON %1$s.product_id = %3$s.id\n" + " ORDER BY order_date;", tableName, joinClientsTableName, joinCatalogTableName); try(Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query); ResultSet resultSet = statement.executeQuery()) { while(resultSet.next()) { Order newOrder = builtOrderFromResultSet(resultSet); orderList.add(newOrder); } } catch (SQLException ex) { ex.printStackTrace(); } return orderList; } /** * Метод создания записи в БД объекта класса Order, используя * явное приведение типов. * @param obj * В случае, если объект obj не является объектом класса Product, * то выбрасывется unchecked UncorrectTypeExceprion исключение. */ @Override public void create(Object obj) { if ( !(obj instanceof Order) ) { throw new UncorrectTypeRuntimeException(); } Order order = (Order) obj; String query = String.format("INSERT INTO %s VALUES(NULL, '%s', %d, %d, %d);", tableName, order.getOrder_date(), order.getClient_id(), order.getProduct_id(), order.getQuantity()); try(Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { statement.execute(); } catch (SQLException ex) { ex.printStackTrace(); } } /** * Метод удаления записи, соответсвубщей параметру id, из БД. * @param id */ public void deleteById(int id) { String query = String.format("DELETE FROM %s WHERE id=%d;", tableName, id); try(Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { statement.execute(); } catch (SQLException ex) { ex.printStackTrace(); } } /** * Метод обновления строки, соответсвующей параметру id, в БД * значениями полей объекта класса Order, используя явное приведение * типов * @param obj * В случае, если объект obj не является объектом класса Order, * то выбрасывется unchecked UncorrectTypeExceprion исключение. */ @Override public void update(Object obj) { if ( !(obj instanceof Order) ) { throw new UncorrectTypeRuntimeException(); } Order order = (Order) obj; String query = String.format("UPDATE %s SET order_date='%s', client_id='%d', product_id='%d', quantity='%d' WHERE id='%d'", tableName, order.getOrder_date(), order.getClient_id(), order.getProduct_id(), order.getQuantity(), order.getId()); try(Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { statement.execute(); } catch (SQLException ex) { ex.printStackTrace(); } } /** * Метод сборки объекта класса Order из элемента resultSet * @param resultSet * @return * Метод возвращает объект класса Order, соответсвующий строке в таблице БД. * @throws SQLException * В случае отсутсвия запрашиваемого к эллементу resultSet ключа * выбрасивается checked SQLExceprion исключение. */ private Order builtOrderFromResultSet(ResultSet resultSet) throws SQLException { Order order = new Order(); order.setId(resultSet.getInt("id")); order.setOrder_date(resultSet.getTimestamp("order_date")); order.setClient_id(resultSet.getInt("client_id")); order.setLast_name(resultSet.getString("last_name")); order.setFirst_name(resultSet.getString("first_name")); order.setMiddle_name(resultSet.getString("middle_name")); order.setProduct_id(resultSet.getInt("product_id")); order.setProduct_name(resultSet.getString("product_name")); order.setProduct_price(resultSet.getBigDecimal("product_price")); order.setQuantity(resultSet.getInt("quantity")); return order; } }
true
b8d9d99a1235afd813f0e7c3ca0207ca409e0ac6
Java
shaileshitech/workspace
/HackerEarth/src/ChocoInversion.java
UTF-8
2,341
3.265625
3
[]
no_license
import java.io.BufferedReader; import java.io.InputStreamReader; public class ChocoInversion { static void mergesort(int array[], int pos[], int result[], int start, int end) { if (start >= end) { return; } int mid = start + (end - start) / 2; mergesort(array, pos, result, start, mid); mergesort(array, pos, result, mid + 1, end); merge(array, pos, result, start, mid, end); } static void merge(int array[], int pos[], int result[], int start, int mid, int end) { int temp[]= new int[array.length]; for (int i = start; i <= end; ++i) { temp[i] = pos[i]; } int cur = start; int leftcur = start; int rightcur = mid + 1; while (leftcur <= mid && rightcur <= end) { if (array[temp[leftcur]] <= array[temp[rightcur]]) { pos[cur] = temp[leftcur]; result[pos[cur]] += rightcur - mid - 1; ++leftcur; ++cur; } else { pos[cur] = temp[rightcur]; ++cur; ++rightcur; } } while (leftcur <= mid) { pos[cur] = temp[leftcur]; result[pos[cur]] += end - mid; ++cur; ++leftcur; } while (rightcur <= end) { pos[cur] = temp[rightcur]; ++cur; ++rightcur; } } public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int N = Integer.parseInt(line); int[] a = new int[N]; String line2 = br.readLine(); String array[]= line2.split(" "); int pos[] = new int[a.length]; int result[] = new int[a.length]; for (int i = 0; i < N; i++) { a[i]= Integer.parseInt(array[i]); pos[i] = i; } mergesort(a,pos,result,0, N-1); int max = 0; for(int i=0;i<result.length;i++){ if(max<result[i]){ max= result[i]; } } System.out.println(max); } }
true
7cae85308c07584d31b5cd0a62cfcb599d72333e
Java
thaidem/patterns
/src/main/java/Prototype.java
UTF-8
2,911
3.640625
4
[]
no_license
//Прототип, (англ. Prototype) — порождающий шаблон проектирования. //Назначение: Задаёт виды создаваемых объектов с помощью экземпляра-прототипа и создаёт // новые объекты путём копирования этого прототипа. Он позволяет уйти от реализации и позволяет // следовать принципу «программирование через интерфейсы». В качестве возвращающего типа указывается // интерфейс/абстрактный класс на вершине иерархии, а классы-наследники могут подставить туда наследника, // реализующего этот тип. //Проще говоря, это паттерн создания объекта через клонирование другого объекта вместо создания через конструктор. class MainPrototype { public static void main(String[] args) throws CloneNotSupportedException { Address address = new Address("Lenina", 43); PersonProto person = new PersonProto("Mike", 25, address); // PersonProto person2 = person.clone(); PersonProto person2 = new PersonProto(person); System.out.println(person != person2); System.out.println(person.name == person2.name); System.out.println(person.address.street == person2.address.street); person.name = "Max"; System.out.println(person2.name); person.address.street = "New"; System.out.println(person2.address.street); } } class Address implements Cloneable { String street; int number; public Address(String street, int number) { this.street = street; this.number = number; } public Address(Address address) { this.street = address.street; this.number = address.number; } @Override protected Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } } class PersonProto implements Cloneable { String name; int age; final Address address; public PersonProto(String name, int age, Address address) { System.out.println("constructor1"); this.name = name; this.age = age; this.address = address; } public PersonProto(PersonProto person) { System.out.println("constructor2"); this.name = person.name; this.age = person.age; this.address = new Address(person.address); } // @Override // protected PersonProto clone() throws CloneNotSupportedException { // PersonProto person = (PersonProto) super.clone(); // person.address = this.address.clone(); // return person; // } // public PersonProto copy(PersonProto person) { // return new PersonProto(person.name, person.age); // } }
true
03eaae8fb093a018e44bc641c5fca6d2451c3d3b
Java
fcracker79/daschner
/src/main/java/io/mirko/boundary/UserNotificationsDecoder.java
UTF-8
1,568
2.40625
2
[ "MIT" ]
permissive
package io.mirko.boundary; import javax.websocket.*; import java.io.*; import java.nio.ByteBuffer; import java.util.logging.Logger; public class UserNotificationsDecoder implements Encoder.Binary<UserNotificationMessage>, Decoder.Binary<UserNotificationMessage> { @Override public UserNotificationMessage decode(ByteBuffer bytes) throws DecodeException { Logger.getLogger(getClass().getName()).info("Decoding....."); final ByteArrayInputStream is = new ByteArrayInputStream(bytes.array()); try (ObjectInputStream oi = new ObjectInputStream(is)) { return (UserNotificationMessage) oi.readObject(); } catch(Exception e) { Logger.getLogger(getClass().getName()).info("Could not read bytes"); throw new DecodeException(bytes, "Could not read bytes", e); } } @Override public void init(EndpointConfig config) { // do nothing } @Override public ByteBuffer encode(UserNotificationMessage object) throws EncodeException { final ByteArrayOutputStream ob = new ByteArrayOutputStream(); try (ObjectOutputStream o = new ObjectOutputStream(ob)) { o.writeObject(object); o.flush(); } catch(IOException e) { throw new EncodeException(object, "Could not write bytes", e); } return ByteBuffer.wrap(ob.toByteArray()); } @Override public boolean willDecode(ByteBuffer bytes) { return true; } @Override public void destroy() { // do nothing } }
true
570f98c5c47c2d035893d303ecfb6ec6ffc30a9f
Java
diegolsouzaa/wiremock
/tutoriais/4-wiremock-com-junit/address-register-api/src/test/java/br/com/balatech/addressregister/service/AddressServiceTest.java
UTF-8
2,596
1.984375
2
[]
no_license
package br.com.balatech.addressregister.service; import br.com.balatech.addressregister.bean.ZipCodeResponse; import br.com.balatech.addressregister.config.CEPConfig; import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.http.HttpStatus; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("mock") public class AddressServiceTest { private AddressService addressService; @Autowired private CEPConfig cepConfig; @Rule public WireMockRule wireMockRule = new WireMockRule(8082); @Before public void setUp() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); addressService = new AddressService(restTemplate, cepConfig); } @Test public void listAddressByZipCodeWithSuccess() { ZipCodeResponse mockResponse = new ZipCodeResponse(); mockResponse.setAddress("Rua X"); mockResponse.setCity("Sao Paulo"); mockResponse.setComplement("xxx"); mockResponse.setNeighborhood("Novo"); mockResponse.setZipCode("12345678"); mockResponse.setState("SP"); stubFor(get(urlPathEqualTo("/ws/12345678/json")).willReturn(ResponseDefinitionBuilder.okForJson(mockResponse))); ZipCodeResponse zipCodeResponse = addressService.getAddressByZipCode("12345678"); verify(1, getRequestedFor(urlPathEqualTo("/ws/12345678/json"))); Assert.assertNotNull(zipCodeResponse); Assert.assertFalse(zipCodeResponse.isObjectEmpty()); } @Test public void listAddressByZipCodeWithFail() { stubFor(get(urlPathEqualTo("/ws/07010100/json")).willReturn(aResponse().withStatus(HttpStatus.BAD_GATEWAY.value()))); ZipCodeResponse zipCodeResponse = addressService.getAddressByZipCode("07010100"); verify(1, getRequestedFor(urlPathEqualTo("/ws/07010100/json"))); Assert.assertNotNull(zipCodeResponse); } }
true
b73b2d19989e5d656adcf31f5b23c4b1289452f9
Java
Edvvin/StreamingSoftware
/SubServer/src/inner/MovieElf.java
UTF-8
1,242
2.484375
2
[ "MIT" ]
permissive
package inner; import java.rmi.RemoteException; import java.util.ArrayList; import my.rmi.*; import server.Main; public class MovieElf extends Thread { public MovieElf() { super(); } @Override public void run() { try { while(!interrupted()) { ArrayList<Order> orders; synchronized(this) { while(true) { try{ orders = Main.ss.csrmi.getOrders(Main.ss.port); if(orders.size() > 0) break; else wait(); } catch(NotSycnhedException | RemoteException e) { Main.ss.reconnect(); wait(); } } } ArrayList<Order> success = new ArrayList<>(); for(Order o: orders) { boolean reply = Main.ss.carryOut(o); if(reply) { success.add(o); if(!Main.ss.movies.containsKey(o.getMovie())) Main.ss.movies.put(o.getMovie(), new Movie(o.getMovie(), o.getFileSize())); Main.ss.movies.get(o.getMovie()).addChunk(o.getIndex()); } } try { Main.ss.csrmi.registerOrders(Main.ss.port, success); } catch(NotSycnhedException | RemoteException e) { Main.ss.reconnect(); } } } catch(InterruptedException e) { } } public synchronized void newMovie() { notify(); } }
true
39df47864261988b2fe166454061965cb50cc01d
Java
harshilraja/SpringBoot
/SpringBootQueryDsl/src/main/java/com/tistory/heowc/repository/GradeRepositoryCustom.java
UTF-8
363
1.914063
2
[]
no_license
package com.tistory.heowc.repository; import java.util.List; import com.tistory.heowc.domain.Grade; public interface GradeRepositoryCustom { public List<Grade> findGradeJoinNameOfStudent(String name); public List<Grade> findGradeSubQueryNameOfStudent(String name); public Long deleteByNum(Integer num); public Long setFixedNameByNum(Grade grade); }
true
cb42373d0c165393b74049e7f2aebda68b57c600
Java
mrpkdeveloper/crux-course-java-
/src/data_structure_question/stock_span.java
UTF-8
807
3.34375
3
[]
no_license
package data_structure_question; import data_Structures.dynamic_Stack; public class stock_span { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub int[] arr = { 50, 30, 35, 40, 38, 35 }; int[] ans = stock(arr); for (int i = 1; i < ans.length; i++) { System.out.print(ans[i]+" "); } System.out.println("END"); } public static int[] stock(int[] arr) throws Exception { dynamic_Stack stack = new dynamic_Stack(); int[] ans = new int[arr.length]; ans[0] = 1; stack.push(0); for (int i = 1; i < arr.length; i++) { while (!stack.isEmpty() && arr[stack.top()] < arr[i]) { stack.pop(); } if (stack.isEmpty()) { ans[i] = i+1 ; } else { ans[i] = i - stack.top(); } stack.push(i); } return ans; } }
true
cdabb9237c8b76a6a97092deb4608034dffe00b8
Java
hexq/test4j
/test4j.spec/src/test/testng/org/test4j/spec/scenario/step/SpecMethodTest.java
UTF-8
2,883
2.53125
3
[]
no_license
package org.test4j.spec.scenario.step; import java.lang.reflect.Type; import java.util.Arrays; import java.util.List; import java.util.Map; import org.test4j.spec.annotations.Given; import org.test4j.spec.annotations.Named; import org.test4j.spec.annotations.Then; import org.test4j.spec.annotations.When; import org.test4j.spec.inner.ISpecMethod; import org.test4j.spec.inner.ISpecMethod.SpecMethodID; import org.test4j.spec.scenario.step.SpecMethod; import org.test4j.testng.Test4J; import org.testng.annotations.Test; @SuppressWarnings({ "unchecked" }) public class SpecMethodTest extends Test4J { @Test(groups = "spec") public void testFindMethods_Normal() { Map<SpecMethodID, ISpecMethod> map = SpecMethod.findMethods(StepMethodDemo.class); want.map(map).sizeEq(5).hasKeys(new SpecMethodID("given1", 0), // <br> new SpecMethodID("given2", 2),// <br> new SpecMethodID("given3", 3),// <br> new SpecMethodID("when", 2),// <br> new SpecMethodID("then", 2)// <br> ); } @Test(groups = "spec") public void testFindMethods_HasSameMethodID() { try { SpecMethod.findMethods(SameMethodID.class); want.fail(); } catch (RuntimeException e) { String msg = e.getMessage(); want.string(msg).contains("named given2 and with 2 arguments"); } } @Test(groups = "spec") public void testGetParaAnnotationNames() throws Exception { SpecMethod specMethod = reflector.newInstance(SpecMethod.class); List<String> names = specMethod.getParaAnnotationNames(SameMethodID.class.getMethod("given2", String.class, int.class)); want.list(names).isEqualTo(Arrays.asList("arg1", "arg2")); } @Test(groups = "spec") public void testGetParaTypes() throws Exception { SpecMethod specMethod = reflector.newInstance(SpecMethod.class); List<Type> types = specMethod.getParaTypes(SameMethodID.class.getMethod("given2", String.class, int.class)); want.list(types).isEqualTo(Arrays.asList(String.class, int.class)); } } class SameMethodID { @Given public void given2(@Named("arg1") String arg1, @Named("arg2") Boolean arg2) { } @Given public void given2(@Named("arg1") String arg1, @Named("arg2") int arg2) { } } class StepMethodDemo { @Given public void given1() { } @Given public void given2(@Named("arg1") String arg1, @Named("arg2") Boolean arg2) { } @Given public void given3(@Named("arg1") String arg1, @Named("arg2") int arg2, @Named("arg3") Object[] arg3) { } @When public void when(@Named("arg1") String arg1, @Named("arg2") Boolean arg2) { } @Then public void then(@Named("arg1") String arg1, @Named("arg2") Boolean arg2) { } }
true
1467b7266be97580f81136db64d87263320a8533
Java
darktw1nk/microservices-user-service
/src/main/java/com/winter/resources/UserResource.java
UTF-8
4,766
2.234375
2
[]
no_license
package com.winter.resources; import com.winter.model.*; import com.winter.network.request.LoginRequest; import com.winter.network.request.RegisterRequest; import com.winter.network.response.LoggedInResponse; import com.winter.service.CompanyService; import com.winter.service.UserService; import io.smallrye.reactive.messaging.annotations.Channel; import io.smallrye.reactive.messaging.annotations.Emitter; import org.checkerframework.checker.nullness.Opt; import org.eclipse.microprofile.metrics.MetricUnits; import org.eclipse.microprofile.metrics.annotation.Counted; import org.eclipse.microprofile.metrics.annotation.Timed; import org.eclipse.microprofile.rest.client.inject.RestClient; import org.jboss.logging.Logger; import org.jboss.resteasy.annotations.jaxrs.PathParam; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Base64; import java.util.List; import java.util.Optional; @Path("/api/user") public class UserResource { private static final Logger logger = Logger.getLogger(UserResource.class); @Inject UserService userService; @Inject @Channel("users-topic") Emitter<User> userEmitter; @Counted(name = "countGetUsers", description = "Counts how many times the getUsers method has been invoked") @Timed(name = "timeGetUsers", description = "Times how long it takes to invoke getUsers method", unit = MetricUnits.MILLISECONDS) @GET @Produces(MediaType.APPLICATION_JSON) public Response getAll() { logger.debug("get all"); List<User> users = userService.listAll(); return Response.ok(users).build(); } @Counted(name = "countGetUser", description = "Counts how many times the getUser method has been invoked") @Timed(name = "timeGetUser", description = "Times how long it takes to invoke getUser method", unit = MetricUnits.MILLISECONDS) @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getUser(@PathParam("id") Long id) { return userService.findById(id) .map(user -> Response.ok(user).build()) .orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); } @Counted(name = "countFindUserByHash", description = "Counts how many times the findUserByHash method has been invoked") @Timed(name = "timeFindUserByHash", description = "Times how long it takes to invoke timeFindUserByHash method", unit = MetricUnits.MILLISECONDS) @GET @Path("/hash/{id}") @Produces(MediaType.APPLICATION_JSON) public Response findUserByHash(@PathParam("id") String id) { byte[] decodedBytes = Base64.getDecoder().decode(id); String login = new String(decodedBytes); return userService.findByLogin(login) .map(user -> Response.ok(user).build()) .orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); } @Counted(name = "countLogin", description = "Counts how many times the getUser method has been invoked") @Timed(name = "timeLogin", description = "Times how long it takes to invoke getUser method", unit = MetricUnits.MILLISECONDS) @POST @Path("/login") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response login(LoginRequest request) { logger.error("logging as"); logger.error(request); Optional<User> dbUser = userService.findByLogin(request.getLogin()); if (dbUser.isPresent()) { if (request.getPassword().equals(dbUser.get().getPassword())) { LoggedInResponse response = new LoggedInResponse(); response.setStatus("ok"); response.setToken(Base64.getEncoder().encodeToString(dbUser.get().getLogin().getBytes())); return Response.ok(response).build(); } else { return Response.status(403).build(); } } else { return Response.status(Response.Status.BAD_REQUEST).build(); } } @Counted(name = "countPostRegisterUser", description = "Counts how many times the registerUser method has been invoked") @Timed(name = "timePostRegisterUser", description = "Times how long it takes to invoke registerUser method", unit = MetricUnits.MILLISECONDS) @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response registerUser(RegisterRequest request) { return userService.registerUser(request.getLogin(),request.getPassword(),request.getCompanyName()) .map(user -> Response.ok(user).build()) .orElseGet(() -> Response.status(Response.Status.NOT_FOUND).build()); } }
true
56de9558e3de4bd8149e07b6d9315ba53122eff5
Java
klunge/KlungeFramework
/samples/3-advanced/order-service/src/main/java/com/kloia/sample/model/Orders.java
UTF-8
840
1.984375
2
[ "Apache-2.0" ]
permissive
package com.kloia.sample.model; import com.kloia.eventapis.spring.model.JpaEntity; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.EnumType; import javax.persistence.Enumerated; /** * Created by zeldalozdemir on 17/02/2017. */ @Getter @Setter @AllArgsConstructor @NoArgsConstructor @javax.persistence.Entity(name = "ORDERS") public class Orders extends JpaEntity { @Enumerated(EnumType.STRING) private OrderState state; private long price; private String stockId; private int reservedStockVersion; private int orderAmount; private String paymentAddress; private float amount; private String cardInformation; private String paymentId; private String address; private String description; }
true
a3274d5ef5e0138074130ccbec1be973e0d25154
Java
picatrix1899/barghos
/barghos-tuple-api/src/test/java/org/barghos/tuple/api/test/t2/Tup2strRTest.java
UTF-8
2,349
2.796875
3
[ "MIT" ]
permissive
package org.barghos.tuple.api.test.t2; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; import org.barghos.tuple.api.t2.Tup2strR; import org.barghos.tuple.api.tn.TupstrR; /** * This class provides component tests for the interface {@link Tup2strR}. * * @author picatrix1899 */ class Tup2strRTest { /** * This test ensures, that the interface extends the interface * {@link TupstrR}. */ @Test void inheritance_TupRTest() { assertTrue(TupstrR.class.isAssignableFrom(Tup2strR.class)); } /** * this test ensures, that the function {@link Tup2strR#getDimensions()} * always returns 2 and does not make any calls. */ @Test void getDimensionsTest() { Tup2strR t = mock(Tup2strR.class); when(t.getDimensions()).thenCallRealMethod(); assertEquals(2, t.getDimensions()); verify(t).getDimensions(); verifyNoMoreInteractions(t); } /** * This test ensures, that the function {@link Tup2strR#getByIndex(int)} * returns the x component for the index 0. */ @Test void getByIndex_XTest() { Tup2strR t = mock(Tup2strR.class); when(t.getByIndex(0)).thenCallRealMethod(); when(t.getX()).thenReturn("a"); assertEquals("a", t.getByIndex(0)); verify(t).getByIndex(0); verify(t).getX(); verifyNoMoreInteractions(t); } /** * This test ensures, that the function {@link Tup2strR#getByIndex(int)} * returns the y component for the index 1. */ @Test void getByIndex_YTest() { Tup2strR t = mock(Tup2strR.class); when(t.getByIndex(1)).thenCallRealMethod(); when(t.getY()).thenReturn("a"); assertEquals("a", t.getByIndex(1)); verify(t).getByIndex(1); verify(t).getY(); verifyNoMoreInteractions(t); } /** * This test ensures, that the function {@link Tup2strR#toArray(String[])} * returns the given array with the components in the right order. */ @Test void toArrayWithExtractionParamTest() { Tup2strR t = mock(Tup2strR.class); String[] array = new String[2]; when(t.toArray(array)).thenCallRealMethod(); when(t.getX()).thenReturn("a"); when(t.getY()).thenReturn("b"); assertSame(array, t.toArray(array)); assertArrayEquals(new String[] {"a", "b"}, array); verify(t).toArray(array); verify(t).getX(); verify(t).getY(); verifyNoMoreInteractions(t); } }
true
f55e5812fa19dd4ba09a322f7e0140ce57115c5b
Java
PSNAppz/CTFTime-Android
/app/src/main/java/com/neonsec/ctftime/ctf_timemobile/CardsAdapter.java
UTF-8
3,077
2.296875
2
[]
no_license
package com.neonsec.ctftime.ctf_timemobile; /** * Created by psn on 3/4/18. */ import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author Alhaytham Alfeel on 10/10/2016. */ public class CardsAdapter extends ArrayAdapter<CardModel>{ private CardModel model; public CardsAdapter(Context context) { super(context, R.layout.card_item); } @NonNull @Override public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.card_item, parent, false); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } model = getItem(position); holder.title.setText(model.getTitle()); holder.type.setText(model.getType()); holder.url.setText(model.getUrl()); DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis(); String jtdate = model.getStart(); String dt = parser2.parseDateTime(jtdate).toString(); SimpleDateFormat startDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX" ); Date date = null; try { date = startDate.parse(dt); } catch (ParseException e) { e.printStackTrace(); } holder.start.setText(date.toString()); try { Picasso.get().load(model.getImageURL()).into(holder.imageView); }catch (Exception e){ holder.imageView.setImageResource(R.drawable.ic_future); } if(model.getOnsite()){ holder.onsite.setTextColor(Color.parseColor("#6200ea")); holder.onsite.setText("Onsite"); }else{ holder.onsite.setTextColor(Color.parseColor("#00c853")); holder.onsite.setText("Online"); } return convertView; } class ViewHolder { ImageView imageView; TextView title,type,url,onsite,start; ViewHolder(View view) { imageView = (ImageView) view.findViewById(R.id.image); title = (TextView) view.findViewById(R.id.title); type = (TextView) view.findViewById(R.id.type); onsite = (TextView) view.findViewById(R.id.onsite); url = (TextView) view.findViewById(R.id.url); start = (TextView) view.findViewById(R.id.start); } } }
true
f0d548e3a1a3f8bde40d6a2930721aeb8f5503f1
Java
RubinLab/epad-ws
/src/main/java/edu/stanford/epad/epadws/service/EpadProjectOperations.java
UTF-8
40,097
2.25
2
[]
no_license
/******************************************************************************* * Copyright (c) 2015 The Board of Trustees of the Leland Stanford Junior University * BY CLICKING ON "ACCEPT," DOWNLOADING, OR OTHERWISE USING EPAD, YOU AGREE TO THE FOLLOWING TERMS AND CONDITIONS: * STANFORD ACADEMIC SOFTWARE SOURCE CODE LICENSE FOR * "ePAD Annotation Platform for Radiology Images" * * This Agreement covers contributions to and downloads from the ePAD project ("ePAD") maintained by The Board of Trustees * of the Leland Stanford Junior University ("Stanford"). * * * Part A applies to downloads of ePAD source code and/or data from ePAD. * * * Part B applies to contributions of software and/or data to ePAD (including making revisions of or additions to code * and/or data already in ePAD), which may include source or object code. * * Your download, copying, modifying, displaying, distributing or use of any ePAD software and/or data from ePAD * (collectively, the "Software") is subject to Part A. Your contribution of software and/or data to ePAD (including any * that occurred prior to the first publication of this Agreement) is a "Contribution" subject to Part B. Both Parts A and * B shall be governed by and construed in accordance with the laws of the State of California without regard to principles * of conflicts of law. Any legal action involving this Agreement or the Research Program will be adjudicated in the State * of California. This Agreement shall supersede and replace any license terms that you may have agreed to previously with * respect to ePAD. * * PART A. DOWNLOADING AGREEMENT - LICENSE FROM STANFORD WITH RIGHT TO SUBLICENSE ("SOFTWARE LICENSE"). * 1. As used in this Software License, "you" means the individual downloading and/or using, reproducing, modifying, * displaying and/or distributing Software and the institution or entity which employs or is otherwise affiliated with you. * Stanford hereby grants you, with right to sublicense, with respect to Stanford's rights in the Software, a * royalty-free, non-exclusive license to use, reproduce, make derivative works of, display and distribute the Software, * provided that: (a) you adhere to all of the terms and conditions of this Software License; (b) in connection with any * copy, distribution of, or sublicense of all or any portion of the Software, the terms and conditions in this Software * License shall appear in and shall apply to such copy and such sublicense, including without limitation all source and * executable forms and on any user documentation, prefaced with the following words: "All or portions of this licensed * product have been obtained under license from The Board of Trustees of the Leland Stanford Junior University. and are * subject to the following terms and conditions" AND any user interface to the Software or the "About" information display * in the Software will display the following: "Powered by ePAD http://epad.stanford.edu;" (c) you preserve and maintain * all applicable attributions, copyright notices and licenses included in or applicable to the Software; (d) modified * versions of the Software must be clearly identified and marked as such, and must not be misrepresented as being the * original Software; and (e) you consider making, but are under no obligation to make, the source code of any of your * modifications to the Software freely available to others on an open source basis. * * 2. The license granted in this Software License includes without limitation the right to (i) incorporate the Software * into your proprietary programs (subject to any restrictions applicable to such programs), (ii) add your own copyright * statement to your modifications of the Software, and (iii) provide additional or different license terms and conditions * in your sublicenses of modifications of the Software; provided that in each case your use, reproduction or distribution * of such modifications otherwise complies with the conditions stated in this Software License. * 3. This Software License does not grant any rights with respect to third party software, except those rights that * Stanford has been authorized by a third party to grant to you, and accordingly you are solely responsible for (i) * obtaining any permissions from third parties that you need to use, reproduce, make derivative works of, display and * distribute the Software, and (ii) informing your sublicensees, including without limitation your end-users, of their * obligations to secure any such required permissions. * 4. You agree that you will use the Software in compliance with all applicable laws, policies and regulations including, * but not limited to, those applicable to Personal Health Information ("PHI") and subject to the Institutional Review * Board requirements of the your institution, if applicable. Licensee acknowledges and agrees that the Software is not * FDA-approved, is intended only for research, and may not be used for clinical treatment purposes. Any commercialization * of the Software is at the sole risk of you and the party or parties engaged in such commercialization. You further agree * to use, reproduce, make derivative works of, display and distribute the Software in compliance with all applicable * governmental laws, regulations and orders, including without limitation those relating to export and import control. * 5. You or your institution, as applicable, will indemnify, hold harmless, and defend Stanford against any third party * claim of any kind made against Stanford arising out of or related to the exercise of any rights granted under this * Agreement, the provision of Software, or the breach of this Agreement. Stanford provides the Software AS IS and WITH ALL * FAULTS. Stanford makes no representations and extends no warranties of any kind, either express or implied. Among * other things, Stanford disclaims any express or implied warranty in the Software: * (a) of merchantability, of fitness for a particular purpose, * (b) of non-infringement or * (c) arising out of any course of dealing. * * Title and copyright to the Program and any associated documentation shall at all times remain with Stanford, and * Licensee agrees to preserve same. Stanford reserves the right to license the Program at any time for a fee. * 6. None of the names, logos or trademarks of Stanford or any of Stanford's affiliates or any of the Contributors, or any * funding agency, may be used to endorse or promote products produced in whole or in part by operation of the Software or * derived from or based on the Software without specific prior written permission from the applicable party. * 7. Any use, reproduction or distribution of the Software which is not in accordance with this Software License shall * automatically revoke all rights granted to you under this Software License and render Paragraphs 1 and 2 of this * Software License null and void. * 8. This Software License does not grant any rights in or to any intellectual property owned by Stanford or any * Contributor except those rights expressly granted hereunder. * * PART B. CONTRIBUTION AGREEMENT - LICENSE TO STANFORD WITH RIGHT TO SUBLICENSE ("CONTRIBUTION AGREEMENT"). * 1. As used in this Contribution Agreement, "you" means an individual providing a Contribution to ePAD and the * institution or entity which employs or is otherwise affiliated with you. * 2. This Contribution Agreement applies to all Contributions made to ePAD at any time. By making a Contribution you * represent that: (i) you are legally authorized and entitled by ownership or license to make such Contribution and to * grant all licenses granted in this Contribution Agreement with respect to such Contribution; (ii) if your Contribution * includes any patient data, all such data is de-identified in accordance with U.S. confidentiality and security laws and * requirements, including but not limited to the Health Insurance Portability and Accountability Act (HIPAA) and its * regulations, and your disclosure of such data for the purposes contemplated by this Agreement is properly authorized and * in compliance with all applicable laws and regulations; and (iii) you have preserved in the Contribution all applicable * attributions, copyright notices and licenses for any third party software or data included in the Contribution. * 3. Except for the licenses you grant in this Agreement, you reserve all right, title and interest in your Contribution. * 4. You hereby grant to Stanford, with the right to sublicense, a perpetual, worldwide, non-exclusive, no charge, * royalty-free, irrevocable license to use, reproduce, make derivative works of, display and distribute the Contribution. * If your Contribution is protected by patent, you hereby grant to Stanford, with the right to sublicense, a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable license under your interest in patent rights embodied in * the Contribution, to make, have made, use, sell and otherwise transfer your Contribution, alone or in combination with * ePAD or otherwise. * 5. You acknowledge and agree that Stanford ham may incorporate your Contribution into ePAD and may make your * Contribution as incorporated available to members of the public on an open source basis under terms substantially in * accordance with the Software License set forth in Part A of this Agreement. You further acknowledge and agree that * Stanford shall have no liability arising in connection with claims resulting from your breach of any of the terms of * this Agreement. * 6. YOU WARRANT THAT TO THE BEST OF YOUR KNOWLEDGE YOUR CONTRIBUTION DOES NOT CONTAIN ANY CODE OBTAINED BY YOU UNDER AN * OPEN SOURCE LICENSE THAT REQUIRES OR PRESCRIBES DISTRBUTION OF DERIVATIVE WORKS UNDER SUCH OPEN SOURCE LICENSE. (By way * of non-limiting example, you will not contribute any code obtained by you under the GNU General Public License or other * so-called "reciprocal" license.) *******************************************************************************/ package edu.stanford.epad.epadws.service; import java.io.File; import java.util.Date; import java.util.List; import java.util.Map; import edu.stanford.epad.dtos.AnnotationStatus; import edu.stanford.epad.epadws.handlers.core.ProjectReference; import edu.stanford.epad.epadws.handlers.core.SeriesReference; import edu.stanford.epad.epadws.handlers.core.StudyReference; import edu.stanford.epad.epadws.handlers.core.SubjectReference; import edu.stanford.epad.epadws.models.EpadFile; import edu.stanford.epad.epadws.models.EpadStatistics; import edu.stanford.epad.epadws.models.EventLog; import edu.stanford.epad.epadws.models.FileType; import edu.stanford.epad.epadws.models.NonDicomSeries; import edu.stanford.epad.epadws.models.Project; import edu.stanford.epad.epadws.models.ProjectToSubjectToStudyToUserToFlaggedImage; import edu.stanford.epad.epadws.models.ProjectType; import edu.stanford.epad.epadws.models.Study; import edu.stanford.epad.epadws.models.Subject; import edu.stanford.epad.epadws.models.Template; import edu.stanford.epad.epadws.models.User; import edu.stanford.epad.epadws.models.UserRole; import edu.stanford.epad.epadws.models.dao.AbstractDAO; /** * All Epad User/Project/Subject/Study related operations to replace XNAT functionality * * @author Dev Gude * */ public interface EpadProjectOperations { /** * */ void clearCache(); int getCacheSize(); /** * Creates a project record in database * * @param loggedInUser * @param projectId * @param projectName * @param description * @param type * @return * @throws Exception */ Project createProject(String loggedInUser, String projectId, String projectName, String description, String defaultTemplate, ProjectType type) throws Exception; /** * Updates project fields in database (all arguments except projectId are optional) * @param loggedInUser * @param projectId * @param projectName * @param description * @param type * @return * @throws Exception */ Project updateProject(String loggedInUser, String projectId, String projectName, String description, String defaultTemplate, ProjectType type) throws Exception; /** * Creates a user record in database * * @param loggedInUser * @param username * @param firstName * @param lastName * @param email * @param password * @return * @throws Exception */ User createUser(String loggedInUser, String username, String firstName, String lastName, String email, String password, String colorpreference, List<String> addPermissions, List<String> removePermissions) throws Exception; /** * Updates a user record in database, fields can be null except username, password and oldpassword should match * * @param loggedInUser * @param username * @param firstName * @param lastName * @param email * @param password * @param oldpassword * @return * @throws Exception */ User updateUser(String loggedInUser, String username, String firstName, String lastName, String email, String password, String oldpassword, String colorpreference, List<String> addPermissions, List<String> removePermissions) throws Exception; /** * Set admin flag in user record * @param loggedInUser * @param username * @throws Exception */ void setAdmin(String loggedInUser, String username) throws Exception; /** * Reset admin flag in user record * @param loggedInUser * @param username * @throws Exception */ void resetAdmin(String loggedInUser, String username) throws Exception; /** * Set enabled flag in user record * @param loggedInUser * @param username * @throws Exception */ void enableUser(String loggedInUser, String username) throws Exception; /** * Reset enabled flag in user record * @param loggedInUser * @param username * @throws Exception */ void disableUser(String loggedInUser, String username) throws Exception; /** * Delete user record. Exception on foreign key violation (if related records exist) * @param loggedInUser * @param username * @throws Exception */ void deleteUser(String loggedInUser, String username) throws Exception; /** * Add User to project * @param loggedInUser * @param projectId * @param username * @param role - Owner, Member, Collaborator * @throws Exception */ void addUserToProject(String loggedInUser, String projectId, String username, UserRole role, String defaultTemplate) throws Exception; /** * Remove user from project * @param loggedInUser * @param projectId * @param username * @throws Exception */ void removeUserFromProject(String loggedInUser, String projectId, String username) throws Exception; /** * Set user role in project * @param loggedInUser * @param projectId * @param username * @param role - Owner, Member, Collaborator * @throws Exception */ void setUserRoleForProject(String loggedInUser, String projectId, String username, UserRole role) throws Exception; /* * Add logs to user object */ void updateUserTaskStatus(String username, String type, String target, String status, Date startTime, Date completeTime); void updateUserTaskStatus(String username, String type, String projectID, String target, String status, Date startTime, Date completeTime); void createEventLog(String username, String projectID, String subjectID, String studyUID, String seriesUID, String imageUID, String aimID, String function, String params); void createEventLog(String username, String projectID, String subjectID, String studyUID, String seriesUID, String imageUID, String aimID, String filename, String function, String params, boolean error); EpadStatistics getUserStatistics(String loggediInUser, String username, boolean exceptionOnErr) throws Exception; /** * Create Subject record in database * @param loggedInUser * @param subjectUID * @param name * @param dob * @param gender * @return * @throws Exception */ Subject createSubject(String loggedInUser, String subjectUID, String name, Date dob, String gender) throws Exception; Subject createSubject(String loggedInUser, String subjectUID, String name, Date dob, String gender, boolean changeOwner) throws Exception; /** * create a subject with a display uid * @param loggedInUser * @param subjectUID * @param name * @param dob * @param gender * @param displayUID * @return * @throws Exception */ Subject createSubject(String loggedInUser, String subjectUID, String name, Date dob, String gender, String displayUID) throws Exception; Subject createSubject(String loggedInUser, String subjectUID, String name, Date dob, String gender, boolean changeOwner, String displayUID) throws Exception; /** * Create Study record in database * @param loggedInUser * @param studyUID * @param subjectUID * @return * @throws Exception */ Study createStudy(String loggedInUser, String studyUID, String subjectUID, String description) throws Exception; Study createStudy(String loggedInUser, String studyUID, String subjectUID, String description, Date studyDate) throws Exception; Study createStudy(String loggedInUser, String studyUID, String subjectUID, String description, Date studyDate, boolean changeOwner) throws Exception; /** * Create Study record in database * @param loggedInUser * @param studyUID * @param subjectUID * @return * @throws Exception */ NonDicomSeries createNonDicomSeries(String loggedInUser, String seriesUID, String studyUID, String description, Date seriesDate, String modality, String referencedSeries) throws Exception; /** * Add Subject/Studies to Project * @param loggedInUser * @param subjectUID * @param projectId * @throws Exception */ void addSubjectToProject(String loggedInUser, String subjectUID, String projectId) throws Exception; /** * Add Study to Project * @param loggedInUser * @param studyUID * @param subjectUID * @param projectId * @throws Exception */ void addStudyToProject(String loggedInUser, String studyUID, String subjectUID, String projectId) throws Exception; /** * Remove Subject/Studies from project * @param loggedInUser * @param subjectUID * @param projectId * @throws Exception */ void removeSubjectFromProject(String loggedInUser, String subjectUID, String projectId) throws Exception; /** * Remove Study from Project * @param loggedInUser * @param studyUID * @param projectId * @throws Exception */ void removeStudyFromProject(String loggedInUser, String studyUID, String projectId) throws Exception; /** * Check if Subject is in Project * @param subjectUID * @param projectId * @throws Exception */ boolean isSubjectInProject(String subjectUID, String projectId) throws Exception; /** * Create File Record * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param file * @param filename * @param description * @param type * @return * @throws Exception */ EpadFile createFile(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, File file, String filename, String description, FileType type) throws Exception; /** * Get Project from database * @param projectId * @return * @throws Exception */ Project getProject(String projectId) throws Exception; /** * Get User from database * @param username * @return * @throws Exception */ User getUser(String username) throws Exception; /** * Get User from database by email * @param email * @return * @throws Exception */ User getUserByEmail(String email) throws Exception; /** * Get Subject from database * @param subjectUID * @return * @throws Exception */ Subject getSubject(String subjectUID) throws Exception; /** * Get Study from database * @param studyUID * @return * @throws Exception */ Study getStudy(String studyUID) throws Exception; /** * Get All Project records * @return * @throws Exception */ List<Project> getAllProjects() throws Exception; /** * Get all user records with projects/roles * @return * @throws Exception */ List<User> getAllUsers() throws Exception; /** * Get public projects * @return * @throws Exception */ List<Project> getPublicProjects() throws Exception; /** * Get Projects for a user * @param username * @return * @throws Exception */ List<Project> getProjectsForUser(String username) throws Exception; /** * Get single project for a user * @param username * @param projectID * @return * @throws Exception */ Project getProjectForUser(String username, String projectID) throws Exception; /** * Get Users for a project * @param projectId * @return * @throws Exception */ List<User> getUsersForProject(String projectId) throws Exception; /** * Get Users with role for a project * @param projectId * @return * @throws Exception */ List<User> getUsersWithRoleForProject(String projectId) throws Exception; /** * Get Subjects for a project * @param projectId * @return * @throws Exception */ List<Subject> getSubjectsForProject(String projectId) throws Exception; List<Subject> getSubjectsForProject(String projectId, String sortBy) throws Exception; List<Subject> getUnassignSubjects() throws Exception; /** * Get Subject for project * @param projectId * @param subjectUID * @return * @throws Exception */ Subject getSubjectForProject(String projectId, String subjectUID) throws Exception; /** * Get projects for a subject * @param subjectUID * @return * @throws Exception */ List<Project> getProjectsForSubject(String subjectUID) throws Exception; /** * Get projects for a study * @param subjectUID * @return * @throws Exception */ List<Project> getProjectsForStudy(String studyUID) throws Exception; /** * Get Subject/Patient by name * @param subjectName * @return * @throws Exception */ Subject getSubjectFromName(String subjectName) throws Exception; /** * Get Subject for a project by name * @param subjectName * @param projectID * @return * @throws Exception */ Subject getSubjectFromNameForProject(String subjectName, String projectID) throws Exception; /** * Get First Project for a Study * @param studyUID * @return * @throws Exception */ Project getFirstProjectForStudy(String studyUID) throws Exception; /** * Get Studies for Project/Subject * @param projectId * @param subjectUID * @return * @throws Exception */ List<Study> getStudiesForProjectAndSubject(String projectId, String subjectUID) throws Exception; /** * Check if Study in Project * @param projectId * @param subjectUID * @param studyUID * @return * @throws Exception */ boolean isStudyInProjectAndSubject(String projectId, String subjectUID, String studyUID) throws Exception; /** * Get all studies for project * @param projectId * @return * @throws Exception */ List<Study> getAllStudiesForProject(String projectId) throws Exception; /** * Get Studies for a subject * @param subjectUID * @return * @throws Exception */ List<Study> getStudiesForSubject(String subjectUID) throws Exception; Subject getSubjectForStudy(String studyUID) throws Exception; /** * Get Non-dicom series for a study * @param subjectUID * @return * @throws Exception */ List<NonDicomSeries> getNonDicomSeriesForStudy(String studyUID) throws Exception; /** * Get Non-dicom series * @param seriesUID * @return * @throws Exception */ NonDicomSeries getNonDicomSeries(String seriesUID) throws Exception; /** * Set user status for project and subject * @param loggedInUser * @param projectID * @param subjectUID * @param status * @throws Exception */ void setUserStatusForProjectAndSubject(String loggedInUser, String projectID, String subjectUID, String status) throws Exception; /** * Get user status for project and subject * @param loggedInUser * @param projectID * @param subjectUID * @return * @throws Exception */ String getUserStatusForProjectAndSubject(String loggedInUser, String projectID, String subjectUID) throws Exception; /** * Get map for subject/status for a user/project * @param loggedInUser * @param projectID * @return * @throws Exception */ Map<String, String> getUserStatusForProjectSubjects(String loggedInUser, String projectID) throws Exception; /** * Get map for subjectId/status for a user/project * @param loggedInUser * @param projectID * @return * @throws Exception */ Map<Long, String> getUserStatusForProjectSubjectIds(String loggedInUser, String projectID) throws Exception; /** * Get File for project/subject/study/series by filename * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @return * @throws Exception */ EpadFile getEpadFile(String projectID, String subjectUID, String studyUID, String seriesUID, String filename) throws Exception; /** * Get Files for project/subject/study/series by filetype * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @return * @throws Exception */ List<EpadFile> getEpadFiles(String projectID, String subjectUID, String studyUID, String seriesUID, FileType fileType, boolean toplevelOnly) throws Exception; /** * Get files for project * @param projectID * @return * @throws Exception */ List<EpadFile> getProjectFiles(String projectID, boolean toplevelOnly) throws Exception; /** * Get files for project/subject * @param projectID * @param subjectUID * @return * @throws Exception */ List<EpadFile> getSubjectFiles(String projectID, String subjectUID, boolean toplevelOnly) throws Exception; /** * Get files for project/subject/study * @param projectID * @param subjectUID * @param studyUID * @return * @throws Exception */ List<EpadFile> getStudyFiles(String projectID, String subjectUID, String studyUID, boolean toplevelOnly) throws Exception; /** * Get files for project/subject/study/series * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @return * @throws Exception */ List<EpadFile> getSeriesFiles(String projectID, String subjectUID, String studyUID, String seriesUID) throws Exception; /** * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @throws Exception */ void enableFile(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, String filename) throws Exception; /** * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @throws Exception */ void disableFile(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, String filename) throws Exception; /** * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param templateName * @throws Exception */ void enableTemplate(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, String templateName) throws Exception; /** * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param templateName * @throws Exception */ void disableTemplate(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, String templateName) throws Exception; /** * @param fileID * @param filename * @param description * @param fileType * @param mimeType * @return * @throws Exception */ EpadFile updateEpadFile(long fileID, String filename, String description, String fileType, String mimeType) throws Exception; /** * @param projectID * @return * @throws Exception */ List<String> getDisabledTemplates(String projectID) throws Exception; /** * @param project * @param file */ void linkFileToProject(String loggedInUser, Project project, EpadFile file) throws Exception; /** * @param project * @param file */ void unlinkFileFromProject(String loggedInUser, Project project, EpadFile file) throws Exception; /** * @param project * @return * @throws Exception */ List<EpadFile> getLinkedFiles(Project project) throws Exception; /** * @param username * @return * @throws Exception */ boolean isAdmin(String username) throws Exception; /** * Check if user is in project * @param username * @param projectID * @return * @throws Exception */ boolean hasAccessToProject(String username, String projectID) throws Exception; /** * Check if user is in project * @param username * @param project key * @return * @throws Exception */ boolean hasAccessToProject(String username, long id) throws Exception; /** * Check if collaborator * @param username * @param projectID * @return * @throws Exception */ boolean isCollaborator(String username, String projectID) throws Exception; /** * Check if member * @param username * @param projectID * @return * @throws Exception */ boolean isMember(String username, String projectID) throws Exception; /** * Check if owner * @param username * @param projectID * @return * @throws Exception */ boolean isOwner(String username, String projectID) throws Exception; /** * Get project role * @param username * @param projectID * @return * @throws Exception */ UserRole getUserProjectRole(String username, String projectID) throws Exception; /** * Delete project * @param username * @param projectID * @throws Exception */ void deleteProject(String username, String projectID) throws Exception; /** * Delete subject from project * @param username * @param subjectUID * @param projectID * @throws Exception */ void deleteSubject(String username, String subjectUID, String projectID) throws Exception; /** * Delete study from project * @param username * @param studyUID * @param subjectUID * @param projectID * @throws Exception */ void deleteStudy(String username, String studyUID, String subjectUID, String projectID) throws Exception; /** * Delete subject * @param username * @param subjectUID * @throws Exception */ void deleteSubject(String username, String subjectUID) throws Exception; /** * Delete study * @param username * @param studyUID * @throws Exception */ void deleteStudy(String username, String studyUID) throws Exception; /** * Delete Non-dicom series * @param seriesUID * @return * @throws Exception */ void deleteNonDicomSeries(String seriesUID) throws Exception; /** * Delete file * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @throws Exception */ void deleteFile(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, String filename) throws Exception; /** * Get event logs for this user * @param username * @return */ List<EventLog> getUseEventLogs(String username, int start, int count) throws Exception; /** * Get reviewers for this user * @param username * @return * @throws Exception */ List<User> getReviewers(String username) throws Exception; /** * Get reviewees for this user * @param username * @return * @throws Exception */ List<User> getReviewees(String username) throws Exception; /** * Add reviewer to this user * @param loggedInUser * @param username * @param reviewer * @throws Exception */ void addReviewer(String loggedInUser, String username, String reviewer) throws Exception; /** * Add reviewee to this user * @param loggedInUser * @param username * @param reviewee * @throws Exception */ void addReviewee(String loggedInUser, String username, String reviewee) throws Exception; /** * Remove reviewer from this user * @param loggedInUser * @param username * @param reviewer * @throws Exception */ void removeReviewer(String loggedInUser, String username, String reviewer) throws Exception; /** * Remove reviewee from this user * @param loggedInUser * @param username * @param reviewee * @throws Exception */ void removeReviewee(String loggedInUser, String username, String reviewee) throws Exception; /** * Get database object by primary key * @param dbclass * @param id * @return * @throws Exception */ AbstractDAO getDBObject(Class dbclass, long id) throws Exception; /** * Sort db object list * @param objects * @param field * @param ascending * @return sorted list * @throws Exception */ List sort(List<AbstractDAO> objects, String field, boolean ascending); /** * get user count for a specific project with project uid * @param projectId * @return count * @throws Exception */ long getUserCountProject(String projectId) throws Exception; /** * get user count for a specific project with project id * @param id * @return count * @throws Exception */ long getUserCountForProject(long id) throws Exception; /** * Gets all the parameters and returns the annotation status for that specific user and series * @param projectuid * @param subjectuid * @param studyuid * @param seriesuid * @param username * @param numberOfSeries for cumulative status * @return annotation status see AnnotationStatus class for values or null * @author emelalkim */ AnnotationStatus getAnnotationStatusForUser(String projectUID, String subjectUID, String studyUID, String series_uid, String username, int numberOfSeries); /** * Gets the number of users that are in the status annotating the specific series for the project (using model) * @param projectUID * @param subjectUID * @param studyUID * @param series_uid * @param status annotation status * @return count or 0 * @author emelalkim */ int getAnnotationStatusUserCount(String projectUID, String subjectUID, String studyUID, String series_uid, AnnotationStatus status); /** * update annotation status for user * if annotation status can be converted to an integer writes it * if not checks if it is DONE * if not writes error * see AnnotationStatus class for the code values * @param username * @param seriesReference * @param annotationStatus * @param sessionID * @throws Exception */ void updateAnnotationStatus(String username, SeriesReference seriesReference, String annotationStatus, String sessionID) throws Exception; /** * updates the annotation status for whole study * @param username * @param studyReference * @param annotationStatus * @param sessionID * @throws Exception */ void updateAnnotationStatus(String username, StudyReference studyReference, String annotationStatus, String sessionID) throws Exception; /** * updates the annotation status for whole subject * @param username * @param subjectReference * @param annotationStatus * @param sessionID * @throws Exception */ void updateAnnotationStatus(String username, SubjectReference subjectReference, String annotationStatus, String sessionID) throws Exception; /** * updates the annotation status for whole project * @param username * @param projectReference * @param annotationStatus * @param sessionID * @throws Exception */ void updateAnnotationStatus(String username, ProjectReference projectReference, String annotationStatus, String sessionID) throws Exception; /** * create file with templateleveltype information * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param file * @param filename * @param description * @param fileType * @param templateLevelType * @return * @throws Exception */ EpadFile createFile(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, File file, String filename, String description, FileType fileType, String templateLevelType) throws Exception; /** * get studies older than given number of days * @param days * @return * @throws Exception */ List<Study> getStudiesOlderThanDays(Integer days) throws Exception; /** * get all projects for a specific template * @param templateid * @return a list of project ids * @throws Exception */ List<Long> getProjectsForTemplate(long templateid) throws Exception; /** * get template entry from db * @param templateCode * @return * @throws Exception */ Template getTemplate(String templateCode) throws Exception; /** * set project-template relation. enable/disable template for a specific project * @param loggedInUser * @param projectID * @param templateCode * @throws Exception */ void setProjectTemplate(String loggedInUser, String projectID, String templateCode, boolean enable) throws Exception; /** * get disabled projects for a template * @param templateId * @return * @throws Exception */ List<Long> getDisabledProjectsForTemplate(long templateId) throws Exception; /** * get the current enable/disable status * @param loggedInUser * @param projectID * @param templateCode * @return * @throws Exception */ boolean getProjectTemplate(String loggedInUser, String projectID, String templateCode) throws Exception; /** * get enabled projects for a specific template * @param templateId * @return * @throws Exception */ List<Long> getEnabledProjectsForTemplate(long templateId) throws Exception; /** * new get disables templates. returns codes * @param projectID * @return * @throws Exception */ List<String> getDisabledTemplateCodes(String projectID) throws Exception; /** * get file with type * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @param filetype * @return * @throws Exception */ EpadFile getEpadFile(String projectID, String subjectUID, String studyUID, String seriesUID, String filename, String filetype) throws Exception; /** * delete a file with filetype attribute * @param loggedInUser * @param projectID * @param subjectUID * @param studyUID * @param seriesUID * @param filename * @param filetype * @throws Exception */ void deleteFile(String loggedInUser, String projectID, String subjectUID, String studyUID, String seriesUID, String filename, String filetype) throws Exception; /** * check if the image is flagged for this project and user * @param username * @param imageUID * @param projectID * @param subjectID * @return */ boolean isFlagged(String username, String imageUID, String projectID, String subjectID, String studyID); /** * set image flagged for this project and user * @param username * @param imageUID * @param projectID * @param flag * @param subjectID */ void setFlagged(String username, String imageUID, String projectID, boolean flag, String subjectID, String studyID); /** * get the flag status from db * @param username * @param imageUID * @param projectID * @param subjectID * @return */ ProjectToSubjectToStudyToUserToFlaggedImage getFlagStatus(String username, String imageUID, String projectID, String subjectID, String studyID); /** * gets the imageuids for the flagged images in the project. if the project id is null returns all * @param username * @param projectID * @param subjectID * @return */ List<String> getFlaggedImageUIDs(String username, String projectID, String subjectID, String studyID); }
true
ede415d5ae6174064488857dd17d10a025abc9b7
Java
yavid-dmitry/JD1_Unit01
/task05/main/Task02.java
UTF-8
818
3.34375
3
[]
no_license
package by.htp.task05.main; /* * 2. В целочисленной последовательности есть нулевые элементы. Создать массив из номеров этих элементов. */ public class Task02 { public static void main(String[] args) { // TODO Auto-generated method stub int n = 10; int[] a = Method.initArray(n, 100); for(int i = 0; i < n; i++) { if(a[i] > 60) { a[i] = 0; } } int length = 0; for(int i = 0; i < n; i++) { if(a[i] == 0) { length++; } } int[] arrayZeroIndex = new int[length]; int count = 0; for(int i = 0; i < n; i++) { if(a[i] == 0) { arrayZeroIndex[count] = i; count++; } } Method.print(a); Method.print(arrayZeroIndex); } }
true
93fcc192fa2fd6f64cffde241629bf38359ee684
Java
DeusBlu/D20Zuul
/D20Zuul 0.1_9/src/testFighterClass.java
UTF-8
236
2.484375
2
[]
no_license
public class testFighterClass { @SuppressWarnings("unused") public static void main(String[] args) { Fighter fighter = new Fighter(); fighter.addXP(140000); int[] attacks = fighter.getAttacks(); System.out.println(); } }
true
39b8a87f644daee2b5f62727a38aee24372a3e86
Java
superbiaYang/ImageProcessing
/app/src/main/java/view/fragment/BinaryMorphologyFragment.java
UTF-8
5,262
2.484375
2
[]
no_license
package view.fragment; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import superbiayang.imageprocessing.R; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link BinaryMorphologyFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link BinaryMorphologyFragment#newInstance} factory method to * create an instance of this fragment. */ public class BinaryMorphologyFragment extends Fragment implements View.OnClickListener { private OnFragmentInteractionListener mListener; private int[] mSkeleton; public BinaryMorphologyFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment BinaryMorphologyFragment. */ public static BinaryMorphologyFragment newInstance() { BinaryMorphologyFragment fragment = new BinaryMorphologyFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_binary_morphology, container, false); int[] buttonId = { R.id.distance_button, R.id.skeleton_button, R.id.reconstruct_button, R.id.binary_erode_button, R.id.binary_conditional_dilate_button, R.id.standard_edge_button, R.id.external_edge_button, R.id.internal_edge_button }; for (int id : buttonId) { Button button = (Button) view.findViewById(id); button.setOnClickListener(this); } return view; } @Override public void onAttach(Context context) { super.onAttach(context); mSkeleton = null; if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } /** * In order to support API 21 */ @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) activity; } else { throw new RuntimeException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; mSkeleton = null; } @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.distance_button: mListener.transformDistance(); break; case R.id.skeleton_button: mSkeleton = mListener.skeleton(); if (mSkeleton != null) { getView().findViewById(R.id.reconstruct_button).setEnabled(true); } break; case R.id.reconstruct_button: mListener.reconstruct(mSkeleton); break; case R.id.binary_erode_button: mListener.erode(); break; case R.id.binary_conditional_dilate_button: mListener.conditionalDilate(); break; case R.id.standard_edge_button: mListener.standardEdge(); break; case R.id.internal_edge_button: mListener.internalEdge(); break; case R.id.external_edge_button: mListener.externalEdge(); break; } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { void transformDistance(); int[] skeleton(); void reconstruct(int[] skeleton); void erode(); void conditionalDilate(); void standardEdge(); void externalEdge(); void internalEdge(); } }
true
a5706971eec1c35741702e48f611b23dd5bbd119
Java
limadmarlon/MEG
/src/lexical/LexAnalyzer.java
UTF-8
12,851
2.796875
3
[]
no_license
package lexical; import lexical.Token; import lexical.tkCateg; public class LexAnalyzer { private String code; private String tokenName; private tkCateg categ; private int count; private int initToken; public LexAnalyzer(String code) { super(); this.code = code; this.count = 0; this.initToken = 0; } public Token nextToken(){ try{ return nextToken2(); }catch (StringIndexOutOfBoundsException e) { if(categ == tkCateg.tk_start){ //EOF implement return new Token("",tkCateg.tk_EOF,-1); }else{ //implement last token count = code.length(); return new Token(code.substring(initToken, code.length()),categ,initToken); } } } private Token nextToken2() throws StringIndexOutOfBoundsException{ categ = tkCateg.tk_start; initToken = count; ignoreSpecial(); //garante que nao ira lancar uma exception categ = tkCateg.tkOpr_log; if(code.charAt(count) == '&') {count++; return new Token("&",categ,initToken);} if(code.charAt(count) == '|') {count++; return new Token("|",categ,initToken);} categ = tkCateg.tkOpr_neg; if(code.charAt(count) == '!') {count++; return new Token("!",categ,initToken);} categ = tkCateg.tkOpr_sum; if(code.charAt(count) == '-') {count++; return new Token("-",categ,initToken);} if(code.charAt(count) == '+'){ if(code.charAt(count+1) == '+'){ //implement concat categ = tkCateg.tkOpr_concat; count=+2; return new Token("++",categ,initToken); }else{ //implement plus count++; return new Token("+",categ,initToken); } } categ = tkCateg.tkOpr_mul; if(code.charAt(count) == '*') {count++; return new Token("*",categ,initToken);} if(code.charAt(count) == '/'){ //commandblock///////////////////// if(code.charAt(count + 1) == '*'){ if(code.charAt(count + 2) == '*'){ categ=tkCateg.tk_start; count+=3; ignoreCommentBlock(); return nextToken(); } } //ComentLine/////////////////////// if(code.charAt(count) == '/'){ categ=tkCateg.tk_start; count+=2; ignoreCommentLine(); return nextToken(); } //Division count++; return new Token("/",categ,initToken); } categ = tkCateg.tkOpr_att; if(code.charAt(count) == '=') {count++; return new Token("=",categ,initToken);} categ = tkCateg.tkOpr_r; if(code.charAt(count) == '<') {count++; return new Token("<",categ,initToken);} if(code.charAt(count) == '>') {count++; return new Token(">",categ,initToken);} if(code.charAt(count) == '<' && code.charAt(count+1) == '=') {count+=2; return new Token("<=",categ,initToken);} if(code.charAt(count) == '>' && code.charAt(count+1) == '=') {count+=2; return new Token(">=",categ,initToken);} if(code.charAt(count) == '=' && code.charAt(count+1) == '=') {count+=2; return new Token("==",categ,initToken);} categ = tkCateg.tkOpr_index_enter; if(code.charAt(count) == '[') {count++; return new Token("[",categ,initToken);} categ = tkCateg.tkOpr_index_out; if(code.charAt(count) == ']') {count++; return new Token("]",categ,initToken);} categ = tkCateg.tkDel_comma; if(code.charAt(count) == ',') {count++; return new Token(",",categ,initToken);} categ = tkCateg.tkDel_par_enter; if(code.charAt(count) == '(') {count++; return new Token("(",categ,initToken);} categ = tkCateg.tkDel_par_out; if(code.charAt(count) == ')') {count++; return new Token(")",categ,initToken);} categ = tkCateg.tkDel_bra_enter; if(code.charAt(count) == '{') {count++; return new Token("{",categ,initToken);} categ = tkCateg.tkDel_bra_out; if(code.charAt(count) == '}') {count++; return new Token("}",categ,initToken);} categ = tkCateg.tkDel_dot; if(code.charAt(count) == '.') {count++; return new Token(".",categ,initToken);} categ = tkCateg.tkDel_scolon; if(code.charAt(count) == ';') {count++; return new Token(";",categ,initToken);} categ = tkCateg.tkDel_colon; if(code.charAt(count) == ':') {count++; return new Token(":",categ,initToken);} categ = tkCateg.tkDel_comma; if(code.charAt(count) == ',') {count++; return new Token(",",categ,initToken);} categ = tkCateg.tkLit_bool; if(code.charAt(count) == '#') { count++; if(code.charAt(count) == 'T') {count++; return new Token("#T",categ,initToken);} else if (code.charAt(count) == 'F') {count++; return new Token("#F",categ,initToken);} else {count ++; return new Token(code.substring(initToken, count),categ,initToken);}//error } ////////////////char literal////////// categ = tkCateg.tkLit_char; if(code.charAt(count) == '\'') { tokenName = ""; count++; while(!(code.charAt(count) == '\'') || (code.charAt(count-1) == '\\')){ tokenName = tokenName.concat(Character.toString(code.charAt(count))); count++; } count++; return new Token(tokenName,categ,initToken); } //////////////////string literal////////////// categ = tkCateg.tkLit_string; if(code.charAt(count) == '"') { tokenName = ""; count++; while(!(code.charAt(count) == '"') || (code.charAt(count-1) == '\\')){ tokenName = tokenName.concat(Character.toString(code.charAt(count))); count++; } count++; return new Token(tokenName,categ,initToken); } ///////literal Number///////////////////////// categ = tkCateg.tkLit_int; if(Character.isDigit(code.charAt(count))){ tokenName = ""; while((Character.isDigit(code.charAt(count)) || code.charAt(count) == '.')){ tokenName = tokenName.concat(Character.toString(code.charAt(count))); if(code.charAt(count) =='.'){ categ = tkCateg.tkLit_float; if(!Character.isDigit(code.charAt(count+1))) categ = tkCateg.tk_error; count++; while(Character.isDigit(code.charAt(count))){ tokenName = tokenName.concat(Character.toString(code.charAt(count))); count++; } //return tkLit_float return new Token(tokenName,categ,initToken); }else{ count++; } } return new Token(tokenName,categ,initToken); } //////////words///////////////////////////////// if(Character.isAlphabetic(code.charAt(count))){ ///////////////tipos/////////////////////// categ = tkCateg.tkType_int; if( code.charAt(count ) == 'i' && code.charAt(count+1) == 'n' && code.charAt(count+2) == 't' && !(Character.isAlphabetic(code.charAt(count+3)) || code.charAt(count+3) == '_')) { count+=3; return new Token("int",categ,initToken); } categ = tkCateg.tkType_float; if( code.charAt(count ) == 'f' && code.charAt(count+1) == 'l' && code.charAt(count+2) == 'o' && code.charAt(count+3) == 'a' && code.charAt(count+4) == 't' && !(Character.isAlphabetic(code.charAt(count+5)) || code.charAt(count+5) == '_')) { count+=5; return new Token("float",categ,initToken); } categ = tkCateg.tkType_char; if( code.charAt(count ) == 'c' && code.charAt(count+1) == 'h' && code.charAt(count+2) == 'a' && code.charAt(count+3) == 'r' && !(Character.isAlphabetic(code.charAt(count+4)) || code.charAt(count+4) == '_')) { count+=4; return new Token("char",categ,initToken); } categ = tkCateg.tkType_bool; if( code.charAt(count ) == 'b' && code.charAt(count+1) == 'o' && code.charAt(count+2) == 'o' && code.charAt(count+3) == 'l' && !(Character.isAlphabetic(code.charAt(count+4)) || code.charAt(count+4) == '_')) { count+=4; return new Token("bool",categ,initToken); } categ = tkCateg.tkType_string; if( code.charAt(count ) == 's' && code.charAt(count+1) == 't' && code.charAt(count+2) == 'r' && code.charAt(count+3) == 'i' && code.charAt(count+4) == 'n' && code.charAt(count+5) == 'g' && !(Character.isAlphabetic(code.charAt(count+6)) || code.charAt(count+6) == '_')) { count+=6; return new Token("string",categ,initToken); } categ = tkCateg.tkType_array; if( code.charAt(count ) == 'a' && code.charAt(count+1) == 'r' && code.charAt(count+2) == 'r' && code.charAt(count+3) == 'a' && code.charAt(count+4) == 'y' && !(Character.isAlphabetic(code.charAt(count+5)) || code.charAt(count+5) == '_')) { count+=5; return new Token("array",categ,initToken); } ////////////////reserved words///////////////////// categ = tkCateg.tk_if; if( code.charAt(count ) == 'i' && code.charAt(count+1) == 'f' && !(Character.isAlphabetic(code.charAt(count+2)) || code.charAt(count+2) == '_')) { count+=2; return new Token("if",categ,initToken); } categ = tkCateg.tk_else; if( code.charAt(count ) == 'e' && code.charAt(count+1) == 'l' && code.charAt(count+2) == 's' && code.charAt(count+3) == 'e' && !(Character.isAlphabetic(code.charAt(count+4)) || code.charAt(count+4) == '_')) { count+=4; return new Token("else",categ,initToken); } categ = tkCateg.tk_while; if( code.charAt(count ) == 'w' && code.charAt(count+1) == 'h' && code.charAt(count+2) == 'i' && code.charAt(count+3) == 'l' && code.charAt(count+4) == 'e' && !(Character.isAlphabetic(code.charAt(count+5)) || code.charAt(count+5) == '_')) { count+=5; return new Token("while",categ,initToken); } categ = tkCateg.tk_then; if( code.charAt(count ) == 't' && code.charAt(count+1) == 'h' && code.charAt(count+2) == 'e' && code.charAt(count+3) == 'n' && !(Character.isAlphabetic(code.charAt(count+4)) || code.charAt(count+4) == '_')) { count+=4; return new Token("then",categ,initToken); } categ = tkCateg.tk_do; if( code.charAt(count ) == 'd' && code.charAt(count+1) == 'o' && !(Character.isAlphabetic(code.charAt(count+2)) || code.charAt(count+2) == '_')) { count+=2; return new Token("do",categ,initToken); } categ = tkCateg.tk_in; if( code.charAt(count ) == 'i' && code.charAt(count+1) == 'n' && !(Character.isAlphabetic(code.charAt(count+2)) || code.charAt(count+2) == '_')) { count+=2; return new Token("in",categ,initToken); } categ = tkCateg.tk_for; if( code.charAt(count ) == 'f' && code.charAt(count+1) == 'o' && code.charAt(count+2) == 'r' && !(Character.isAlphabetic(code.charAt(count+3)) || code.charAt(count+3) == '_')) { count+=3; return new Token("for",categ,initToken); } categ = tkCateg.tk_out; if( code.charAt(count ) == 'o' && code.charAt(count+1) == 'u' && code.charAt(count+2) == 't' && !(Character.isAlphabetic(code.charAt(count+3)) || code.charAt(count+3) == '_')) { count+=3; return new Token("out",categ,initToken); } categ = tkCateg.tk_return; if( code.charAt(count ) == 'r' && code.charAt(count+1) == 'e' && code.charAt(count+2) == 't' && code.charAt(count+3) == 'u' && code.charAt(count+4) == 'r' && code.charAt(count+5) == 'n' && !(Character.isAlphabetic(code.charAt(count+6)) || code.charAt(count+6) == '_')) { count+=6; return new Token("return",categ,initToken); } categ = tkCateg.tk_end; if( code.charAt(count ) == 'e' && code.charAt(count+1) == 'n' && code.charAt(count+2) == 'd' && !(Character.isAlphabetic(code.charAt(count+3)) || code.charAt(count+3) == '_')) { count+=3; return new Token("end",categ,initToken); } categ = tkCateg.tkMain; if( code.charAt(count ) == 'm' && code.charAt(count+1) == 'a' && code.charAt(count+2) == 'i' && code.charAt(count+3) == 'n' && !(Character.isAlphabetic(code.charAt(count+4)) || code.charAt(count+4) == '_')) { count+=4; return new Token("main",categ,initToken); } tokenName = ""; categ = tkCateg.tkId; while(Character.isAlphabetic(code.charAt(count)) || code.charAt(count) == '_' ){ tokenName = tokenName.concat(Character.toString(code.charAt(count))); if(code.charAt(count) =='_'){ if(code.charAt(count+1) == '_'){ categ = tkCateg.tk_error; } count++; }else{ count++; } } //return tkId return new Token(tokenName,categ,initToken); } return null; } private void ignoreSpecial() throws StringIndexOutOfBoundsException{ while(code.charAt(count) == ' ' || code.charAt(count) == '\n'){ count++; initToken++; } } private void ignoreCommentBlock() throws StringIndexOutOfBoundsException{ boolean outOfBlock=false; while(!outOfBlock){ if(code.charAt(count) == '*'){ if(code.charAt(count+1) == '*'){ if(code.charAt(count+2) == '/'){ outOfBlock = true; } } } count+=3; } } private void ignoreCommentLine() throws StringIndexOutOfBoundsException{ while(!(code.charAt(count) == '\n')){ count++; initToken++; } count++; } }
true
0c088e9362473b0199d4f85dbc5e23424ad3099b
Java
KhioneusNevula/TemenDingir
/src/main/java/com/gm910/temendingir/world/gods/cap/DeityStorage.java
UTF-8
648
2.1875
2
[]
no_license
package com.gm910.temendingir.world.gods.cap; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.Capability.IStorage; public class DeityStorage implements IStorage<DeityData> { @Override public INBT writeNBT(Capability<DeityData> capability, DeityData instance, Direction side) { return instance.write(new CompoundNBT()); } @Override public void readNBT(Capability<DeityData> capability, DeityData instance, Direction side, INBT nbt) { instance.read((CompoundNBT) nbt); } }
true
94e0cad34ad2b8bdc495c77ce4ee78b54b7bbb4f
Java
bublikdrdrdr/miniBank
/src/generated/java/tk/ubublik/pai/entity/PasswordResetRequest_.java
UTF-8
842
1.804688
2
[]
no_license
package tk.ubublik.pai.entity; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(PasswordResetRequest.class) public abstract class PasswordResetRequest_ { public static volatile SingularAttribute<PasswordResetRequest, Date> date; public static volatile SingularAttribute<PasswordResetRequest, Long> id; public static volatile SingularAttribute<PasswordResetRequest, User> user; public static volatile SingularAttribute<PasswordResetRequest, String> hash; public static final String DATE = "date"; public static final String ID = "id"; public static final String USER = "user"; public static final String HASH = "hash"; }
true
67975f8450620c99608e6e0f934475bb99be9e2b
Java
NinjaMoon/leetcode-practices
/hard-questions/273-integer-to-english-words/Solution273.java
UTF-8
3,268
3.734375
4
[]
no_license
class Solution273 { public String translateBelowTwenty(int num) { switch(num) { case 1: return "One"; case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; case 5: return "Five"; case 6: return "Six"; case 7: return "Seven"; case 8: return "Eight"; case 9: return "Nine"; case 10: return "Ten"; case 11: return "Eleven"; case 12: return "Twelve"; case 13: return "Thirteen"; case 14: return "Fourteen"; case 15: return "Fifteen"; case 16: return "Sixteen"; case 17: return "Seventeen"; case 18: return "Eighteen"; case 19: return "Nineteen"; } return ""; } public String translateAboveTwenty(int num) { switch(num) { case 2: return "Twenty"; case 3: return "Thirty"; case 4: return "Forty"; case 5: return "Fifty"; case 6: return "Sixty"; case 7: return "Seventy"; case 8: return "Eighty"; case 9: return "Ninety"; } return ""; } public String additionalNumber(int level) { switch(level) { case 1: return " Thousand"; case 2: return " Million"; case 3: return " Billion"; } return ""; } public String convertFirstTwo(int num) { String result = ""; if(num < 20) { result = translateBelowTwenty(num); } else { int remainder = num % 10; int tenth = num / 10; result = (remainder > 0) ? translateAboveTwenty(tenth) + " " + translateBelowTwenty(remainder) : translateAboveTwenty(tenth); } return result; } public String convertFirstThree(int num) { String result = ""; int remainder = 0; int hundred = 0; if(num >= 100) { remainder = num % 100; hundred = num / 100; } else { remainder = num; } if(hundred > 0) { result = (remainder > 0) ? translateBelowTwenty(hundred) + " Hundred " : translateBelowTwenty(hundred) + " Hundred"; } result = result + convertFirstTwo(remainder); return result; } public String convertNumberToWords(int num, int level) { String result = ""; int remainder = 0; int nextIteration = 0; if(num >= 1000) { remainder = num % 1000; nextIteration = num / 1000; } else { remainder = num; } result = convertFirstThree(remainder); result = (result.length() > 0) ? result + additionalNumber(level) : result; if(nextIteration > 0) { return convertNumberToWords(nextIteration, ++level).trim() + " " + result; } return result; } public String numberToWords(int num) { if(num == 0) return "Zero"; String answer = convertNumberToWords(num, 0); return answer.trim(); } }
true
84f74fbc9f89a18b06717b07ba8c67484f1e930c
Java
Maiada-Wagdy-Mahmoud/The-Auctioneer
/src/main/java/edu/mum/cs/auctioneer/services/UserServiceImpl.java
UTF-8
405
2.046875
2
[]
no_license
package edu.mum.cs.auctioneer.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import edu.mum.cs.auctioneer.repositories.UserRepository; @Service public class UserServiceImpl implements UserService{ private UserRepository userRepo; @Autowired public UserServiceImpl(UserRepository userRepo) { this.userRepo = userRepo; } }
true
5628c9c1d0dee7a8706a9ce491a44b4a85cfcdee
Java
newman008/Basics
/CodingChallenge/LeetCode/1-99/_56_MergeIntervals.java
UTF-8
1,244
3.421875
3
[]
no_license
package LeetCode2; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class _56_MergeIntervals { public class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public List<Interval> merge(List<Interval> intervals) { if(intervals.size() < 2) return intervals; Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval v1, Interval v2) { return v1.start - v2.start; } }); List<Interval> res = new ArrayList<Interval>(); int start = intervals.get(0).start; int end = intervals.get(0).end; for(Interval interval : intervals) { if(interval.start > end) { res.add(new Interval(start, end)); start = interval.start; end = interval.end; } else { end = Math.max(end, interval.end); } } res.add(new Interval(start, end)); return res; } }
true
b622dddff7a4ca7b8f12d118a7d7c536048370d3
Java
gonsalez12/minhasFinancas-backEnd
/src/test/java/com/gonsalez/minhasfinancas/model/repository/UsuarioRepositoryTest.java
UTF-8
941
2.03125
2
[]
no_license
package com.gonsalez.minhasfinancas.model.repository; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import com.gonsalez.minhasfinancas.model.entity.Usuario; @SpringBootTest @RunWith(SpringRunner.class) @ActiveProfiles("teste") public class UsuarioRepositoryTest { @Autowired UsuarioRepository repository; @Test public void deveVerificarAExistenciaDeEmail() { //cenario Usuario usuario = Usuario.builder().nome("usaurio").email("usuario@email.com").build(); repository.save(usuario); //ação boolean result = repository.exitsByEmail("usaurio@email.com"); //verificação Assertions.assertThat(result).isTrue(); } }
true
aa9e44052cd02efd92963e4739033d10bf8bab95
Java
HengeLiu/examination-analysis
/src/main/java/analysis/interceptor/SecurityFilterInterceptor.java
UTF-8
1,132
2.078125
2
[]
no_license
package analysis.interceptor; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.springframework.security.access.SecurityMetadataSource; import org.springframework.security.access.intercept.AbstractSecurityInterceptor; /** * 安全过滤拦截器 * * @author elio * @version 1.0 * @since 2018/09/19 */ public class SecurityFilterInterceptor extends AbstractSecurityInterceptor implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { } @Override public void destroy() { } @Override public Class<?> getSecureObjectClass() { return null; } @Override public SecurityMetadataSource obtainSecurityMetadataSource() { return null; } }
true
9b0804d0bb9f5dd6892c1618dc08c4cdd8fed51f
Java
sealzjh/pay
/src/main/java/com/dada/pay/service/CardService.java
UTF-8
3,308
2.359375
2
[ "Apache-2.0" ]
permissive
package com.dada.pay.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dada.pay.core.BaseService; import com.dada.pay.dao.PayCardDao; import com.dada.pay.model.PayCardModel; @Service public class CardService extends BaseService{ @Autowired private PayCardDao _PayCardDao; public int saveCard(int accountId ,String accountName , String accountCard , int accountTypeId, int payBankId , int payCityId , String payCityName , int paySubbankId , String paySubbankName) { PayCardModel card = new PayCardModel(); card.setAccountId(accountId); card.setAccountName(accountName); card.setAccountCard(accountCard); card.setAccountTypeId(accountTypeId); card.setPayBankId(payBankId); card.setPayCityId(payCityId); card.setPayCityName(payCityName); card.setPaySubbankId(paySubbankId); card.setPaySubbankName(paySubbankName); return _PayCardDao.save(card); } public void deleteCard(int cardId) { PayCardModel card = _PayCardDao.getById(cardId); _PayCardDao.delete(card); } public void setDefault(int accountId , int cardId) { List <PayCardModel> list = (List<PayCardModel>) _PayCardDao.getDefaultCard(accountId); for(PayCardModel item:list) { item.setIsDefault(0); _PayCardDao.update(item); } PayCardModel card = _PayCardDao.getById(cardId); card.setIsDefault(1); _PayCardDao.update(card); } public List<Map <String , Object>> getAccountCard(int accountId) { List <PayCardModel> list = (List<PayCardModel>) _PayCardDao.getAccountCard(accountId); List <Map <String , Object>> rs = new ArrayList<Map <String , Object>>(); for(PayCardModel item:list) { Map <String , Object> data = new HashMap<String , Object> (); data.put("cardId", item.getCardId()); data.put("accountId" , item.getAccountId()); data.put("accountName", item.getAccountName()); data.put("accountCard", item.getAccountCard()); data.put("accountTypeId", item.getAccountTypeId()); data.put("payBankId", item.getPayBankId()); data.put("payCityId", item.getPayCityId()); data.put("payCityName", item.getPayCityName()); data.put("paySubbankId", item.getPaySubbankId()); data.put("paySubbankName", item.getPaySubbankName()); data.put("isDefault" , item.getIsDefault()); rs.add(data); } return rs; } public Map <String , Object> getDefaultCard(int accountId) { List <PayCardModel> list = (List<PayCardModel>) _PayCardDao.getDefaultCard(accountId); Map <String , Object> data = new HashMap<String , Object> (); for(PayCardModel item:list) { data.put("cardId", item.getCardId()); data.put("accountId" , item.getAccountId()); data.put("accountName", item.getAccountName()); data.put("accountCard", item.getAccountCard()); data.put("accountTypeId", item.getAccountTypeId()); data.put("payBankId", item.getPayBankId()); data.put("payCityId", item.getPayCityId()); data.put("payCityName", item.getPayCityName()); data.put("paySubbankId", item.getPaySubbankId()); data.put("paySubbankName", item.getPaySubbankName()); data.put("isDefault", item.getIsDefault()); } return data; } }
true
999144a307bed43be74a5020ce813dbff7fb77ce
Java
Almnir/MosquitoService
/src/main/java/HelloWorld.java
UTF-8
1,233
2.53125
3
[]
no_license
import java.util.HashMap; import java.util.Map; import static spark.Spark.*; public class HelloWorld { private static Map<String, String> usernamePasswords = new HashMap<String, String>(); public static void main(String[] args) { usernamePasswords.put("foo", "bar"); usernamePasswords.put("admin", "admin"); staticFileLocation("/public"); get("/", (req, res) -> "Я у мамки программист!"); get("/users/:name", (request, response) -> "Привет, " + request.params(":name")); before("/hello", (request, response) -> { String user = request.queryParams("user"); String password = request.queryParams("password"); String dbPassword = usernamePasswords.get(user); if (!(password != null && password.equals(dbPassword))) { halt(401, "Вам здесь не рады!!!"); } }); before("/hello", (request, response) -> response.header("Foo", "Set by second before filter")); get("/hello", (req, res) -> "Кулхацкир привет!"); after("/hello", (request, response) -> response.header("spark", "added by after-filter")); } }
true
229af8deaa36b387aab722eff10c77a05f7f5036
Java
iantal/AndroidPermissions
/apks/comparison_qark/de.number26.android/classes_dex2jar/b/a/a/a/b/b/t.java
UTF-8
3,211
2.125
2
[ "Apache-2.0" ]
permissive
package b.a.a.a.b.b; import b.a.a.a.b.a.j; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; public abstract class t<E> extends AbstractCollection<E> implements Serializable { private transient x<E> a; t() {} int a(Object[] paramArrayOfObject, int paramInt) { Iterator localIterator = iterator(); while (localIterator.hasNext()) { Object localObject = localIterator.next(); int i = paramInt + 1; paramArrayOfObject[paramInt] = localObject; paramInt = i; } return paramInt; } public abstract bt<E> a(); @Deprecated public final boolean add(E paramE) { throw new UnsupportedOperationException(); } @Deprecated public final boolean addAll(Collection<? extends E> paramCollection) { throw new UnsupportedOperationException(); } @Deprecated public final void clear() { throw new UnsupportedOperationException(); } public abstract boolean contains(Object paramObject); abstract boolean e(); public x<E> f() { x localX = this.a; if (localX == null) { localX = g(); this.a = localX; } return localX; } x<E> g() { switch (size()) { default: return new bb(this, toArray()); case 1: return x.a(a().next()); } return x.c(); } @Deprecated public final boolean remove(Object paramObject) { throw new UnsupportedOperationException(); } @Deprecated public final boolean removeAll(Collection<?> paramCollection) { throw new UnsupportedOperationException(); } @Deprecated public final boolean retainAll(Collection<?> paramCollection) { throw new UnsupportedOperationException(); } public final Object[] toArray() { int i = size(); if (i == 0) { return ax.a; } Object[] arrayOfObject = new Object[i]; a(arrayOfObject, 0); return arrayOfObject; } public final <T> T[] toArray(T[] paramArrayOfT) { j.a(paramArrayOfT); int i = size(); if (paramArrayOfT.length < i) { paramArrayOfT = ax.a(paramArrayOfT, i); } else if (paramArrayOfT.length > i) { paramArrayOfT[i] = null; } a(paramArrayOfT, 0); return paramArrayOfT; } public static abstract class b<E> { b() {} static int a(int paramInt1, int paramInt2) { if (paramInt2 < 0) { throw new AssertionError("cannot store more than MAX_VALUE elements"); } int i = 1 + (paramInt1 + (paramInt1 >> 1)); if (i < paramInt2) { i = Integer.highestOneBit(paramInt2 - 1) << 1; } if (i < 0) { i = Integer.MAX_VALUE; } return i; } public b<E> a(Iterable<? extends E> paramIterable) { Iterator localIterator = paramIterable.iterator(); while (localIterator.hasNext()) { b(localIterator.next()); } return this; } public b<E> a(Iterator<? extends E> paramIterator) { while (paramIterator.hasNext()) { b(paramIterator.next()); } return this; } public abstract b<E> b(E paramE); } }
true
9a20964d4e9cec86c99a42cc96fe7b3fb5ef4da9
Java
xujing52/security-demo
/src/main/java/com/example/securitydemo/model/Operation.java
UTF-8
928
2.078125
2
[]
no_license
package com.example.securitydemo.model; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; @Entity @Data @ToString @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor @Table(name = "operation") public class Operation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String url; private String code; private String remark; //急加载 会查询authority表 @ManyToMany(mappedBy = "operations",fetch = FetchType.LAZY) private List<Authority> authorities; }
true