text stringlengths 10 2.72M |
|---|
package com.steveq.settingspage.ui.activities;
import android.app.Fragment;
import android.content.Context;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.Button;
import com.steveq.settingspage.R;
import com.steveq.settingspage.ui.fragments.Settings1Fragment;
import com.steveq.settingspage.ui.fragments.Settings2Fragment;
import com.steveq.settingspage.ui.fragments.Settings3Fragment;
import java.util.List;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// PreferenceManager.setDefaultValues(this, R.xml.preferences1, false);
// PreferenceManager.setDefaultValues(this, R.xml.preferences1, false);
/**
* code that set fixed settings page when it is called
* onBuildHeaders is not being called
* TODO: uncomment code below to set single page and not show list of settings headers
*/
// setContentView(R.layout.activity_settings);
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.contentFrame, new Settings1Fragment()).
// commit();
}
@Override
public void onBuildHeaders(List<Header> target) {
super.onBuildHeaders(target);
loadHeadersFromResource(R.xml.preference_headers, target);
}
@Override
protected boolean isValidFragment(String fragmentName) {
if(Settings1Fragment.class.getName().equals(fragmentName) ||
Settings2Fragment.class.getName().equals(fragmentName) ||
Settings3Fragment.class.getName().equals(fragmentName)){
return true;
}
return false;
}
}
|
package com.datatypes;
public class SubtractTwoInteger {
public static void main(String args[]) {
//variable declaration
int numberOne = 40;
int numberTwo = 24;
//temp variable
int subtraction = numberOne - numberTwo;
System.out.println("Subtraction of Two numbers: " + subtraction);
}
}
|
package c05;
public class a7
{
public static void main(String[] args)
{
/* 1. 변수를 생성하시오. */
int sam = 180;
int num = 3;
double sum = 0;
/* 2. 메소드를 통한 칼로리를 계산하시오. */
sum = cal_kcal(180, 3);
/* 3. 결과를 출력하시오 */
System.out.printf("삼겹살 %d인분: %.2f kcal", num, sum);
}
/* 4. 칼로리 계산을 위한 메소드를 작성하시오. */
public static double cal_kcal(int sam, int num)
{
// TODO Auto-generated method stub
double sam_kcal = 5.179;
double sum = 0;
sum = sam_kcal * (double)sam * (double)num;
return sum;
}
}
|
package com.example.demo.dao;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.query.N1qlQuery;
import com.couchbase.client.java.query.N1qlQueryResult;
import com.couchbase.client.java.query.N1qlQueryRow;
import com.couchbase.client.java.query.Statement;
import com.example.demo.model.Test;
import com.example.demo.utils.N1QL;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.couchbase.core.CouchbaseTemplate;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import static com.couchbase.client.java.query.Select.select;
import static com.couchbase.client.java.query.dsl.Expression.*;
@Service
public class CouchBaseDAO extends DAO {
final private Logger logger = LoggerFactory.getLogger(CouchBaseDAO.class);
private ObjectMapper objectMapper;
@Autowired
public CouchBaseDAO(CouchbaseTemplate couchbaseTemplate, ObjectMapper objectMapper) {
super(couchbaseTemplate);
this.objectMapper = objectMapper;
}
public List<Test> getTestData(String id) {
Statement statement = select("test.*")
.from(i("test"))
.where(x("`value`").eq(s(id)))
.limit(100);
N1qlQueryResult result = execute(statement);
return result.allRows().stream().map(item -> this.toModel(objectMapper, item, Test.class))
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
public void setCouchbaseTemplate(CouchbaseTemplate couchbaseTemplate) {
this.setTemplate(couchbaseTemplate);
}
}
|
package com.tencent.mm.plugin.card.ui;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.plugin.card.a;
import com.tencent.mm.plugin.card.a.c;
import com.tencent.mm.plugin.card.a.d;
import com.tencent.mm.plugin.card.a.g;
import com.tencent.mm.plugin.card.d.m;
import com.tencent.mm.plugin.card.model.am;
import com.tencent.mm.plugin.card.sharecard.a.b;
import com.tencent.mm.plugin.card.sharecard.model.l;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
public final class f {
private MMActivity gKS;
private ImageView[] hEA = new ImageView[3];
private ImageView hEB;
private int hEv;
private View hEw;
private TextView hEx;
private TextView hEy;
private ImageView hEz;
View hyK;
private b hzM;
public f(MMActivity mMActivity, View view, int i, b bVar) {
this.gKS = mMActivity;
this.hyK = view;
this.hEv = i;
this.hzM = bVar;
this.hEw = this.hyK.findViewById(d.card_home_page_item_layout);
this.hEx = (TextView) this.hyK.findViewById(d.card_home_page_item_title);
this.hEy = (TextView) this.hyK.findViewById(d.card_home_page_item_tips);
this.hEz = (ImageView) this.hyK.findViewById(d.card_home_page_item_type_icon);
this.hEA[0] = (ImageView) this.hyK.findViewById(d.card_home_page_item_icon_1);
this.hEA[1] = (ImageView) this.hyK.findViewById(d.card_home_page_item_icon_2);
this.hEA[2] = (ImageView) this.hyK.findViewById(d.card_home_page_item_icon_3);
this.hEB = (ImageView) this.hyK.findViewById(d.card_red_dot_img);
if (this.hEv == 1) {
this.hEx.setText(this.gKS.getString(g.card_member_card_count_title, new Object[]{Integer.valueOf(0)}));
this.hEz.setImageResource(com.tencent.mm.plugin.card.a.f.card_home_member_card_icon);
} else if (this.hEv == 2) {
this.hEx.setText(g.card_share_card_title);
this.hEz.setImageResource(com.tencent.mm.plugin.card.a.f.card_home_friend_ticket_icon);
} else if (this.hEv == 3) {
this.hEx.setText(g.card_ticket_title);
this.hEz.setImageResource(com.tencent.mm.plugin.card.a.f.card_home_my_ticket_icon);
}
}
public final void setOnClickListener(OnClickListener onClickListener) {
this.hEw.setOnClickListener(onClickListener);
}
public final void aL() {
if (this.hEv == 2) {
l lVar = (l) am.axn().getValue("key_share_card_layout_data");
if (lVar == null) {
x.w("MicroMsg.CardHomePageItemController", "updateShareCardView data is null");
return;
}
if (bi.oW(lVar.hyz)) {
this.hEy.setVisibility(8);
} else {
this.hEy.setVisibility(0);
this.hEy.setText(lVar.hyz);
}
if (bi.cX(lVar.hyy)) {
for (int i = 0; i < 3; i++) {
this.hEA[i].setVisibility(8);
}
} else {
for (int i2 = 0; i2 < 3; i2++) {
if (i2 < lVar.hyy.size()) {
this.hEA[i2].setVisibility(0);
m.a(this.hEA[i2], (String) lVar.hyy.get(i2), this.gKS.getResources().getDimensionPixelSize(a.b.LargerPadding), c.my_card_package_defaultlogo, false);
} else {
this.hEA[i2].setVisibility(8);
}
}
}
if (bi.cX(lVar.hyy) || lVar.hyy.size() != 1 || !lVar.cal || lVar.cam) {
this.hEB.setVisibility(8);
} else {
this.hEB.setVisibility(0);
}
} else if (this.hEv == 3) {
this.hEx.setText(g.card_ticket_title);
this.hyK.findViewById(d.card_home_page_item_extra_relative).setVisibility(8);
String str = (String) am.axn().getValue("key_card_entrance_tips");
if (bi.oW(str)) {
this.hEy.setVisibility(8);
return;
}
this.hEy.setText(str);
this.hEy.setVisibility(0);
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commercefacades.search.solrfacetsearch.converters.populator;
import de.hybris.platform.commercefacades.search.data.SearchFilterQueryData;
import de.hybris.platform.commercefacades.search.data.SearchQueryData;
import de.hybris.platform.commerceservices.search.solrfacetsearch.data.SolrSearchFilterQueryData;
import de.hybris.platform.commerceservices.search.solrfacetsearch.data.SolrSearchQueryData;
import de.hybris.platform.commerceservices.search.solrfacetsearch.data.SolrSearchQueryTermData;
import de.hybris.platform.converters.Populator;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/**
* Converter implementation for {@link de.hybris.platform.commercefacades.search.data.SearchQueryData} as source and
* {@link de.hybris.platform.commerceservices.search.solrfacetsearch.data.SolrSearchQueryData} as target type.
*/
public class SolrSearchQueryDecoderPopulator implements Populator<SearchQueryData, SolrSearchQueryData>
{
private static final Logger LOG = Logger.getLogger(SolrSearchQueryDecoderPopulator.class);
@Override
public void populate(final SearchQueryData source, final SolrSearchQueryData target)
{
if (source == null)
{
return;
}
if (StringUtils.isNotEmpty(source.getValue()))
{
final String[] split = source.getValue().split(":");
if (split.length > 0)
{
target.setFreeTextSearch(split[0]);
}
if (split.length > 1)
{
target.setSort(split[1]);
}
final List<SolrSearchQueryTermData> terms = new ArrayList<SolrSearchQueryTermData>();
for (int i = 2; (i + 1) < split.length; i += 2)
{
final SolrSearchQueryTermData termData = new SolrSearchQueryTermData();
termData.setKey(split[i]);
try
{
termData.setValue(URLDecoder.decode(split[i + 1], "UTF-8"));
}
catch (final UnsupportedEncodingException e)
{
// UTF-8 is supported encoding, so it shouldn't come here
LOG.error("Solr search query URLdecoding failed.", e);
}
terms.add(termData);
}
target.setFilterTerms(terms);
}
target.setFilterQueries(createSolrSearchFilterQueries(source));
target.setSearchQueryContext(source.getSearchQueryContext());
}
protected List<SolrSearchFilterQueryData> createSolrSearchFilterQueries(final SearchQueryData source)
{
final List<SolrSearchFilterQueryData> solrSearchFilterQueries = new ArrayList();
if (CollectionUtils.isNotEmpty(source.getFilterQueries()))
{
for (final SearchFilterQueryData searchFilterQueryData : source.getFilterQueries())
{
final SolrSearchFilterQueryData solrSearchFilterQuery = new SolrSearchFilterQueryData();
solrSearchFilterQuery.setKey(searchFilterQueryData.getKey());
solrSearchFilterQuery.setValues(searchFilterQueryData.getValues());
solrSearchFilterQuery.setOperator(searchFilterQueryData.getOperator());
solrSearchFilterQueries.add(solrSearchFilterQuery);
}
}
return solrSearchFilterQueries;
}
}
|
package com.niit.designerswear;
public class PaymentController {
}
|
package abstra;
class build {
public build() {
System.out.println("hello sum");
}
void green() {
}
}
class prop extends build{
prop()
{
super();
}
void green() {
System.out.println("hello green");
}
}
public class buld {
public static void main(String args[]) {
prop p = new prop();
}
} |
package com.ssp.tp;
import java.io.FileNotFoundException;
import java.util.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
char[][] target = new char[n][m];
sc.nextLine();
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
for (int j = 0; j < m; j++) {
target[i][j] = str.charAt(j);
}
}
String a = sc.nextLine();
System.out.println(path(target, a, x, y, z));
}
public static long path(char[][] target, String a, int x, int y, int z){
long count = 0;
int row = target.length;
int col = target[0].length;
Map<Character, List<Integer>> map = new HashMap<>();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
List<Integer> temp = new ArrayList<>();
temp.add(i);
temp.add(j);
map.put(target[i][j], temp);
}
}
int p = 0;
int q = 0;
for (int i = 0; i < a.length(); i++) {
count += z;
char cur = a.charAt(i);
List<Integer> list = map.get(cur);
int curP = list.get(0);
int curQ = list.get(1);
if(curP == p || curQ == q){
count += (long) (Math.abs(p - curP) + Math.abs(q - curQ)) * x;
p = curP;
q = curQ;
}else{
count += (long) (Math.abs(p - curP) + Math.abs(q - curQ)) * x;
p = curP;
q = curQ;
count += y;
}
}
return count;
}
}
|
package com.kh.efp.member.model.service;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.kh.efp.member.model.dao.MemberDao;
import com.kh.efp.member.model.exception.LoginException;
import com.kh.efp.member.model.vo.Member;
import com.kh.efp.member.model.vo.Profile;
import com.kh.efp.member.model.vo.loginUser;
@Service
public class MemberserviceImpl implements MemberService {
@Autowired private SqlSessionTemplate sqlSession;
@Autowired private MemberDao md;
@Autowired private BCryptPasswordEncoder passwordEncoder;
@Override
public Member loginMember(Member m) throws LoginException {
Member loginUser = null;
String encPassword = md.selectEncPassword(sqlSession, m);
if(!passwordEncoder.matches(m.getmPwd(), encPassword)){
throw new LoginException("로그인 정보가 존재하지 않습니다");
}else{
loginUser = md.selectMember(sqlSession, m);
}
return loginUser;
}
@Override
public int checkmName(String mName) {
int ckVal = md.checkmName(sqlSession, mName);
return ckVal;
}
@Override
@Transactional
public int insertMember(Member m, Profile pf) {
int result = -99;
System.out.println("service m : " + m + " / pf : " + pf);
int result1 = md.insertMember(sqlSession, m);
int mid = md.selectMid(sqlSession, m);
pf.setMid(mid);
System.out.println(mid);
System.out.println("pf : " + pf);
int result2 = md.insertMemberProfile(sqlSession, pf); //여기서 에러
System.out.println(result2);
if(result1 > 0 && result2 > 0){
result = 1;
}else{
result = 0;
}
return result;
}
@Override
public Profile selectMemberProfile(int mid) {
Profile pf = md.selectMemberProfile(sqlSession, mid);
return pf;
}
@Override
public int insertChangedProfile(Profile pf) {
return md.insertChangedProfile(sqlSession, pf);
}
@Override
public Member selectMember(Member m) {
// TODO Auto-generated method stub
return md.selectMember(sqlSession, m);
}
@Override
public int selectmPhone(String mPhone) {
// TODO Auto-generated method stub
return md.selectmPhone(sqlSession, mPhone);
}
@Override
public int selectCntEmail(String mEmail) {
return md.selectCntEmail(sqlSession, mEmail);
}
@Override
public String selectmEmail(Member m) {
return md.selectmEmail(sqlSession, m);
}
@Override
public int updatemEmailmPwd(Member m) {
// TODO Auto-generated method stub
return md.updatemEmailmPwd(sqlSession, m);
}
@Override
public int selectAuthmEmail(Member m) {
// TODO Auto-generated method stub
return md.selectAuthmEmail(sqlSession, m);
}
@Override
public int updatemStatus(int imid) {
// TODO Auto-generated method stub
return md.updatemStatus(sqlSession, imid);
}
@Override
public loginUser loginMember2(Member m) throws LoginException {
loginUser loginUser = null;
Member member = null;
String encPassword = md.selectEncPassword(sqlSession, m);
if(!passwordEncoder.matches(m.getmPwd(), encPassword)){
throw new LoginException("로그인 정보가 존재하지 않습니다");
}else{
member = md.selectMember(sqlSession, m);
m.setMid(member.getMid());
loginUser = md.selectLoginUser(sqlSession, m);
}
return loginUser;
}
@Override
public void selectPwd(int mid, String nowPwd, String newPwd) throws LoginException {
Member m = new Member();
m.setMid(mid);
String encPassword = md.selectEncPassword(sqlSession, m);
if(!passwordEncoder.matches(nowPwd, encPassword)){
throw new LoginException("비밀번호가 일치하지 않습니다.");
}else{
m.setmPwd(passwordEncoder.encode(newPwd));
int result = md.updateMidmPwd(sqlSession, m);
if(result <= 0){
throw new LoginException("비밀번호 수정에 실패했습니다.");
}
}
}
@Override
public void selectInfo(Member m) throws LoginException {
String encPassword = md.selectEncPassword(sqlSession, m);
if(!passwordEncoder.matches(m.getmPwd(), encPassword)){
throw new LoginException("비밀번호가 일치하지 않습니다.");
}else{
int result = md.updateInfo(sqlSession, m);
if(result <= 0){
throw new LoginException("회원정보 수정에 실패했습니다.");
}
}
}
}
|
package category.binaryBearch;
import java.util.Arrays;
public class BinarySearch {
public static int triangleNumber(int[] arr) {
if(arr == null || arr.length < 3) return 0;
Arrays.sort(arr);
int res = 0;
for(int i = 0; i < arr.length - 2; i++) {
for(int j = i + 1; j < arr.length - 1; j++) {
// find the last index that arr[index] < arr[i] + arr[j]
int target = arr[j] + arr[i];
int start = j + 1, end = arr.length - 1;
while(start < end) {
int mid = start + (end - start) / 2;
if(arr[mid] >= target) {
end = mid - 1;
} else {
start = mid + 1;
}
}
res += - j + (arr[start] < target ? start : start - 1);
}
}
return res;
}
public static void main(String[] args) {
System.out.println(triangleNumber(new int[]{2,2,3,4}));
}
}
|
package model;
import java.util.Date;
public class Employee_Working {
private String EMPLOYMENT_ID;
private Date HIRE_DATE_FOR_WORKING;
private String WORKERS_COMP_CODE;
private Date TERMINATION_DATE;
private Date REHIRE_DATE_FOR_WORKING;
private Date LAST_REVIEW_DATE;
private int NUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH;
private int NUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH;
private int TOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH;
public Employee_Working() {
super();
// TODO Auto-generated constructor stub
}
public Employee_Working(String eMPLOYMENT_ID, Date hIRE_DATE_FOR_WORKING, String wORKERS_COMP_CODE,
Date tERMINATION_DATE, Date rEHIRE_DATE_FOR_WORKING, Date lAST_REVIEW_DATE,
int nUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH, int nUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH,
int tOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH) {
super();
EMPLOYMENT_ID = eMPLOYMENT_ID;
HIRE_DATE_FOR_WORKING = hIRE_DATE_FOR_WORKING;
WORKERS_COMP_CODE = wORKERS_COMP_CODE;
TERMINATION_DATE = tERMINATION_DATE;
REHIRE_DATE_FOR_WORKING = rEHIRE_DATE_FOR_WORKING;
LAST_REVIEW_DATE = lAST_REVIEW_DATE;
NUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH = nUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH;
NUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH = nUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH;
TOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH = tOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH;
}
public String getEMPLOYMENT_ID() {
return EMPLOYMENT_ID;
}
public void setEMPLOYMENT_ID(String eMPLOYMENT_ID) {
EMPLOYMENT_ID = eMPLOYMENT_ID;
}
public Date getHIRE_DATE_FOR_WORKING() {
return HIRE_DATE_FOR_WORKING;
}
public void setHIRE_DATE_FOR_WORKING(Date hIRE_DATE_FOR_WORKING) {
HIRE_DATE_FOR_WORKING = hIRE_DATE_FOR_WORKING;
}
public String getWORKERS_COMP_CODE() {
return WORKERS_COMP_CODE;
}
public void setWORKERS_COMP_CODE(String wORKERS_COMP_CODE) {
WORKERS_COMP_CODE = wORKERS_COMP_CODE;
}
public Date getTERMINATION_DATE() {
return TERMINATION_DATE;
}
public void setTERMINATION_DATE(Date tERMINATION_DATE) {
TERMINATION_DATE = tERMINATION_DATE;
}
public Date getREHIRE_DATE_FOR_WORKING() {
return REHIRE_DATE_FOR_WORKING;
}
public void setREHIRE_DATE_FOR_WORKING(Date rEHIRE_DATE_FOR_WORKING) {
REHIRE_DATE_FOR_WORKING = rEHIRE_DATE_FOR_WORKING;
}
public Date getLAST_REVIEW_DATE() {
return LAST_REVIEW_DATE;
}
public void setLAST_REVIEW_DATE(Date lAST_REVIEW_DATE) {
LAST_REVIEW_DATE = lAST_REVIEW_DATE;
}
public int getNUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH() {
return NUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH;
}
public void setNUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH(int nUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH) {
NUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH = nUMBER_DAYS_REQUIREMENT_OF_WORKING_PER_MONTH;
}
public int getNUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH() {
return NUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH;
}
public void setNUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH(int nUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH) {
NUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH = nUMBER_DAYS_ACTUAL_OF_WORKING_PER_MONTH;
}
public int getTOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH() {
return TOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH;
}
public void setTOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH(int tOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH) {
TOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH = tOTAL_NUMBER_VACATION_WORKING_DAYS_PER_MONTH;
}
}
|
package vfc.domain;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int commentId;
private String comment;
@ManyToOne(targetEntity = Event.class)
@JoinColumn(name="event_id")
private Event event;
public Comment() {
}
public int getCommentId() {
return commentId;
}
public void setCommentId(int commentId) {
this.commentId = commentId;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
|
package com.jlgproject.util;
import com.jlgproject.App;
import com.jlgproject.model.Login_zud;
/**
* @author 王锋 on 2017/7/21.
*/
public class UserInfoState {
/**
* 判断用户登录状态
*
* @return
*/
public static boolean isLogin() {
Login_zud login_zud = (Login_zud) SharedUtil.getSharedUtil().getObject(App.getContext(), ConstUtils.IOGIN_INFO, null);
if (login_zud != null) {
return true;
}
return false;
}
/**返回用户Token
*
* @return 用户token
*/
public static String getToken() {
String token = null;
if (isLogin()) {
Login_zud login_zud = (Login_zud) SharedUtil.getSharedUtil().getObject(App.getContext(), ConstUtils.IOGIN_INFO, null);
token = login_zud.getData().getToken();
}
return token;
}
/**给用户身份状态值重新赋值
*
* @param newUserType
*/
public static void setUserType(int newUserType) {
int user_Type = SharedUtil.getSharedUtil().getInt(App.getContext(), ConstUtils.USER_TYPE);
if (user_Type != 0) {
SharedUtil.getSharedUtil().remove(App.getContext(), ConstUtils.USER_TYPE);
SharedUtil.getSharedUtil().putInt(App.getContext(), ConstUtils.USER_TYPE,newUserType);
L.e("-----------删除并存储成功--------------");
}else{
SharedUtil.getSharedUtil().putInt(App.getContext(), ConstUtils.USER_TYPE,newUserType);
L.e("-----------存储成功--------------");
}
}
/**
* 返回用户身份状态值
* @return
*/
public static int getUserType(){
int user_Type = SharedUtil.getSharedUtil().getInt(App.getContext(), ConstUtils.USER_TYPE);
if(user_Type==0){
return 0;
}
return user_Type;
}
public static void setUserPhone(String phone) {
String user_Type = SharedUtil.getSharedUtil().getString(App.getContext(), ConstUtils.USER_PHONE);
if (user_Type==null) {
SharedUtil.getSharedUtil().remove(App.getContext(), ConstUtils.USER_PHONE);
SharedUtil.getSharedUtil().putString(App.getContext(), ConstUtils.USER_PHONE,phone);
L.e("-----------删除并存储成功--------------");
}else{
SharedUtil.getSharedUtil().putString(App.getContext(), ConstUtils.USER_PHONE,phone);
L.e("-----------存储成功--------------");
}
}
/**
* 返回用户手机号
* @return
*/
public static String getUserPhone(){
String phone = SharedUtil.getSharedUtil().getString(App.getContext(), ConstUtils.USER_PHONE);
if(phone==null){
return null;
}
return phone;
}
/**给用户设置hangtype
*
* @param newUserType
*/
public static void setHangType(int newUserType) {
int user_Type = SharedUtil.getSharedUtil().getInt(App.getContext(), ConstUtils.HANG_TYPE);
if (user_Type != 0) {
SharedUtil.getSharedUtil().remove(App.getContext(), ConstUtils.HANG_TYPE);
SharedUtil.getSharedUtil().putInt(App.getContext(), ConstUtils.HANG_TYPE,newUserType);
L.e("-----------删除并存储成功--------------");
}else{
SharedUtil.getSharedUtil().putInt(App.getContext(), ConstUtils.HANG_TYPE,newUserType);
L.e("-----------存储成功--------------");
}
}
/**
* 返回用户hangtype
* @return
*/
public static int getHangType(){
int hangType = SharedUtil.getSharedUtil().getInt(App.getContext(), ConstUtils.HANG_TYPE);
if(hangType==0){
return 0;
}
return hangType;
}
public static boolean getUser_type(){
int index=UserInfoState.getUserType();
if(index==2 || index ==3){
return true;
}
return false;
}
}
|
public class MathClass {
//All methods in the Math class are static.
//You can't create or extend an instance of the Math class.
public static void main(String[] args) {
//Math.abs -> função modular, retorna o mesmo tipo
System.out.println(Math.abs(-3.2));
//Math.pow -> retorna double
System.out.println(Math.pow(3, 2.0));
//Math.sqrt -> retorns double
System.out.println(Math.sqrt(9));
//Math.PI -> a public variable (doube ≃ pi) -> n é método()
int raio = 3;
double circunferencia = 2 * Math.PI * raio;
System.out.println(Math.round(circunferencia));
/* Outros Métodos importantes:
*
* Math.cos()
* Math.sin()
* Math.tan()
* Math.log()
* Math.max() -> return max of 2 values
* Math.min() -> return min of 2 values
* Math.round() -> returns a rounded number
*/
}
} |
//Author: Timothy van der Graaff
package utilities;
import java.util.Random;
public class Security_Code_Generator {
public static String entire_string;
public static int number_of_characters;
//Randomly choose a string position each time this
//method is called;
private static int get_random_string_position() {
int random_string_position;
Random random_generator = new Random();
random_string_position = random_generator.nextInt(entire_string.length());
if (random_string_position - 1 == -1) {
return random_string_position;
} else {
return random_string_position - 1;
}
}
public static String generate_hash() {
int string_position;
char this_character;
StringBuilder random_string = new StringBuilder();
//This loop executes a specified number of times,
//depending on the desired number of characters in the new string.
for (int i = 0; i < number_of_characters; i++) {
//The string position retrieves one character and
//adds it to the new string.
string_position = get_random_string_position();
this_character = entire_string.charAt(string_position);
random_string.append(this_character);
}
return random_string.toString();
}
}
|
package com.bsa.bsa_giphy.service;
import com.bsa.bsa_giphy.dto.Gif;
import com.bsa.bsa_giphy.exception.DataNotFoundException;
import com.bsa.bsa_giphy.exception.FileProcessingException;
import com.bsa.bsa_giphy.repository.GifsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
@Service
public class CacheOperationService {
private final GifsRepository gifsRepository;
@Value("${app.cache.dir}")
private String cache;
@Value("${app.users.dir}")
private String users;
@Autowired
public CacheOperationService(GifsRepository gifsRepository) {
this.gifsRepository = gifsRepository;
}
public void deleteUserCacheFromDisk(String userId) {
Path dirPath = Path.of(users + userId + "/");
if(!Files.exists(dirPath)) {
throw new DataNotFoundException();
}
deleteDirectory(dirPath);
}
public void deleteCacheFromMemory(String userId) {
gifsRepository.deleteByUser(userId);
}
public void deleteCacheFromMemoryByQuery(String userId, String query) {
gifsRepository.deleteByQuery(userId, query);
}
public void deleteAllCacheFromDisk() throws FileProcessingException {
final Path cachePath = Path.of(cache);
if(Files.exists(cachePath)) {
deleteDirectory(cachePath);
}
if(!Files.exists(cachePath)) {
createDirectoriesIfNotExist(cachePath);
}
}
private void deleteDirectory(Path dirPath) {
try {
if(Files.exists(dirPath)) {
Files.walk(dirPath)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
}
} catch (IOException e) {
throw new FileProcessingException("Could not delete folder");
}
}
public List<Gif> getCacheFromDisk(String query) {
if(query == null) {
return listAll();
}
File dir = new File(cache + query);
return listFilesInDirectory(dir);
}
public List<Gif> listAll() {
List<Gif> result = new ArrayList<>();
File cacheDir = new File(cache);
File[] dirs = cacheDir.listFiles();
if(dirs == null || dirs.length == 0) {
throw new DataNotFoundException();
}
for(File dir : dirs) {
result.addAll(listFilesInDirectory(dir));
}
return result;
}
public List<Path> listAllFilesPaths() {
List<Path> result = new ArrayList<>();
File cacheDir = new File(cache);
File[] dirs = cacheDir.listFiles();
if(dirs == null || dirs.length == 0) {
throw new DataNotFoundException();
}
for(File dir : dirs) {
var files = dir.listFiles();
if(files == null || files.length == 0) {
throw new DataNotFoundException();
}
for(File file : files) {
result.add(file.toPath());
}
}
return result;
}
public List<Gif> listFilesInDirectory(File dir) {
List<Gif> result = new ArrayList<>();
File[] files = dir.listFiles();
if(files == null) {
throw new DataNotFoundException();
}
String query = dir.getName();
Gif gif = new Gif(query);
for(File file : files) {
gif.getGifs().add(file.toPath());
}
result.add(gif);
return result;
}
public Path writeToUsersDir(String userId, String query,
Path cacheFilePath, String fileName) {
try {
Path usersDirPath = Path.of(users + userId + "/" + query);
createDirectoriesIfNotExist(
Path.of(users),
Path.of(users + userId),
usersDirPath
);
if (!Files.exists(Path.of(usersDirPath + "/" + fileName))) {
Files.copy(cacheFilePath, Path.of(usersDirPath + "/" + fileName));
}
return Path.of(usersDirPath + "/" + fileName);
} catch (IOException e) {
throw new FileProcessingException("Could not update users cache");
}
}
public void writeHistoryToCsv(String userId, String query, Path filePath) {
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date(System.currentTimeMillis());
String currDate = formatter.format(date);
createDirectoriesIfNotExist(
Path.of(users),
Path.of(users + userId)
);
File csvOutputFile = new File(users + userId + "/" + "history.csv");
FileWriter fw = new FileWriter(csvOutputFile, true);
fw.write(currDate + "," + query + ","
+ filePath.toAbsolutePath() + "\n");
fw.close();
} catch (IOException e) {
throw new FileProcessingException("Could not add record to users history");
}
}
public void createDirectoriesIfNotExist(Path ... dirPaths) {
try {
for(Path dirPath : dirPaths) {
if (!Files.exists(dirPath)) {
Files.createDirectory(dirPath);
}
}
} catch (IOException e) {
throw new FileProcessingException("Unable to create a directory");
}
}
}
|
package com.passing.struts.vo;
/**
* FrequencyVo class
* @author weishijie
*
*/
public class FrequencyVo {
private int wordId;
private String word;
private int frequency;
public FrequencyVo(int wordId, String word, int frequency) {
super();
this.wordId = wordId;
this.word = word;
this.frequency = frequency;
}
public int getWordId() {
return wordId;
}
public void setWordId(int wordId) {
this.wordId = wordId;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
}
|
package jp.co.nttdata.rate.util;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
/**
* Performs basic variable interpolation on a String for variables within
* a Map. Variables of the form, ${var}, are supported.
*
* @author Ken Fitzpatrick
* @author Henri Yandell
*/
@SuppressWarnings("unused")
public class Interpolation {
// QUERY: Anyway to escape the ${..} variable so it is not interpolated?
private static final String SYMBOLIC_VALUE_MARKER_START = "${";
private static final String SYMBOLIC_VALUE_MARKER_END = "}";
/**
* <p>
* Returns a String that is the result of having performed
* variable interpolation on <code>templateString</code>,
* using the value set found in <code>values</code>.
* </p>
* <p>
* The solution is compatible with all JDK versions
* where Jakarta/Commons/Lang also is supported.
* </p>
* <p>
* The expected format of <code>templateString</code> is:
*<code><pre>
* The ${animal} jumped over the ${target}.
*</pre></code>
* such that the key/value pairs found in <code>values</code>
* are substituted into the string at the <code>${key-name}</code> markers.
* In the above example, <code>valuesMap</code> could have been populated as:
*<code><pre>
* Map valuesMap = HashMap();
* valuesMap.put( "animal", "quick brown fox" );
* valuesMap.put( "target", "lazy dog" );
* String resolvedString = StringUtils.interpolate( templateString, valuesMap );
*</pre></code>
* yielding:
*<code><pre>
* The quick brown fox jumped over the lazy dog.
*</pre></code>
* </p>
* <p>
* The same <code>templateString</code> from the above example could be reused as:
*<code><pre>
* Map valuesMap = HashMap();
* valuesMap.put( "animal", "cow" );
* valuesMap.put( "target", "moon" );
* String resolvedString = StringUtils.interpolate( templateString, valuesMap );
*</pre></code>
* yielding:
*<code><pre>
* The cow jumped over the moon.
*</pre></code>
* </p>
* <p>
* The value of <code>templateString</code> is returned in an unaltered if <code>templateString</code>
* is null, empty, or contains no marked variables that can be resolved by the key/value pairs found in
* <code>valuesMap</code>, or if <code>valuesMap</code> is null, empty or has no key/value pairs that can be
* applied to the marked variables within <code>templateString</code>.
* </p>
* @param templateString String containing any mixture of variable and non-variable
* content, to be used as a template for the value substitution process
* @param valuesMap Map containing the key/value pairs to be used to resolve
* the values of the marked variables found within <code>templateString</code>
* @return String
*/
@SuppressWarnings("unchecked")
public static String interpolate( String templateString, Map valuesMap ) {
//TODO このメソッドは性能向上できる?
// pre-conditions
if ( valuesMap == null )
return templateString;
if ( templateString == null )
return templateString;
if ( templateString.length() < 1 )
return templateString;
if ( valuesMap.isEmpty() )
return templateString;
// default the returned String to the templateString
String returnString = templateString;
String nextKey = null;
Object substitutionBean = null;
String substitutionValue = null;
String nextValueToBeSubstituted = null;
// get a list of substitution valuesMap
Iterator keys = valuesMap.keySet().iterator();
while( keys.hasNext() ) {
nextKey = ( String ) keys.next();
//TODO ConvertUtil.convert?
substitutionValue = StringUtils.defaultString( String.valueOf(valuesMap.get( nextKey )) );
nextValueToBeSubstituted = SYMBOLIC_VALUE_MARKER_START + nextKey + SYMBOLIC_VALUE_MARKER_END;
returnString = StringUtils.replace( returnString, nextValueToBeSubstituted, substitutionValue );
}
return returnString;
}
/**
* <p>
* Returns a String that is the result of having performed variable interpolation on
* <code>templateString</code>, using the value set found in <code>values</code>,
* repeatedly until there are no changes.
* </p>
* <p>
* The expected format of <code>templateString</code> is:
*<code><pre>
* The ${animal} jumped over the ${target}.
*</pre></code>
* such that the key/value pairs found in <code>values</code> are substituted into the string at the
* <code>${key-name}</code> markers. In the above example, <code>valuesMap</code>
* could have been populated as:
*<code><pre>
* Map valuesMap = HashMap();
* valuesMap.put( "animal", "${critter}" );
* valuesMap.put( "target", "${pet}" );
* valuesMap.put( "pet", "${petCharacteristic} dog" );
* valuesMap.put( "petCharacteristic", "lazy" );
* valuesMap.put( "critter", "${critterSpeed} ${critterColor} ${critterType}" );
* valuesMap.put( "critterSpeed", "quick" );
* valuesMap.put( "critterColor", "brown" );
* valuesMap.put( "critterType", "fox" );
* String resolvedString = StringUtils.interpolate( templateString, valuesMap, true );
*</pre></code>
* yielding:
*<code><pre>
* The quick brown fox jumped over the lazy dog.
*</pre></code>
* </p>
* yielding:
*<code><pre>
* The cow jumped over the moon.
*</pre></code>
* </p>
* <p>
* The value of <code>templateString</code> is returned in an unaltered form if
* <code>templateString</code> is null, empty, or
* contains no marked variables that can be resolved by the key/value pairs found in
* <code>valuesMap</code>, or if <code>valuesMap</code> is null, empty or has no key/value
* pairs that can be applied to the marked variables within <code>templateString</code>.
* </p>
* @param templateString String containing any mixture of variable and non-variable
* content, to be used as a template for the value substitution process
* @param valuesMap Map containing the key/value pairs to be used to resolve
* the values of the marked variables found within <code>templateString</code>
* @return String
*/
@SuppressWarnings("unchecked")
public static String interpolateRepeatedly(
String templateString,
Map valuesMap)
{
// pre-conditions
if ( valuesMap == null )
return templateString;
if ( templateString == null )
return templateString;
if ( templateString.length() < 1 )
return templateString;
if ( valuesMap.isEmpty() )
return templateString;
String currentResult = templateString;
String previousResult = null;
while( ! StringUtils.equals( currentResult, previousResult ) )
{
previousResult = currentResult;
currentResult = Interpolation.interpolate( previousResult, valuesMap );
}
return currentResult;
}
}
|
package com.hesoyam.pharmacy.pharmacy.repository;
import com.hesoyam.pharmacy.pharmacy.model.OrderItem;
import org.springframework.data.jpa.repository.JpaRepository;
public interface OrderItemRepository extends JpaRepository<OrderItem, Long> {
}
|
package woc.assignment.one;
import java.util.Scanner;
public class WordPalin {
public static void main(String[] args) {
Scanner scObj = new Scanner(System.in);
System.out.print("Enter String : ");
String str = scObj.next();
if(strRev(str).equals(str)){
System.out.print("Pallindrome ");
return;
}
System.out.print("Not Pallindrome ");
}
public static String strRev(String param){
char[] chArr = param.toCharArray();
String rev = "";
for(int i = chArr.length-1; i>=0 ;i--){
rev += chArr[i];
}
return rev;
}
}
|
package it.polito.tdp.crimes.model;
public class Arco {
private String of1;
private String of2;
private int peso;
public Arco(String of1, String of2, int peso) {
super();
this.of1 = of1;
this.of2 = of2;
this.peso = peso;
}
public String getOf1() {
return of1;
}
public void setOf1(String of1) {
this.of1 = of1;
}
public String getOf2() {
return of2;
}
public void setOf2(String of2) {
this.of2 = of2;
}
public int getPeso() {
return peso;
}
public void setPeso(int peso) {
this.peso = peso;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((of1 == null) ? 0 : of1.hashCode());
result = prime * result + ((of2 == null) ? 0 : of2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Arco other = (Arco) obj;
if (of1 == null) {
if (other.of1 != null)
return false;
} else if (!of1.equals(other.of1))
return false;
if (of2 == null) {
if (other.of2 != null)
return false;
} else if (!of2.equals(other.of2))
return false;
return true;
}
}
|
package com.milos.domain.worker;
import com.milos.domain.MessageStats;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.concurrent.BlockingQueue;
/**
* StatsWorker polls message stats form source queue,
* formats the data to a readable string and sends it to
* console output stream.
*/
public class StatsWorker implements Runnable {
private BlockingQueue<MessageStats> sourceQueue;
private PrintWriter outputStream;
public StatsWorker(final BlockingQueue<MessageStats> sourceQueue, final OutputStream outputStream) {
this.sourceQueue = sourceQueue;
this.outputStream = new PrintWriter(outputStream, true);
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
MessageStats stats = sourceQueue.poll();
if (stats == null) {
continue;
}
String content = new StringBuilder()
.append("message: ").append(stats.getMessageId()).append("; ")
.append("duration: ").append(stats.getProcessDurationInMillis()).append(" ms ; ")
.append("avg: ").append(stats.getCapturedAvgDurationInMillis()).append(" ms").toString();
outputStream.println(content);
}
}
}
|
package com.pellcorp.android.isohunt;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PageResults implements Serializable {
private List<Result> searchResults = new ArrayList<Result>();
private int currentPage = 0;
private int numberOfPages = 0;
public PageResults() {
}
void addResult(Result result) {
searchResults.add(result);
}
public int getCurrentPage() {
return currentPage;
}
void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getNumberOfPages() {
return numberOfPages;
}
void setNumberOfPages(int numberOfPages) {
this.numberOfPages = numberOfPages;
}
public List<Result> getSearchResults() {
return Collections.unmodifiableList(searchResults);
}
}
|
package com.findme.service;
import com.findme.exception.BadRequestException;
import com.findme.exception.InternalServerError;
import com.findme.types.RelationshipStatus;
public interface RelationshipService {
RelationshipStatus getRelationshipStatus(String userFromId, String userToId) throws InternalServerError, BadRequestException;
void saveRelationship(String userFromId, String userToId) throws InternalServerError, BadRequestException;
void updateRelationship(String userFromId, String userToId, String status) throws InternalServerError, BadRequestException;
}
|
package com.mfm_app.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.mfm_app.entities.SecondaryBodypartList;
@Repository
public interface SecondaryBodypartRepository extends JpaRepository<SecondaryBodypartList, String> {
}
|
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) throws ClassNotFoundException {
String message = "리플렉션이 뭐예요???";
//Class cls = message.getClass();
Class cls = Class.forName("java.lang.String");
String className = cls.getName();
System.out.println(className);
Method[] methodList = cls.getMethods();
for (Method method : methodList) {
// System.out.println(method.getName());
// System.out.println(method);
// System.out.println(method);
// System.out.println(method.getModifiers());
// System.out.println(method.getModifiers() == Method.PUBLIC);
Class[] params = method.getParameterTypes();
if(params != null) {
for (Class paramType : params) {
System.out.print(method.getName() + paramType.getName() + ",");
}
}
}
}
}
|
package com.hb.rssai.view.me;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hb.rssai.R;
import com.hb.rssai.adapter.CollectionAdapter;
import com.hb.rssai.adapter.DialogAdapter;
import com.hb.rssai.base.BaseActivity;
import com.hb.rssai.bean.ResBase;
import com.hb.rssai.bean.ResCollection;
import com.hb.rssai.bean.ResInfo;
import com.hb.rssai.bean.UserCollection;
import com.hb.rssai.constants.Constant;
import com.hb.rssai.presenter.BasePresenter;
import com.hb.rssai.presenter.CollectionPresenter;
import com.hb.rssai.util.LiteOrmDBUtil;
import com.hb.rssai.util.SharedPreferencesUtil;
import com.hb.rssai.util.StringUtil;
import com.hb.rssai.util.T;
import com.hb.rssai.view.common.ContentActivity;
import com.hb.rssai.view.common.RichTextActivity;
import com.hb.rssai.view.iView.ICollectionView;
import com.hb.rssai.view.widget.FullListView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.ShareBoardConfig;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import me.drakeet.materialdialog.MaterialDialog;
public class CollectionActivity extends BaseActivity implements CollectionAdapter.onItemLongClickedListener, ICollectionView {
@BindView(R.id.sys_tv_title)
TextView mSysTvTitle;
@BindView(R.id.sys_toolbar)
Toolbar mSysToolbar;
@BindView(R.id.app_bar_layout)
AppBarLayout mAppBarLayout;
@BindView(R.id.coll_tv_empty)
TextView mCollTvEmpty;
@BindView(R.id.coll_ll)
LinearLayout mCollLl;
@BindView(R.id.coll_recycler_view)
RecyclerView mCollRecyclerView;
@BindView(R.id.coll_swipe_layout)
SwipeRefreshLayout mCollSwipeLayout;
@BindView(R.id.include_no_data)
View includeNoData;
@BindView(R.id.include_load_fail)
View includeLoadFail;
@BindView(R.id.llf_btn_re_try)
Button mLlfBtnReTry;
private LinearLayoutManager mLayoutManager;
private String collectionId = "";
private CollectionAdapter adapter;
private ResCollection.RetObjBean.RowsBean newRowsBean;
private List<ResCollection.RetObjBean.RowsBean> resCollections = new ArrayList<>();
private int pageNum = 1;
private boolean isEnd = false, isLoad = false;
private ResCollection.RetObjBean.RowsBean bean;
private String infoId = "";
private UMShareListener mShareListener;
private ShareAction mShareAction;
/**
* 取消对话框
*
* @return
*/
private DialogAdapter dialogAdapter;
private MaterialDialog materialDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((CollectionPresenter) mPresenter).getList();
}
@Override
protected void onRefresh() {
pageNum = 1;
isLoad = true;
isEnd = false;
mCollSwipeLayout.setRefreshing(true);
((CollectionPresenter) mPresenter).getList();
}
@Override
protected void loadMore() {
if (!isEnd && !isLoad) {
mCollSwipeLayout.setRefreshing(true);
pageNum++;
((CollectionPresenter) mPresenter).getList();
}
}
@Override
protected void initView() {
mLayoutManager = new LinearLayoutManager(this);
mCollRecyclerView.setLayoutManager(mLayoutManager);
mCollSwipeLayout.setColorSchemeResources(R.color.refresh_progress_1,
R.color.refresh_progress_2, R.color.refresh_progress_3);
mCollSwipeLayout.setProgressViewOffset(true, 0, (int) TypedValue
.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
mLlfBtnReTry.setOnClickListener(v -> onRefresh());
mCollSwipeLayout.setOnRefreshListener(() -> onRefresh());
//TODO 设置上拉加载更多
mCollRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
int lastVisibleItem;
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (adapter == null) {
isLoad = false;
mCollSwipeLayout.setRefreshing(false);
return;
}
// 在最后两条的时候就自动加载
if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 2 >= adapter.getItemCount()) {
// 加载更多
loadMore();
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
}
});
initShare();
}
private void initShare() {
mShareListener = new CustomShareListener(this);
/*增加自定义按钮的分享面板*/
mShareAction = new ShareAction(CollectionActivity.this)
.setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.WEIXIN_FAVORITE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
//.addButton("umeng_sharebutton_copy", "umeng_sharebutton_copy", "umeng_socialize_copy", "umeng_socialize_copy")
.addButton("umeng_sharebutton_copyurl", "umeng_sharebutton_copyurl", "umeng_socialize_copyurl", "umeng_socialize_copyurl")
.setShareboardclickCallback(new ShareBoardlistener() {
@Override
public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
// if (snsPlatform.mShowWord.equals("umeng_sharebutton_copy")) {
// Toast.makeText(CollectionActivity.this, "复制文本按钮", Toast.LENGTH_LONG).show();
// } else
if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
StringUtil.copy(newRowsBean.getLink(), CollectionActivity.this);
Toast.makeText(CollectionActivity.this, "复制链接按钮", Toast.LENGTH_LONG).show();
} else if (share_media == SHARE_MEDIA.SMS) {
new ShareAction(CollectionActivity.this).withText("来自ZR分享面板")
.setPlatform(share_media)
.setCallback(mShareListener)
.share();
} else {
String url = newRowsBean.getLink();
UMWeb web = new UMWeb(url);
web.setTitle(newRowsBean.getTitle());
web.setDescription(newRowsBean.getTitle());
web.setThumb(new UMImage(CollectionActivity.this, R.mipmap.ic_launcher));
new ShareAction(CollectionActivity.this).withMedia(web)
.setPlatform(share_media)
.setCallback(mShareListener)
.share();
}
}
});
}
private static class CustomShareListener implements UMShareListener {
private WeakReference<CollectionActivity> mActivity;
private CustomShareListener(CollectionActivity activity) {
mActivity = new WeakReference(activity);
}
@Override
public void onStart(SHARE_MEDIA platform) {
}
@Override
public void onResult(SHARE_MEDIA platform) {
if (platform.name().equals("WEIXIN_FAVORITE")) {
Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
} else {
if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
&& platform != SHARE_MEDIA.EMAIL
&& platform != SHARE_MEDIA.FLICKR
&& platform != SHARE_MEDIA.FOURSQUARE
&& platform != SHARE_MEDIA.TUMBLR
&& platform != SHARE_MEDIA.POCKET
&& platform != SHARE_MEDIA.PINTEREST
&& platform != SHARE_MEDIA.INSTAGRAM
&& platform != SHARE_MEDIA.GOOGLEPLUS
&& platform != SHARE_MEDIA.YNOTE
&& platform != SHARE_MEDIA.EVERNOTE) {
Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
&& platform != SHARE_MEDIA.EMAIL
&& platform != SHARE_MEDIA.FLICKR
&& platform != SHARE_MEDIA.FOURSQUARE
&& platform != SHARE_MEDIA.TUMBLR
&& platform != SHARE_MEDIA.POCKET
&& platform != SHARE_MEDIA.PINTEREST
&& platform != SHARE_MEDIA.INSTAGRAM
&& platform != SHARE_MEDIA.GOOGLEPLUS
&& platform != SHARE_MEDIA.YNOTE
&& platform != SHARE_MEDIA.EVERNOTE) {
Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
if (t != null) {
Log.d("throw", "throw:" + t.getMessage());
}
}
}
@Override
public void onCancel(SHARE_MEDIA platform) {
Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
}
}
@Override
protected int providerContentViewId() {
return R.layout.activity_collection;
}
@Override
protected void setAppTitle() {
mSysToolbar.setTitle("");
setSupportActionBar(mSysToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);//设置ActionBar一个返回箭头,主界面没有,次级界面有
actionBar.setDisplayShowTitleEnabled(false);
}
mSysTvTitle.setText(getResources().getString(R.string.str_coll_title));
}
@Override
protected BasePresenter createPresenter() {
return new CollectionPresenter(this);
}
@Override
public void onItemLongClicked(ResCollection.RetObjBean.RowsBean rowsBean) {
newRowsBean = rowsBean;
sureCollection(rowsBean);
}
/**
* 构造对话框数据
*
* @return
*/
private List<HashMap<String, Object>> initDialogData() {
List<HashMap<String, Object>> list = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
map.put("name", "分享");
map.put("collectionId", 1);
map.put("url", R.mipmap.ic_share);
list.add(map);
HashMap<String, Object> map2 = new HashMap<>();
map2.put("name", "删除");
map2.put("collectionId", 2);
map2.put("url", R.mipmap.ic_delete);
list.add(map2);
return list;
}
private void sureCollection(ResCollection.RetObjBean.RowsBean rowsBean) {
if (materialDialog == null) {
materialDialog = new MaterialDialog(this);
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.view_dialog, null);
FullListView listView = view.findViewById(R.id.dialog_listView);
List<HashMap<String, Object>> list = initDialogData();
listView.setOnItemClickListener((parent, view1, position, id) -> {
if (list.get(position).get("collectionId").equals(1)) {
//TODO 分享
materialDialog.dismiss();
// Intent intent = new Intent(CollectionActivity.this, QrCodeActivity.class);
// intent.putExtra(QrCodeActivity.KEY_FROM, QrCodeActivity.FROM_VALUES[1]);
// intent.putExtra(QrCodeActivity.KEY_TITLE, newRowsBean.getTitle());
// intent.putExtra(QrCodeActivity.KEY_INFO_ID, newRowsBean.getInformationId());
// intent.putExtra(QrCodeActivity.KEY_CONTENT, Base64Util.getEncodeStr(Constant.FLAG_COLLECTION_SOURCE + newRowsBean.getLink()));
// startActivity(intent);
ShareBoardConfig config = new ShareBoardConfig();
config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_NONE);
mShareAction.open(config);
} else if (list.get(position).get("collectionId").equals(2)) {
materialDialog.dismiss();
LiteOrmDBUtil.deleteWhere(UserCollection.class, "collectionId", new String[]{"" + newRowsBean.getId()});
//adapter.notifyDataSetChanged();
collectionId = newRowsBean.getId();
((CollectionPresenter) mPresenter).del();
//T.ShowToast(CollectionActivity.this, "删除成功!");
}
});
if (dialogAdapter == null) {
dialogAdapter = new DialogAdapter(this, list);
listView.setAdapter(dialogAdapter);
}
dialogAdapter.notifyDataSetChanged();
materialDialog.setContentView(view).setTitle(Constant.TIPS_SYSTEM).setNegativeButton("关闭", v -> {
materialDialog.dismiss();
}).show();
} else {
materialDialog.show();
}
}
@Override
public void loadError(Throwable throwable) {
includeLoadFail.setVisibility(View.VISIBLE);
includeNoData.setVisibility(View.GONE);
mCollRecyclerView.setVisibility(View.GONE);
mCollSwipeLayout.setRefreshing(false);
throwable.printStackTrace();
T.ShowToast(this, Constant.MSG_NETWORK_ERROR);
}
@Override
public void setDelResult(ResBase resBase) {
if (resBase.getRetCode() == 0) {
//TODO 确认删除
onRefresh();
} else {
T.ShowToast(this, resBase.getRetMsg());
}
}
@Override
public void setListResult(ResCollection resCollection) {
if (resCollections != null && pageNum == 1) {
resCollections.clear();
}
isLoad = false;
mCollSwipeLayout.setRefreshing(false);
//TODO 填充数据
if (resCollection.getRetCode() == 0) {
includeNoData.setVisibility(View.GONE);
includeLoadFail.setVisibility(View.GONE);
mCollRecyclerView.setVisibility(View.VISIBLE);
if (resCollection.getRetObj().getRows() != null && resCollection.getRetObj().getRows().size() > 0) {
resCollections.addAll(resCollection.getRetObj().getRows());
if (adapter == null) {
adapter = new CollectionAdapter(this, resCollections);
mCollRecyclerView.setAdapter(adapter);
adapter.setMyOnItemClickedListener(new CollectionAdapter.MyOnItemClickedListener() {
@Override
public void onItemClicked(ResCollection.RetObjBean.RowsBean rowsBean) {
bean = rowsBean;
if (!TextUtils.isEmpty(rowsBean.getInformationId())) {
infoId = rowsBean.getInformationId();
((CollectionPresenter) mPresenter).getInformation(); //获取消息
} else {
Intent intent = new Intent(CollectionActivity.this, ContentActivity.class);
intent.putExtra(ContentActivity.KEY_URL, rowsBean.getLink());
intent.putExtra(ContentActivity.KEY_TITLE, rowsBean.getTitle());
intent.putExtra(ContentActivity.KEY_INFORMATION_ID, rowsBean.getInformationId());
startActivity(intent);
// T.ShowToast(mContext, "抱歉,文章链接已失效,无法打开!");
}
}
});
} else {
adapter.notifyDataSetChanged();
}
}
if (resCollections.size() == resCollection.getRetObj().getTotal()) {
isEnd = true;
}
} else if (resCollection.getRetCode() == 10013) {//暂无数据
includeNoData.setVisibility(View.VISIBLE);
includeLoadFail.setVisibility(View.GONE);
mCollRecyclerView.setVisibility(View.GONE);
} else {
includeNoData.setVisibility(View.GONE);
includeLoadFail.setVisibility(View.VISIBLE);
mCollRecyclerView.setVisibility(View.GONE);
T.ShowToast(this, resCollection.getRetMsg());
}
}
@Override
public void setInfoResult(ResInfo resInfo) {
if (resInfo.getRetCode() == 0) {
Intent intent = new Intent(this, RichTextActivity.class);
intent.putExtra("abstractContent", resInfo.getRetObj().getAbstractContent());
intent.putExtra(ContentActivity.KEY_TITLE, resInfo.getRetObj().getTitle());
intent.putExtra("whereFrom", resInfo.getRetObj().getWhereFrom());
intent.putExtra("pubDate", resInfo.getRetObj().getPubTime());
intent.putExtra("url", resInfo.getRetObj().getLink());
intent.putExtra("id", resInfo.getRetObj().getId());
intent.putExtra("clickGood", resInfo.getRetObj().getClickGood());
intent.putExtra("clickNotGood", resInfo.getRetObj().getClickNotGood());
startActivity(intent);
} else {
// T.ShowToast(mContext, "抱歉,文章链接已失效,无法打开!");
Intent intent = new Intent(this, ContentActivity.class);
intent.putExtra(ContentActivity.KEY_URL, bean.getLink());
intent.putExtra(ContentActivity.KEY_TITLE, bean.getTitle());
intent.putExtra(ContentActivity.KEY_INFORMATION_ID, bean.getInformationId());
startActivity(intent);
}
}
@Override
public int getPageNum() {
return pageNum;
}
@Override
public String getInfoId() {
return infoId;
}
@Override
public String getCollectionId() {
return collectionId;
}
@Override
public String getUserId() {
return SharedPreferencesUtil.getString(this, Constant.USER_ID, "");
}
}
|
package com.av.client.components;
import com.av.db.dataobjects.enums.Rol;
/**
* Interfaz que permite la administracion de permisos de sus componentes
*
* @author Victor J Morales R
*
*/
public interface AvComponent {
/**
* Agrega permiso para el rol definido
*
* @param rol
*/
public void addPermiso(Rol rol);
/**
* Elimina permiso para el rol definido
*
* @param rol
*/
public void removePermiso(Rol rol);
/**
* Funcion que carga todos los permisos registrados en el sistema
*/
public void loadPermisos();
/**
* Define si dicho rol tiene permisos sobre el componente
*
* @param rol
* @return
*/
public boolean contains(Rol rol);
}// AvComponent |
package huawei;
/**
* @author kangkang lou
*/
import java.util.Scanner;
/**
* 有一只兔子,从出生后第3个月起每个月都生一只兔子,小兔子长到第三个月后每个月又生一只兔子,假如兔子都不死,问每个月的兔子总数为多少?
*/
public class Main_36 {
static int rabbit(int month) {
if (month <= 2) {
return 1;
}
return rabbit(month - 1) + rabbit(month - 2);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
System.out.println(rabbit(in.nextInt()));
}
}
}
|
package com.tencent.mm.plugin.luckymoney.appbrand.ui.prepare;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.tencent.mm.plugin.luckymoney.appbrand.ui.WxaLuckyMoneyBaseUI;
import com.tencent.mm.plugin.wxpay.a.f;
import com.tencent.mm.plugin.wxpay.a.g;
import com.tencent.mm.ui.MMActivity;
public class WxaLuckyMoneyCompleteUI extends WxaLuckyMoneyBaseUI implements b {
private Button klJ;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
initView();
}
protected final void initView() {
this.klJ = (Button) findViewById(f.wxa_lucky_money_complete_finish_btn);
this.klJ.setOnClickListener(new OnClickListener() {
public final void onClick(View view) {
WxaLuckyMoneyCompleteUI.this.setResult(0, null);
WxaLuckyMoneyCompleteUI.this.finish();
}
});
}
public void onBackPressed() {
setResult(0, null);
finish();
}
protected final int getLayoutId() {
return g.wxa_lucky_money_complete_ui;
}
public final MMActivity baA() {
return this;
}
public final void Ga(String str) {
}
public final void baB() {
}
}
|
public class Persegi {
public int sisi;
public void tampilSisiPanjang() {
System.out.println("Sisi persegi : " + sisi);
}
public int hitungLuas() {
return sisi * sisi;
}
public int hitungKeliling() {
return 4 * sisi;
}
} |
package com.sezayir.demo.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sezayir.demo.builder.ContactBuilder;
import com.sezayir.demo.entity.Contact;
@RestController
public class ContactController {
@GetMapping("/people")
public List<Contact> getContacts() {
List<Contact> contacts = new ArrayList<Contact>();
Contact contact1 = new ContactBuilder().setFirstName("Sezayir").setLastName("Dagtekin")
.setEmailAddress("test@gmail.com").build();
Contact contact2 = new ContactBuilder().setFirstName("Cem").setLastName("Toker")
.setEmailAddress("cmtk@yahoo.com").build();
contacts.add(contact1);
contacts.add(contact2);
return contacts;
}
}
|
package edu.uci.ics.sdcl.firefly.report.descriptive;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;
import edu.uci.ics.sdcl.firefly.Answer;
import edu.uci.ics.sdcl.firefly.Microtask;
import edu.uci.ics.sdcl.firefly.WorkerSession;
import edu.uci.ics.sdcl.firefly.util.PropertyManager;
public class FileSessionDTO extends SessionDTO{
//Full path of the log file. Ex.: myFolder/myFile.lo
private String logPath;// = //"C:/Users/igMoreira/Desktop/Dropbox/1.CrowdDebug-Summer2015/sampleDatalogs/session-log-TestSample - Copy.log";
private static int dayDate = 7; //July 7th
private static int lastHourRead = -1;
public FileSessionDTO() {
PropertyManager manager = PropertyManager.initializeSingleton();
this.logPath = manager.reportPath + manager.sessionLogFileName;
System.out.println("sessionDTO, logPath: "+logPath);
}
public FileSessionDTO(String path) {
this.logPath = path;
}
@Override
public Map<String, WorkerSession> getSessions() {
if((this.openSessions.isEmpty()) || (this.closedSessions.isEmpty()))
loadSessions();
Map<String, WorkerSession> conc = concatenateSessionTable();
return conc;
}
@Override
public Map<String, Microtask> getMicrotasks() {
if((this.openSessions.isEmpty()) || (this.closedSessions.isEmpty()))
loadSessions();
return microtasks;
}
@Override
protected void loadSessions() {
//CLEAN THE TABLES
this.closedSessions = new LinkedHashMap<String, WorkerSession>();
this.openSessions = new LinkedHashMap<String, WorkerSession>();
this.microtasks = new LinkedHashMap<String, Microtask>();
BufferedReader log = null;
try {
log = new BufferedReader(new FileReader(logPath));
String line = null;
WorkerSession session = null;
while ((line = log.readLine()) != null) {
if(line.equals(""))
continue;
String event = line.split("%")[1];
switch (event) {
case "OPEN SESSION":
session = loadSession(line);
this.openSessions.put(session.getId()+ ":" +session.getWorkerId(), session);
break;
case "CLOSE SESSION":
session = loadSession(line);
if(this.openSessions.containsKey(session.getId()+ ":" +session.getWorkerId()))
{
session = this.openSessions.get(session.getId()+ ":" +session.getWorkerId());
this.openSessions.remove(session.getId()+ ":" +session.getWorkerId());
}
this.closedSessions.put(session.getId()+ ":" +session.getWorkerId(), session);
break;
case "MICROTASK":
loadMicrotask(line);
break;
default:
System.out.println("INVALID EVENT ON LOG " + event );
System.exit(0);
}
}
} catch (FileNotFoundException e) {
System.out.println("DATABASE ERROR: Could not open database file.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("DATABASE ERROR: Could not read database file.");
e.printStackTrace();
}
catch (Exception e) {
System.out.println("ERROR while processing file:" + logPath);
e.printStackTrace();
}
finally
{
try {
log.close();
} catch (IOException e) {
System.out.println("DATABASE ERROR: Could not close database file:"+logPath);
e.printStackTrace();
System.exit(0);
}
}
}
/**
* Responsible for loading data from the database and
* setting to the microtasks attribute.
*/
private void loadMicrotask(String line) {
String[] result = line.split("%");
Integer microtaskID = 0;
String sessionID = null;
String workerID = null;
String explanation = null;
String fileName = null;
String question = null;
String answer = null;
String duration = null;
Integer confidenceLevel = 0;
Integer diffculty = 0;
String questionType = null;
String questionTimestamp = line.substring(0, 27);
for (int i = 0; i < result.length; i++) {
String field = result[i];
field = field.replaceAll("\\s", "");
field = field.replaceAll("\n", "");
switch (field) {
case "workerId": workerID = result[i+1]; break;
case "explanation": explanation = ( i < result.length) ? result[i+1] : ""; break;
case "fileName": fileName = result[i+1]; break;
case "question": question = result[i+1]; break;
case "answer": answer = result[i+1]; break;
case "duration": duration = result[i+1]; break;
case "sessionId": sessionID = result[i+1]; break;
case "microtaskId": microtaskID = Integer.parseInt(result[i+1]); break;
case "confidenceLevel": confidenceLevel = Integer.parseInt(result[i+1]);break;
case "difficulty":diffculty = Integer.parseInt(result[i+1]);break;
case "questionType":questionType = result[i+1]; break;
}
}//for
Vector<Answer> answerList = new Vector<Answer>();
Microtask microtask=null;
int currentNumberMicrotasks = 0;
// Bind the microtask with the session
Map<String, WorkerSession> conc = concatenateSessionTable();
WorkerSession session = conc.get(sessionID+ ":" + workerID);
if(session != null)
{
currentNumberMicrotasks = session.getMicrotaskListSize() + 1;//how many microtasks are there = index +1;
answerList.add(new Answer(answer,confidenceLevel, explanation, workerID, duration, questionTimestamp,diffculty,currentNumberMicrotasks,session.getId()));
microtask = new Microtask(question, microtaskID, answerList , fileName);
microtask.setQuestionType(questionType);
//Add this microtask to the session
session.getMicrotaskList().add(microtask);
conc.put(session.getId(),session);
}
else{
System.out.println("ERROR SESSION NULL when adding Microtask, sessionID:"+sessionID);
}
if(this.microtasks.get(microtaskID.toString()) == null)
{
// The microtask does not exist yet so insert on table
this.microtasks.put(microtaskID.toString(), microtask);
}
else
{
//The microtask already exists so add the answer to it
answerList = this.microtasks.get(microtaskID.toString()).getAnswerList();
answerList.add(new Answer(answer,confidenceLevel, explanation, workerID, duration, questionTimestamp,diffculty,currentNumberMicrotasks,sessionID));
}
}
/**
* Will extract the session content of the
* line on the database log.
* @param line: line containing the session information
*/
private WorkerSession loadSession(String line){
String[] result = line.split("%");
String workerID = (result[3].replaceAll("\\s", ""));
workerID = workerID.replaceAll("\n", "");
String sessionID = (result[5].replaceAll("\\s", ""));
sessionID = sessionID.replaceAll("\n", "");
String fileName = (result[7].replaceAll("\\s", ""));
WorkerSession session = new WorkerSession(sessionID, new Vector<Microtask>());
session.setWorkerId(workerID);
session.setFileName(fileName);
return session;
}
/**
* Concatenates the open and the closed session in
* just one table.
* @return: A hashMap containing all sessions.
*/
public Map<String, WorkerSession> concatenateSessionTable()
{
HashMap<String, WorkerSession> conc = new LinkedHashMap<String, WorkerSession>();
conc.putAll(openSessions);
conc.putAll(closedSessions);
return conc;
}
/**
* gets the sessions of a single worker
* @return: A hashMap containing all the sessions related to the worker
*/
@Override
public ArrayList<WorkerSession> getSessionsByWorkerID(String workerID) {
ArrayList<WorkerSession> workerSessions = new ArrayList<WorkerSession>();
Collection<WorkerSession> sessions = getSessions().values();
for (WorkerSession session : sessions) {
if(session.getWorkerId().compareTo(workerID)==0){
workerSessions.add(session);
}
}
return workerSessions;
}
public Map<String,WorkerSession> getClosedSessions(){
return this.closedSessions;
}
}
|
package com.bat.message.exchange.service.impl;
import com.bat.commoncode.entity.CacheMsgBody;
import com.bat.message.exchange.dao.CacheManageDao;
import com.bat.message.exchange.service.CacheManageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 缓存管理Service
*
* @author ZhengYu
* @version 1.0 2019/11/28 10:33
**/
@Service
public class CacheManageServiceImpl implements CacheManageService {
@Autowired
private CacheManageDao cacheManageDao;
/**
* 将数据放进缓存中
*
* @param cacheMsgBody 缓存数据
* @author ZhengYu
*/
@Override
public void putCache(CacheMsgBody cacheMsgBody) {
// 参数校验
if (cacheMsgBody == null || StringUtils.isEmpty(cacheMsgBody.getCacheKey()) || cacheMsgBody.getCacheValue() == null) {
return;
}
cacheManageDao.putOrGetCache(cacheMsgBody.getCacheKey(), cacheMsgBody.getCacheValue());
}
/**
* 从缓存中获取数据
*
* @param key 缓存数据键
* @return java.lang.Object
* @author ZhengYu
*/
@Override
public Object getCache(String key) {
return cacheManageDao.putOrGetCache(key, null);
}
/**
* 将数据放进缓存中
*
* @param cacheMsgBody 缓存数据
* @author ZhengYu
*/
@Override
public void updateCache(CacheMsgBody cacheMsgBody) {
Object updateCache = cacheManageDao.updateCache(cacheMsgBody.getCacheKey(), cacheMsgBody.getCacheValue());
}
/**
* 将数据从缓存中删除
*
* @param key 缓存数据
* @author ZhengYu
*/
@Override
public void delCache(String key) {
cacheManageDao.delCache(key);
}
}
|
package model;
public class ItvDetail {
private String reqId;
private String candidateId;
private String phaseId;
private String interviewer;
private String qCode;
private String qHeader;
private String question;
private Integer point;
public String getReqId() {
return reqId;
}
public void setReqId(String reqId) {
this.reqId = reqId;
}
public String getCandidateId() {
return candidateId;
}
public void setCandidateId(String candidateId) {
this.candidateId = candidateId;
}
public String getPhaseId() {
return phaseId;
}
public void setPhaseId(String phaseId) {
this.phaseId = phaseId;
}
public String getInterviewer() {
return interviewer;
}
public void setInterviewer(String interviewer) {
this.interviewer = interviewer;
}
public String getqCode() {
return qCode;
}
public void setqCode(String qCode) {
this.qCode = qCode;
}
public String getqHeader() {
return qHeader;
}
public void setqHeader(String qHeader) {
this.qHeader = qHeader;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public Integer getPoint() {
return point;
}
public void setPoint(Integer point) {
this.point = point;
}
public void print() {
// system.out.println("interviewer: " + interviewer);
// system.out.println("candidateId: " + candidateId);
// system.out.println("phaseId: " + phaseId);
// system.out.println("qCode: " + qCode);
// system.out.println("point: " + point);
// system.out.println("question: " + question);
}
}
|
package com.zhouyi.business.core.vo;
import com.zhouyi.business.core.model.LedenEquipment;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* @author 杜承旭
* @ClassNmae: LedenEquipmentVo2
* @Description: TODO
* @date 2019/8/5 10:47
* @Version 1.0
**/
@Data
@ToString
public class LedenEquipmentVo2 extends LedenEquipment implements Serializable {
private String sign;
private Integer page;
private Integer startNo;
private Integer size;
private Integer endNo;
private String overName;
private Integer total;
private Date dateStart;
private Date dateEnd;
}
|
package br.com.scd.demo.exception;
public class AssociatedDoesntExistsException extends InvalidArgumentException {
private static final long serialVersionUID = 1L;
public AssociatedDoesntExistsException() {
super("Id do associado inexistente.");
}
}
|
package com.example.jesuspereyra.test;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* Created by jesuspereyra on 9/7/17.
*/
public class SendToServerRGB extends AsyncTask<String, String, String> {
// private final static String SERVER_ADDRESS = "192.168.18.250";
ResultCallback resultCallback;
public SendToServerRGB(ResultCallback resultCallback) {
super();
this.resultCallback = resultCallback;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
String modifiedSentence = null;
try {
Log.i("Info", "onClick: " + strings[0]);
String SERVER_ADDRESS = (strings[3]);
int port = new Integer(strings[4]);
byte[] message1;
byte[] message2;
byte[] message3;
message1 = (strings[0] + "$" + "R").getBytes();
message2 = (strings[1] + "$" + "G").getBytes();
message3 = (strings[2] + "$" + "B").getBytes();
byte[] receiveData = new byte[22];
InetAddress IPAddress = InetAddress.getByName(SERVER_ADDRESS);
DatagramPacket response1 = new DatagramPacket(message1, message1.length, IPAddress, port);
DatagramPacket response2 = new DatagramPacket(message2, message2.length, IPAddress, port);
DatagramPacket response3 = new DatagramPacket(message3, message3.length, IPAddress, port);
DatagramPacket received = new DatagramPacket(receiveData, receiveData.length);
DatagramSocket clientSocket = null;
clientSocket = new DatagramSocket();
System.out.println("Sending: '" + new String(message1) + "' Red");
System.out.println("Sending: '" + new String(message2) + "' Green");
System.out.println("Sending: '" + new String(message3) + "' Blue");
System.out.println("Size: " + message1.length);
System.out.println("Size: " + message2.length);
System.out.println("Size: " + message3.length);
clientSocket.send(response1);
clientSocket.send(response2);
clientSocket.send(response3);
clientSocket.setSoTimeout(5000);
while (true) {
try {
clientSocket.receive(received);
modifiedSentence = new String(received.getData());
clientSocket.close();
} catch (SocketTimeoutException ste) {
System.out.println("### Timed out after 5 seconds");
clientSocket.close();
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return modifiedSentence;//returns what you want to pass to the onPostExecute()
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
resultCallback.success(result);
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
|
package com.amnix.skinsmoothness;
import android.graphics.Bitmap;
import android.util.Log;
import java.nio.ByteBuffer;
public class AmniXSkinSmooth {
private static ByteBuffer mByteBuffer = null;
static {
System.loadLibrary("AmniXSkinSmooth");
}
private static AmniXSkinSmooth mAmniXSkinSmooth = null;
private AmniXSkinSmooth() {
}
public static AmniXSkinSmooth getInstance() {
if (mAmniXSkinSmooth == null) mAmniXSkinSmooth = new AmniXSkinSmooth();
return mAmniXSkinSmooth;
}
public void startSkinSmoothness(float level) {
if (mByteBuffer == null) return;
jniStartSkinSmooth(level);
}
public void startSkinWhiteness(float level) {
if (mByteBuffer == null) return;
jniStartWhiteSkin(level);
}
public void startFullBeauty(float smoothLevel, float whileLevel) {
if(mByteBuffer == null) return;
jniStartFullBeauty(smoothLevel,whileLevel);
}
public void initSdk() {
if (mByteBuffer == null) return;
jniInitBeauty(mByteBuffer);
}
public void unInitSdk() {
jniUninitBeauty();
}
public void storeBitmap(Bitmap bitmap, boolean recyle) {
if (mByteBuffer != null)
freeBitmap();
mByteBuffer = jniStoreBitmapData(bitmap);
if (recyle)
bitmap.recycle();
}
public void freeBitmap() {
if (mByteBuffer == null)
return;
jniFreeBitmapData(mByteBuffer);
mByteBuffer = null;
}
public Bitmap getBitmap() {
if (mByteBuffer == null)
return null;
return jniGetBitmapFromStoredBitmapData(mByteBuffer);
}
public Bitmap getBitmapAndFree() {
final Bitmap bitmap = getBitmap();
freeBitmap();
return bitmap;
}
public void onDestroy() {
freeBitmap();
unInitSdk();
mAmniXSkinSmooth = null;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if (mByteBuffer == null)
return;
Log.w("AmniXSkinSmooth", "JNI bitmap wasn't freed nicely.please remember to free the bitmap as soon as you can");
freeBitmap();
Log.w("AmniXSkinSmooth", "AmniXSkinSmooth wasn't uninit nicely.please remember to uninit");
unInitSdk();
}
private native void jniUninitBeauty();
private native void jniInitBeauty(ByteBuffer handler);
private native void jniStartSkinSmooth(float skinSmoothLevel);
private native void jniStartWhiteSkin(float whitenessLevel);
private native void jniStartFullBeauty(float skinSmoothLevel, float whitenessLevel);
private native ByteBuffer jniStoreBitmapData(Bitmap bitmap);
private native void jniFreeBitmapData(ByteBuffer handler);
private native Bitmap jniGetBitmapFromStoredBitmapData(ByteBuffer handler);
}
|
package com.github.ezauton.core.actuators;
import com.github.ezauton.core.utils.InterpolationMap;
import com.github.ezauton.core.utils.OddInterpolationMap;
/**
* Take in an input and have a mechanical input
*/
public class Actuators {
/**
* Converts voltage drive to velocity drive. This is not 100% as it does not use encoders. The
* interpolating map allows for mapping voltage to velocity if the relationship is non-linear
* (note: most FRC motors are _very_ linear). Note: values will be different on different surfaces.
*
* @param voltageMotor
* @param velToVoltage
* @return
*/
public static VelocityMotor roughConvertVoltageToVel(VoltageMotor voltageMotor, InterpolationMap velToVoltage) {
return velocity -> voltageMotor.runVoltage(velToVoltage.get(velocity));
}
/**
* Converts voltage drive to velocity drive. This is not 100% as it does not use encoders and assumes
* the motor has a roughly linear relationship between voltage and velocity.
*
* @param voltageMotor
* @param maxSpeed
* @return
*/
public static VelocityMotor roughConvertVoltageToVel(VoltageMotor voltageMotor, double maxSpeed) {
InterpolationMap interpolationMap = new OddInterpolationMap(0D, 0D);
interpolationMap.put(maxSpeed, 1D);
return roughConvertVoltageToVel(voltageMotor, interpolationMap);
}
}
|
/**
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.service.manager.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.rofour.baseball.common.RedisCommons;
import com.rofour.baseball.common.RedisKeyConstants;
import com.rofour.baseball.common.WebUtils;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.manager.SmsVendorInfo;
import com.rofour.baseball.dao.manager.bean.SmsVendorBean;
import com.rofour.baseball.dao.manager.mapper.SmsVendorMapper;
import com.rofour.baseball.exception.BusinessException;
import com.rofour.baseball.service.manager.SmsVendorService;
/**
* @ClassName: TbSmsVendorServiceImpl
* @Description: 管理中心--短信供应商操作实现类
* @author xl
* @date 2016年3月28日 上午9:55:01
*
*/
@Service("smsVendorService")
public class SmsVendorServiceImpl implements SmsVendorService {
@Autowired
@Qualifier("smsVendorMapper")
private SmsVendorMapper smsVendorMapper;
@Autowired
private WebUtils webUtils;
@Resource(name = "redisCommons")
private RedisCommons redisCommons;
/**
* @Description: 删除一个短信供应商
* @param smsVendorId
* @return
* @see com.rofour.baseball.idl.managecenter.service.SmsVendorService#deleteByPrimaryKey(java.lang.String)
*/
@Override
public int deleteByPrimaryKey(String smsVendorId,HttpServletRequest request) {
if(StringUtils.isBlank(smsVendorId)){
throw new BusinessException("111");
}
SmsVendorBean origin = smsVendorMapper.selectByPrimaryKey(smsVendorId);
int result = smsVendorMapper.deleteByPrimaryKey(smsVendorId);
if(result == 0){
throw new BusinessException("01013");
}
delCache();
webUtils.userDeleteLog(request, 18, origin);
return result;
}
/**
* @Description: 添加一个短信供应商
* @param record
* @return
* @see com.rofour.baseball.idl.managecenter.service.SmsVendorService#insert(com.rofour.baseball.idl.managecenter.service.entity.SmsVendorInfo)
*/
@Override
public ResultInfo insert(SmsVendorInfo record,HttpServletRequest request) {
validateInfo(record);
SmsVendorBean bean = smsVendorMapper.selectByPrimaryKey(record.getSmsVendorId());
if(bean != null){
throw new BusinessException("01014");
}
SmsVendorBean smsVendorBean = new SmsVendorBean();
BeanUtils.copyProperties(record, smsVendorBean);
Map<String, Object> map = new HashMap<String, Object>();
map.put("smsVendorCode", smsVendorBean.getSmsVendorCode());
map.put("smsVendorName", smsVendorBean.getSmsVendorName());
map.put("loginName", smsVendorBean.getLoginName());
if (smsVendorMapper.isSmsVendorExist(map) > 0) {
throw new BusinessException("01014");
}
smsVendorMapper.insert(smsVendorBean);
delCache();
webUtils.userAddLog(request, 18, smsVendorBean);
return new ResultInfo(0, "", "添加供应商信息成功");
}
/**
* @Description: 查询短信供应商
* @param smsVendorId
* @return
* @see com.rofour.baseball.idl.managecenter.service.SmsVendorService#selectByPrimaryKey(java.lang.String)
*/
@Override
public SmsVendorInfo selectByPrimaryKey(String smsVendorId) {
SmsVendorBean smsVendorBean = smsVendorMapper.selectByPrimaryKey(smsVendorId);
SmsVendorInfo smsVendorInfo = new SmsVendorInfo();
if (smsVendorBean != null) {
BeanUtils.copyProperties(smsVendorBean, smsVendorInfo);
}
return smsVendorInfo;
}
/**
* @Description: 更新一个短信供应商
* @param record
* @return
* @see com.rofour.baseball.idl.managecenter.service.SmsVendorService#updateByPrimaryKey(com.rofour.baseball.idl.managecenter.service.entity.SmsVendorInfo)
*/
@Override
public ResultInfo updateByPrimaryKey(SmsVendorInfo record,HttpServletRequest request) {
validateInfo(record);
SmsVendorBean smsVendorBean = new SmsVendorBean();
BeanUtils.copyProperties(record, smsVendorBean);
Map<String, Object> map = new HashMap<String, Object>();
map.put("smsVendorCode", smsVendorBean.getSmsVendorCode());
map.put("smsVendorName", smsVendorBean.getSmsVendorName());
map.put("loginName", smsVendorBean.getLoginName());
map.put("smsVendorId", smsVendorBean.getSmsVendorId());
int rtn = smsVendorMapper.isSmsVendorExist(map);
if (rtn > 0) {
throw new BusinessException("01014");
}
SmsVendorBean origin = smsVendorMapper.selectByPrimaryKey(record.getSmsVendorId());
rtn = smsVendorMapper.updateByPrimaryKey(smsVendorBean);
if(rtn == 0){
throw new BusinessException("01013");
}
delCache();
webUtils.userEditLog(request, 18, origin,smsVendorBean);
return new ResultInfo(0, "", "更新成功");
}
/**
* @Description: 查询所有短信供应商
* @return
* @see com.rofour.baseball.idl.managecenter.service.SmsVendorService#selectAll()
*/
@Override
public List<SmsVendorInfo> selectAll(SmsVendorInfo info) {
List<SmsVendorBean> list = smsVendorMapper.selectAll(info);
if(list == null || list.isEmpty()){
throw new BusinessException("01013");
}
List<SmsVendorInfo> dataList = new ArrayList<SmsVendorInfo>();
for (SmsVendorBean item : list) {
SmsVendorInfo smsVendorInfo = new SmsVendorInfo();
BeanUtils.copyProperties(item, smsVendorInfo);
dataList.add(smsVendorInfo);
}
return dataList;
}
/**
*
* @Description: 根据条件查询总数
* @param info
* @return
* @see com.rofour.baseball.service.manager.SmsVendorService#getTotal(com.rofour.baseball.controller.model.manager.SmsVendorInfo)
*/
@Override
public int getTotal(SmsVendorInfo info) {
return smsVendorMapper.getTotal(info);
}
/**
* @Description: 字段校验
* @param smsVendor
* @return
*/
private void validateInfo(SmsVendorInfo smsVendor) {
if(StringUtils.isBlank(smsVendor.getSmsVendorId()) || StringUtils.isBlank(smsVendor.getSmsVendorCode())
|| StringUtils.isBlank(smsVendor.getSmsVendorName()) || StringUtils.isBlank(smsVendor.getLoginName())
|| StringUtils.isBlank(smsVendor.getPassword()) || smsVendor.getLevel() == null
|| smsVendor.getWeight() == null || smsVendor.getThreshold() == null
|| smsVendor.getStatus() == null || StringUtils.isBlank(smsVendor.getInterfaceAddress())){
throw new BusinessException("111");
}
if (smsVendor.getSmsVendorCode().length() > 20 || smsVendor.getSmsVendorName().length() > 100
|| smsVendor.getLoginName().length() > 30 ||smsVendor.getPassword().length() > 30
|| smsVendor.getLevel().toString().length() > 1 || smsVendor.getStatus().toString().length() > 1
|| (smsVendor.getBeDeleted()!=null && smsVendor.getBeDeleted().toString().length() > 1)
|| (smsVendor.getChannelCode()!=null && smsVendor.getChannelCode().length() > 30)
|| smsVendor.getInterfaceAddress().length() > 500) {
throw new BusinessException("112");
}
}
public void delCache() {
String redisMapKey = RedisKeyConstants.SMS_VENDOR_MAP;
redisCommons.delete(redisMapKey);
String redisListKey = RedisKeyConstants.SMS_VENDOR_LIST;
redisCommons.delete(redisListKey);
}
}
|
package com.penzias.service;
import com.penzias.core.interfaces.BasicService;
import com.penzias.entity.BloodFatExamInfo;
import com.penzias.entity.BloodFatExamInfoExample;
public interface BloodFatExamInfoService extends BasicService<BloodFatExamInfoExample, BloodFatExamInfo> {
} |
package entities.fields.ownable;
import desktop_resources.GUI;
import entities.fields.abstracts.Ownable;
import entities.fields.collection.FieldCollection;
import game.Dice;
import game.Player;
public class Brewery extends Ownable
{
private int rate;
private Dice dice;
private FieldCollection fieldCollection;
/**
* Creates a LaborCamp field
*
* @param a
* Field price (int)
* @param b
* Field number (int)
*/
public Brewery(String name, String description, int fieldID, int price, int rate, Dice dice, FieldCollection fieldCollection)
{
super(name, description, fieldID, price);
this.rate = rate;
this.dice = dice;
this.fieldCollection = fieldCollection;
}
@Override
public int getRent()
{
return dice.roll() * rate * fieldCollection.getOwnedFieldsOfType(this, this.owner).length;
}
@Override
public void landOnField(Player player)
{
if (player == owner)
{
GUI.showMessage("You own this field");
}
/**
* Checks whether the player is owner of the field
*
*/
else if (owner == null)
{
/**
* If the field is not owned, the player is asked wether he wants to
* buy the field or not It then checks the player's balance to see
* if there is sufficient money If the player buys the field he is
* set as the owner and withdraws the price from the players account
* The GUI is updated with the correct information
*/
if (player.getAccount().getBalance() >= price
&& GUI.getUserLeftButtonPressed("Do you want to buy this field?", "Yes", "No"))
{
owner = player;
GUI.setOwner(fieldID + 1, owner.getName());
player.getAccount().withdraw(price);
GUI.setBalance(player.getName(), player.getAccount().getBalance());
}
}
/**
* Withdraws a dice roll times 100 times how many LaborCamps is other by
* the otherplayer
*
*/
else if (owner != null && owner != player)
{
if (owner.getJailed()==false)
{
int getmoney = this.getRent();
owner.getAccount().deposit(player.getAccount().withdraw(getmoney));
GUI.setBalance(player.getName(), player.getAccount().getBalance());
GUI.setBalance(owner.getName(), owner.getAccount().getBalance());
}
else{
GUI.showMessage("The owner is jailed so you pass through without paying him money");
}
}
else if (price > player.getAccount().getBalance())
GUI.showMessage("Your balance is too low");
}
/**
* Returns the price of the field
*/
@Override
public int getPrice()
{
// TODO Auto-generated method stub
return price;
}
/**
* Sets the owner
*/
@Override
public void setOwner(Player player)
{
this.owner = player;
}
/**
* Returns the owner of a given field
*/
@Override
public Player getOwner()
{
// TODO Auto-generated method stub
return owner;
}
}
|
package com.medic.quotesbook.views.activities;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.clans.fab.FloatingActionButton;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.medic.quotesbook.R;
import com.medic.quotesbook.models.Quote;
import com.medic.quotesbook.utils.GAK;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class QuoteImageEditorActivity extends AdActivity {
private final String TAG = this.getClass().getSimpleName();
private static final String SCREEN_NAME_IMAGE_QUOTE_EDITOR = "image quote editor";
public static final String QUOTE_KEY = "quotesbook.quote";
public static final int LIMIT_SHORT_QUOTE = 80;
public static final int LIMIT_SMALL_QUOTE = 130;
public static final int LIMIT_MEDIUM_QUOTE = 180;
public static final int N_QUOTE_BACKGROUND = 2;
ImageView quoteBackgroundView;
ImageView authorPictureView;
TextView quoteBodyTV;
TextView qbLogoQuotesTV;
TextView qbLogoBookTV;
TextView authorFirstNameTV;
TextView authorLastNameTV;
View quoteImageRoot;
FloatingActionButton fab;
View progessBar;
Tracker tracker;
String imageFileUrl;
private Quote quote;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quote_image_editor);
tracker = getAppCtrl().getDefaultTracker();
quote = getIntent().getParcelableExtra(QUOTE_KEY);
quoteBackgroundView = (ImageView) findViewById(R.id.quote_background);
authorPictureView = (ImageView) findViewById(R.id.author_picture);
quoteBodyTV = (TextView) findViewById(R.id.quote_body);
authorFirstNameTV = (TextView) findViewById(R.id.author_first_name);
authorLastNameTV = (TextView) findViewById(R.id.author_last_name);
qbLogoQuotesTV = (TextView) findViewById(R.id.qb_lobo_quotes);
qbLogoBookTV = (TextView) findViewById(R.id.qb_lobo_book);
quoteImageRoot = findViewById(R.id.image_quote_root);
fab = (FloatingActionButton) findViewById(R.id.fab);
progessBar = findViewById(R.id.progressBar);
setTopAd();
initAds();
setupFab();
setContent();
}
private void setContent(){
// TODO: Si no hay red avisar de que no se puede obtener la imagen del autor
String shareableQuote = quote.getWithQuotes();
/*
if (shareableQuote.length() < LIMIT_SHORT_QUOTE){
quoteBodyTV.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 22);
}
if (shareableQuote.length() > LIMIT_SMALL_QUOTE){
quoteBodyTV.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
}
if (shareableQuote.length() > LIMIT_MEDIUM_QUOTE){
quoteBodyTV.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
}
*/
quoteBodyTV.setText(shareableQuote);
Picasso.with(this)
.load(quote.getAuthor().getFullPictureURL())
.placeholder(R.drawable.author_background_9)
.error(R.drawable.anonymous_author_1)
.into(authorPictureView, new Callback(){
@Override
public void onSuccess() {
progessBar.setVisibility(View.GONE);
fab.show(true);
}
@Override
public void onError() {
}
});
if (quote.getAuthor().getLastName().equals("")){
authorLastNameTV.setText(quote.getAuthor().getFirstName());
}else{
authorLastNameTV.setText(quote.getAuthor().getLastName());
authorFirstNameTV.setText(quote.getAuthor().getFirstName());
}
int nBackground = (int) (Math.random() * N_QUOTE_BACKGROUND) % N_QUOTE_BACKGROUND ;
//nBackground = 5;
quoteBackgroundView.setImageResource(getBackgroundQuoteResource(nBackground));
quoteBodyTV.setTextColor(getResources().getColor(getImageTextColorResource(nBackground)));
authorFirstNameTV.setTextColor(getResources().getColor(getImageTextColorResource(nBackground)));
authorLastNameTV.setTextColor(getResources().getColor(getImageTextColorResource(nBackground)));
((TextView) findViewById(R.id.author_separator)).setTextColor(getResources().getColor(getImageTextColorResource(nBackground)));
Typeface font = Typeface.createFromAsset(getAssets(), "RobotoSlab-Regular.ttf");
quoteBodyTV.setTypeface(font);
Typeface fontBold = Typeface.createFromAsset(getAssets(), "RobotoSlab-Bold.ttf");
qbLogoBookTV.setTypeface(fontBold);
qbLogoQuotesTV.setTypeface(font);
( (TextView) findViewById(R.id.qb_lobo_quotes_light)).setTypeface(font);
( (TextView) findViewById(R.id.qb_lobo_book_light)).setTypeface(fontBold);
}
private void setupFab(){
fab.hide(false);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fab.setShowProgressBackground(true);
fab.setIndeterminate(true);
Bitmap image = getBitmapFromView(quoteImageRoot);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
imageFileUrl = Environment.getExternalStorageDirectory() + File.separator + quote.getKey() + ".jpg";
File f = new File(imageFileUrl);
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + imageFileUrl));
startActivity(Intent.createChooser(sharingIntent, "Compartir via"));
HitBuilders.EventBuilder event = new HitBuilders.EventBuilder();
event.setCategory(GAK.CATEGORY_SHARE);
event.setAction(GAK.ACTION_QUOTE_IMAGE_SHARED);
event.setLabel(quote.getKey());
tracker.send(event.build());
}
});
}
public static Bitmap getBitmapFromView(View view) {
// CODE FROM: http://stackoverflow.com/questions/5536066/convert-view-to-bitmap-on-android
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
@Override
protected void onPause(){
super.onPause();
Log.d(TAG, "Se activa el loader");
}
@Override
protected void onResume(){
super.onResume();
tracker.setScreenName(SCREEN_NAME_IMAGE_QUOTE_EDITOR);
tracker.send(new HitBuilders.ScreenViewBuilder().build());
fab.hideProgress();
/*if (imageFileUrl != null){
File f = new File(imageFileUrl);
f.delete();
imageFileUrl = null;
}*/
}
private int getBackgroundQuoteResource(int i){
switch (i){
case 0: return R.drawable.bg_quote_share_1;
case 1: return R.drawable.bg_quote_share_2;
case 2: return R.drawable.bg_quote_share_3;
case 3: return R.drawable.bg_quote_share_4;
case 4: return R.drawable.bg_quote_share_5;
default:
return R.drawable.bg_quote_share_2;
}
}
private int getImageTextColorResource(int i){
switch (i){
case 1:
findViewById(R.id.bottom_dark).setVisibility(View.GONE);
return R.color.text_color_2;
default:
findViewById(R.id.bottom_light).setVisibility(View.GONE);
return R.color.text_color_1;
}
}
}
|
package com.example.device;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.example.device.bean.Satellite;
import com.example.device.util.DateUtil;
import com.example.device.util.SwitchUtil;
import java.util.HashMap;
import java.util.Map;
/**
* Created by ouyangshen on 2018/1/27.
*/
public class NavigationActivity extends AppCompatActivity {
private final static String TAG = "NavigationActivity";
private TextView tv_navigation;
private LocationManager mLocationMgr; // 声明一个定位管理器对象
private Map<String, Boolean> mapNavigation = new HashMap<String, Boolean>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
TextView tv_device = findViewById(R.id.tv_device);
tv_device.setText(String.format("当前设备型号为%s", Build.MODEL));
tv_navigation = findViewById(R.id.tv_navigation);
SwitchUtil.checkGpsIsOpen(this, "需要打开定位功能才能查看卫星导航信息");
}
@Override
protected void onResume() {
super.onResume();
// 从系统服务中获取定位管理器
mLocationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 检查当前设备是否已经开启了定位功能
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "请授予定位权限并开启定位功能", Toast.LENGTH_SHORT).show();
return;
}
// 获取定位管理器的最佳定位提供者
String bestProvider = mLocationMgr.getBestProvider(new Criteria(), true);
// 设置定位管理器的位置变更监听器
mLocationMgr.requestLocationUpdates(bestProvider, 300, 0, mLocationListener);
// 给定位管理器添加导航状态监听器
mLocationMgr.addGpsStatusListener(mStatusListener);
}
@Override
protected void onDestroy() {
if (mLocationMgr != null) {
// 移除定位管理器的导航状态监听器
mLocationMgr.removeGpsStatusListener(mStatusListener);
// 移除定位管理器的位置变更监听器
mLocationMgr.removeUpdates(mLocationListener);
}
super.onDestroy();
}
// 定义一个位置变更监听器
private LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {}
@Override
public void onProviderDisabled(String arg0) {}
@Override
public void onProviderEnabled(String arg0) {}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
};
// 定义一个导航状态监听器
private GpsStatus.Listener mStatusListener = new GpsStatus.Listener() {
// 在卫星导航系统的状态变更时触发
public void onGpsStatusChanged(int event) {
Log.d(TAG, "onGpsStatusChanged event="+event);
// 获取卫星定位的状态信息
GpsStatus gpsStatus = mLocationMgr.getGpsStatus(null);
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS: // 周期的报告卫星状态
// 得到所有收到的卫星信息,包括卫星的高度角、方位角、信噪比和卫星编号
Iterable<GpsSatellite> satellites = gpsStatus.getSatellites();
for (GpsSatellite satellite : satellites) {
Satellite item = new Satellite();
item.seq = satellite.getPrn(); // 卫星的伪随机码,可以认为就是卫星的编号
item.signal = Math.round(satellite.getSnr()); // 卫星的信噪比
item.elevation = Math.round(satellite.getElevation()); // 卫星的仰角 (卫星的高度)
item.azimuth = Math.round(satellite.getAzimuth()); // 卫星的方位角
item.time = DateUtil.getNowDateTime();
if (item.seq <= 64 || (item.seq >= 120 && item.seq <= 138)) { // 分给美国的
mapNavigation.put("GPS", true);
} else if (item.seq >= 201 && item.seq <= 237) { // 分给中国的
mapNavigation.put("北斗", true);
} else if (item.seq >= 65 && item.seq <= 89) { // 分给俄罗斯的
mapNavigation.put("格洛纳斯", true);
} else if (item.seq != 193 && item.seq != 194) {
mapNavigation.put("未知", true);
}
}
// 显示设备支持的卫星导航系统信息
showNavigationInfo();
case GpsStatus.GPS_EVENT_FIRST_FIX: // 首次卫星定位
case GpsStatus.GPS_EVENT_STARTED: // 卫星导航服务开始
case GpsStatus.GPS_EVENT_STOPPED: // 卫星导航服务停止
default:
break;
}
}
};
// 显示设备支持的卫星导航系统信息
private void showNavigationInfo() {
boolean isFirst = true;
String desc = "支持的卫星导航系统包括:";
for (Map.Entry<String, Boolean> item_map : mapNavigation.entrySet()) {
if (!isFirst) {
desc = String.format("%s、%s", desc, item_map.getKey());
} else {
desc = String.format("%s%s", desc, item_map.getKey());
isFirst = false;
}
}
tv_navigation.setText(desc);
}
}
|
package sort;
import java.util.Arrays;
public class quickSort {
public static void main(String[] args){
int[] data = new int[]{ 4, 2, 8, 6, 0, 5, 1, 7, 3, 9 };
quicksort(data, 0, data.length-1);
System.out.println(Arrays.toString(data));
}
private static void quicksort(int[] data, int pl, int pr) {
if(pl!=pr) {
int pivotIdx = partition(data, pl,pr);
quicksort(data, pl, pivotIdx-1);
quicksort(data, pivotIdx, pr);
}
}
private static int partition(int[] data, int pl, int pr) {
int pivot = data[pl];
while(pl<=pr) {
// 1. 왼쪽이 피벗보다 크거나 같을때 까지 왼쪽으로 pl++
while(data[pl] < pivot) pl++;
// 2. 오른쪽이 피벗보다 작거나 같을때까지 pr--
while(data[pr] > pivot) pr--;
// 3. pl, pr을 스왑하고 둘다 다음칸으로 전진한다
if(pl<=pr) {
int temp = data[pr];
data[pr] = data[pl];
data[pl] = temp;
pl++;
pr--;
}
System.out.println("교체 결과: " + Arrays.toString(data));
}
return pl;
}
}
|
package com.company;
import java.util.*;
/**
* Created by michaelssss on 2017/2/15.
*/
public class MyArrayList<T> implements List<T> {
private Object[] objects;
private int size;
public MyArrayList(int size) {
this.objects = new Object[size];
this.size = 0;
}
public MyArrayList() {
this(16);
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return this.size() == 0;
}
@Override
public boolean contains(Object o) {
for (Object t : objects) {
if (t.equals(o)) return true;
}
return false;
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public Object[] toArray() {
return Arrays.copyOf(objects, objects.length);
}
@Override
public <T1> T1[] toArray(T1[] a) {
return (T1[]) this.toArray();
}
private void increaseCapacipy() {
Object[] objects = new Object[this.objects.length * 2];
System.arraycopy(this.objects, 0, objects, 0, this.objects.length);
this.objects = objects;
}
private boolean isFull() {
return size() == objects.length - 1;
}
@Override
public boolean add(T t) {
if (isFull()) {
increaseCapacipy();
}
objects[size] = t;
size++;
return true;
}
@Override
public boolean remove(Object o) {
if (indexOf(o) == -1) {
return false;
}
remove(indexOf(o));
return true;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public boolean addAll(Collection<? extends T> c) {
return false;
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public void clear() {
this.objects = new Object[16];
}
@Override
public T get(int index) {
return (T) this.objects[index];
}
@Override
public T set(int index, T element) {
this.objects[index] = element;
return element;
}
@Override
public void add(int index, T element) {
Object[] objects = new Object[size + 1];
System.arraycopy(this.objects, 0, objects, 0, index - 1);
objects[index] = element;
System.arraycopy(this.objects, 0, objects, 0, size - index - 1);
this.objects = objects;
}
@Override
public T remove(int index) {
Object[] objects = new Object[size - 1];
System.arraycopy(this.objects, 0, objects, 0, index - 1);
System.arraycopy(this.objects, index + 1, objects, index - 1, size - index - 1);
T t = get(index);
this.objects = objects;
return t;
}
@Override
public int indexOf(Object o) {
for (int i = 0; i < size; i++) {
if (this.objects[i].equals(o)) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
int index = -1;
for (int i = 0; i < size; i++) {
if (this.objects[i].equals(o)) {
index = i;
}
}
return index;
}
@Override
public ListIterator<T> listIterator() {
return null;
}
@Override
public ListIterator<T> listIterator(int index) {
return null;
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return null;
}
}
|
package org.jlab.clas.analysis.clary;
import java.io.*;
import java.util.*;
import org.jlab.io.base.DataEvent;
import org.jlab.io.base.DataBank;
class SectorMatchCut implements BICandidate {
public boolean candidate( DataEvent event, int rec_index ){
DataBank recBank = event.getBank("REC::Particle");
int sector_ec = Detectors.getSectorECAL( event, rec_index );
int sector_dc = Detectors.getSectorDC( event, rec_index );
//System.out.println(" >> SECTOR MMATCH CUT " );
if( (sector_dc == sector_ec) && (sector_dc >= 0 && sector_ec >= 0) ){
//System.out.println(" >> SECTOR ERROR DO NOT MATCH: DC " + sector_dc + " EC " + sector_ec );
return true;
}
else{
//System.out.println(" >> SECTOR ERROR DO NOT MATCH: DC " + sector_dc + " EC " + sector_ec );
}
return false;
}
}
|
package SortingProblems;
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {44, 11, 18, 33, 21, 67, 99, 103, 11, 42, 61, 88};
int temp = 0;
boolean flag = true;
while(flag == true) {
flag = false;
for (int i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
flag = true;
}
}
}
for(int sortedArr : arr)
System.out.print(sortedArr+ ", ");
}
}
|
package fr.doranco.ecommerce.entity.dto;
public class ArticleDto {
private String id;
private String nom;
private String description;
private String prix;
private String remise;
private String stock;
private String isVendable;
public ArticleDto() {
super();
// TODO Auto-generated constructor stub
}
public ArticleDto(String id, String nom, String description, String prix, String remise, String stock,
String isVendable) {
super();
this.id = id;
this.nom = nom;
this.description = description;
this.prix = prix;
this.remise = remise;
this.stock = stock;
this.isVendable = isVendable;
}
public ArticleDto(String nom, String description, String prix, String remise, String stock, String isVendable) {
super();
this.nom = nom;
this.description = description;
this.prix = prix;
this.remise = remise;
this.stock = stock;
this.isVendable = isVendable;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrix() {
return prix;
}
public void setPrix(String prix) {
this.prix = prix;
}
public String getRemise() {
return remise;
}
public void setRemise(String remise) {
this.remise = remise;
}
public String getStock() {
return stock;
}
public void setStock(String stock) {
this.stock = stock;
}
public String getIsVendable() {
return isVendable;
}
public void setIsVendable(String isVendable) {
this.isVendable = isVendable;
}
}
|
package model;
/**
* Premios recebidos por um candidato.
* Restrito na leitura do lattes para serem apenas dos ultimos 10 anos.
*/
public class Premio {
private int anoPremiacao;
private String nome;
// Construtor.
public Premio(int anoPremiacao, String nome) {
this.anoPremiacao = anoPremiacao;
this.nome = nome;
}
@Override
public String toString() {
return anoPremiacao + " " + nome;
}
}
|
package ch.fhnw.edu.cpib.cst;
import ch.fhnw.edu.cpib.cst.interfaces.IExpr;
import ch.fhnw.edu.cpib.cst.interfaces.IExprListLparenNTS;
import ch.fhnw.edu.cpib.cst.interfaces.IExprListNTS;
import java.util.ArrayList;
// exprListLparenNTS ::= expr exprListNTS
public class ExprListLParenNTS extends Production implements IExprListLparenNTS {
protected final IExpr N_expr;
protected final IExprListNTS N_exprListNTS;
public ExprListLParenNTS(final IExpr n_expr, final IExprListNTS n_exprListNTS) {
N_expr = n_expr;
N_exprListNTS = n_exprListNTS;
}
@Override public ArrayList<ch.fhnw.edu.cpib.ast.interfaces.IExpr> toAbsSyntax() {
ArrayList<ch.fhnw.edu.cpib.ast.interfaces.IExpr> temp = new ArrayList<>();
temp.add(N_expr.toAbsSyntax());
return N_exprListNTS.toAbsSyntax(temp);
}
}
|
package com.sky.contract.service;
import com.sky.contract.mapper.ProjectMapper;
import com.sky.contract.model.Project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by shiqm on 2018/9/29.
*/
@Service
public class ProjectService {
@Autowired
private ProjectMapper projectMapper;
@Autowired
private UserService userService;
public void save(Project project){
projectMapper.insertSelective(project);
}
public List<Project> getAll(){
return projectMapper.getAllProject();
}
public Project get(Long projectId){
return projectMapper.getProject(projectId);
}
public List<Project> getMyProject(){
List<Long> ids = userService.getMyIds();
return projectMapper.getProjectByUsers(ids);
}
public List<Project> getMyProjectByStatus(Short status){
List<Long> ids = userService.getMyIds();
return projectMapper.getProjectByUsersAndStatus(ids,status);
}
public boolean updateStatus(Long projectId,Short status){
Project project=new Project();
project.setProjectId(projectId);
project.setStatus(status);
if(projectMapper.updateByPrimaryKeySelective(project)==1){
return true;
}
return false;
}
}
|
package com.appdear.client;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.appdear.client.commctrls.BaseGroupActivity;
import com.appdear.client.commctrls.PagerCallback;
import com.appdear.client.commctrls.PagerContolerDetail;
import com.appdear.client.commctrls.TabCallBack;
import com.appdear.client.commctrls.TabbarCallback;
import com.appdear.client.commctrls.TabbarNewDetail;
/**
* 类别二级界面(免费--收费--最新)
*
* @author zhangxinyong
*
*/
public class CategoryDetailsActivity extends BaseGroupActivity implements PagerCallback{
/**
* 全局标志
*/
String TAG = CategoryDetailsActivity.class.getName();
/**
* 头部标志
*/
TabbarNewDetail mTopTab = null;
TextView mTv_categoryDetailTitle = null;
String categoryId = null;
String categoryTitle = null;
Intent onNewIntent;
String tempCategoryId;
/**
* 视图
*/
View v1 = null;
View v2 = null;
View v3 = null;
View v4 = null;
View v5 = null;
View temp = null;
/**
* 在页面暂停的时候用户选中的tab标签
*/
selectType type;
private LinearLayout freeLayout;
private LinearLayout feeLayout;
private LinearLayout latestLayout;
private LocalActivityManager mangaer;
TextView tv_navigation;
ImageButton btn_return;
RelativeLayout tab_ll_linear;
public PagerContolerDetail pagerContoler ;
private LayoutInflater mLayoutInflater ;
public void onCreate(Bundle b){
super.onCreate(b);
this.setContentView(R.layout.category_app_detail_layout);
}
@Override
public void init() {
tv_navigation = (TextView) findViewById(R.id.tv_navigation);
tab_ll_linear = (RelativeLayout) findViewById(R.id.layout);
tab_ll_linear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
btn_return = (ImageButton) findViewById(R.id.btn_return);
btn_return.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
categoryTitle = this.getIntent().getStringExtra("category_title");
categoryId = this.getIntent().getStringExtra("category_id");
tv_navigation.setText(this.getIntent().getStringExtra("category_navigation"));
mLayoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v4= mLayoutInflater.inflate(R.layout.pagerview_init, null);
v5= mLayoutInflater.inflate(R.layout.pagerview_init, null);
this.tempCategoryId = categoryId;
type = selectType.TabOne;
mangaer=getLocalActivityManager();
}
TabCallBack callback=new TabCallBack(){
@Override
public void callback(int position) {
// Log.i("info909", "moremanager======callback="+position);
if(position == 0)
{
type = selectType.TabOne;
if(v1==null){
v1 = StartAcitivityForView(1);
}
}else if (position == 1) {
type = selectType.TabSecond;
if(v2==null){
v2 = StartAcitivityForView(2);
}
}else if(position == 2)
{
type = selectType.TabThree;
if(v3==null){
v3 = StartAcitivityForView(3);
}
}
}
};
@Override
protected void onNewIntent(Intent intent) {
this.onNewIntent = intent;
categoryTitle = intent.getStringExtra("category_title");
categoryId = intent.getStringExtra("category_id");
//set null.
if(!categoryId.equals(this.tempCategoryId)){
v1 = null;
v2 = null;
v3 = null;
}
//tab
switch(type){
case TabOne:
if(!categoryId.equals(this.tempCategoryId)){
v1 = StartAcitivityForView(1);
freeLayout.removeAllViews();
freeLayout.addView(v1);
}
break;
case TabSecond:
//
if(!categoryId.equals(this.tempCategoryId)){
v2 = StartAcitivityForView(2);
feeLayout.removeAllViews();
feeLayout.addView(v2);
}
break;
case TabThree:
//
if(!categoryId.equals(this.tempCategoryId)){
v3 = StartAcitivityForView(3);
latestLayout.removeAllViews();
latestLayout.addView(v3);
}
break;
}
super.onNewIntent(intent);
this.tempCategoryId = categoryId;
}
// @Override
// public void fistItemClickCallback() {
// type = selectType.TabOne;
// if(v1==null){
// v1 = StartAcitivityForView(1);
// freeLayout.removeAllViews();
// freeLayout.addView(v1);
// }
// }
//
// @Override
// public void secondItemClickCallback() {
// type = selectType.TabSecond;
// if(v2==null){
// v2 = StartAcitivityForView(2);
// feeLayout.removeAllViews();
// feeLayout.addView(v2);
// }
// }
//
// @Override
// public void thirdItemClickCallback() {
// type = selectType.TabThree;
// if(v3==null||!categoryId.equals(this.tempCategoryId)){
// v3 = StartAcitivityForView(3);
// latestLayout.removeAllViews();
// latestLayout.addView(v3);
// }
// }
private enum selectType{
TabOne,TabSecond,TabThree
}
private View StartAcitivityForView(int tabIndex){
return getLocalActivityManager().startActivity(
tabIndex+"",
new Intent(CategoryDetailsActivity.this,CategoryDetailListActivity.class)
.putExtra("category_id",categoryId).putExtra("tabIndex", tabIndex)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
.putExtra("state", "refresh")
).getDecorView();
}
@Override
public void finish() {
// Log.i("info","finish");
// mangaer.destroyActivity("1",true);
// mangaer.destroyActivity("2",true);
// mangaer.destroyActivity("3",true);
super.finish();
}
@Override
public View viewFirst() {
// TODO Auto-generated method stub
return null;
}
@Override
public View viewSecend() {
// TODO Auto-generated method stub
if(v2==null){
v2 = StartAcitivityForView(2);
}
return v2;
}
@Override
public View viewThird() {
// TODO Auto-generated method stub
if(v3==null){
v3 = StartAcitivityForView(3);
}
return v3;
}
@Override
public void updateUI() {
// TODO Auto-generated method stub
inittab();
}
private void inittab(){
mTopTab = (TabbarNewDetail)this.findViewById(0x1234);
//1.将原有“免费”、“收费”、“最新”三个标签,修改为“最多下载”、“上升排行”、“最新上架”
//4 按下载销量排序
mTopTab.setTitle(new String[]{"最受欢迎", "最多下载", "最新上架"});
//free .
if (v1 == null) {
v1 = mangaer.startActivity(
"1",
new Intent(CategoryDetailsActivity.this, CategoryDetailListActivity.class)
.putExtra("category_id",categoryId).putExtra("tabIndex", 1)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
)
.getDecorView();
}
pagerContoler = new PagerContolerDetail(this);
pagerContoler.setTabCallback(callback);
pagerContoler.initViewPager(mTopTab,v1,v4,v5,false,true,true);
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.business.api.elem;
import java.util.List;
import net.nan21.dnet.core.api.service.business.IEntityService;
import net.nan21.dnet.module.bd.domain.impl.elem.Element;
import net.nan21.dnet.module.bd.domain.impl.elem.ElementFormula;
import net.nan21.dnet.module.bd.domain.impl.elem.ElementInput;
import net.nan21.dnet.module.bd.domain.impl.elem.ElementType;
import net.nan21.dnet.module.bd.domain.impl.elem.Engine;
/**
* Interface to expose business functions specific for {@link Element} domain
* entity.
*/
public interface IElementService extends IEntityService<Element> {
/**
* Find by unique key
*/
public Element findByEngine_code(Engine engine, String code);
/**
* Find by unique key
*/
public Element findByEngine_code(Long engineId, String code);
/**
* Find by reference: engine
*/
public List<Element> findByEngine(Engine engine);
/**
* Find by ID of reference: engine.id
*/
public List<Element> findByEngineId(String engineId);
/**
* Find by reference: type
*/
public List<Element> findByType(ElementType type);
/**
* Find by ID of reference: type.id
*/
public List<Element> findByTypeId(String typeId);
/**
* Find by reference: variables
*/
public List<Element> findByVariables(ElementInput variables);
/**
* Find by ID of reference: variables.id
*/
public List<Element> findByVariablesId(String variablesId);
/**
* Find by reference: formulas
*/
public List<Element> findByFormulas(ElementFormula formulas);
/**
* Find by ID of reference: formulas.id
*/
public List<Element> findByFormulasId(String formulasId);
}
|
package com.yixin.dsc.v1.service.common;
import com.yixin.dsc.dto.DscFlowResultForAlixDto;
import com.yixin.dsc.entity.order.DscSalesApplyMain;
import com.yixin.kepler.v1.datapackage.dto.icbc.IcbcApplyDTO;
import com.yixin.kepler.v1.datapackage.dto.icbc.IcbcBackDataDTO;
/**
* 工行回调后处理通知提报端基类(可处理各个阶段的回调,得到统一的回调通知提报端对象),目前只实现了工行-20180930
* 如果后续实现类需要设置新的参数,参照applyMain的方式,并在调用出set即可,这样可以不影响其余实现类
*/
public abstract class NoticeApplyDeal {
protected ThreadLocal<DscSalesApplyMain> threadLocalApplyMain = new ThreadLocal<>();
protected ThreadLocal<IcbcApplyDTO<IcbcBackDataDTO>> threadLocalICBCFeedBack = new ThreadLocal<>();
public NoticeApplyDeal setApplyMain(DscSalesApplyMain applyMain){
this.threadLocalApplyMain.set(applyMain);
return this;
}
public NoticeApplyDeal setICBCFeedBack(IcbcApplyDTO<IcbcBackDataDTO> feedBack){
this.threadLocalICBCFeedBack.set(feedBack);
return this;
}
/**
* 信审后处理
* @return
*/
public abstract DscFlowResultForAlixDto deal();
}
|
/*
* Copyright 2020 SoftInstigate srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ${package};
/**
*
* @author Simone Marrone <simone@softinstigate.com>
* @author Omar Trasatti <omar@softinstigate.com>
*/
import com.google.gson.JsonObject;
import org.restheart.exchange.JsonRequest;
import org.restheart.exchange.JsonResponse;
import org.restheart.plugins.JsonService;
import org.restheart.plugins.RegisterPlugin;
import org.restheart.utils.HttpStatus;
@RegisterPlugin(
name = "${name}",
description = "${description}",
defaultURI = "/${uri}"
)
public class ${name} implements JsonService {
@Override
public void handle(JsonRequest request, JsonResponse response) throws Exception {
if (request.isOptions()) {
handleOptions(request);
} else if (request.isGet()) {
var resp = new JsonObject();
resp.addProperty("msg", "Hello from ${name}");
response.setContent(resp);
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
}
} |
package ie.com.urlshortener.api.repository;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import ie.com.urlshortener.api.domain.ShortURL;
import ie.com.urlshortener.api.rest.dto.StatisticsDto;
/**
* Implementation of statistics queries.
*
* @author Diego
* @since 19/01/2019
*/
@Repository
public class StatisticsRepository {
protected static final String ATTR_CREATED_DATE = "createdDate";
protected static final String ATTR_LAST_MODIFIED_DATE = "lastModifiedDate";
protected static final String KEY_YEAR_MONTH_DAY = "yearMonthDay";
protected static final String ALIAS_TOTAL = "total";
protected static final String ATTR_KEY = "key";
protected static final String ATTR_VALUE = "value";
protected static final String ATTR_ID = "_id";
private static final String YEAR_MONTH_DAY_PATTERN = "%Y-%m-%d";
protected final MongoOperations mongoOperations;
public StatisticsRepository(final MongoOperations mongoOperations) {
this.mongoOperations = mongoOperations;
}
/**
* Find the last Instant that some URL was created/updated.
*
* @return the last created/update Instant.
*/
public ShortURL findShortURLWithLastUpdate() {
return mongoOperations.findOne(new Query()
.with(new Sort(Sort.Direction.DESC, ATTR_LAST_MODIFIED_DATE))
.limit(1),
ShortURL.class);
}
/**
* Get the 100 days with more registrations.
*
* @return List of 100 days with more registrations.
*/
public List<StatisticsDto> findTop100CreationDate() {
final Aggregation agg = Aggregation.newAggregation(
Aggregation.project().and(ATTR_CREATED_DATE).dateAsFormattedString(YEAR_MONTH_DAY_PATTERN).as(KEY_YEAR_MONTH_DAY),
Aggregation.group(KEY_YEAR_MONTH_DAY).count().as(ALIAS_TOTAL),
Aggregation.sort(Sort.Direction.DESC, ALIAS_TOTAL),
Aggregation.project()
.andExpression(ATTR_ID).as(ATTR_KEY)
.andExpression(ALIAS_TOTAL).as(ATTR_VALUE),
Aggregation.limit(100));
//Convert the aggregation result into a List
final AggregationResults<StatisticsDto> groupResults = mongoOperations.aggregate(agg, ShortURL.class, StatisticsDto.class);
return groupResults.getMappedResults();
}
}
|
package screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.valleskeyp.mygdxgame.MyInputProcessor;
public class MenuScreen implements Screen {
private Sprite backGround;
private SpriteBatch batch;
private Sprite sprite1;
private Sprite sprite2;
private Sprite sprite3;
@Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
backGround.draw(batch);
sprite1.draw(batch);
sprite2.draw(batch);
sprite3.draw(batch);
batch.end();
}
@Override
public void resize(int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void show() {
batch = new SpriteBatch();
MyInputProcessor inputProcessor = new MyInputProcessor();
Gdx.input.setInputProcessor(inputProcessor);
Texture backGroundTexture = new Texture("data/bgGDX.png");
backGround = new Sprite(backGroundTexture);
backGround.setSize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Texture sprite1Texture = new Texture("data/sprite1.png");
sprite1 = new Sprite(sprite1Texture);
sprite1.setSize(120, 120);
sprite1.setPosition(100, 100);
Texture sprite2Texture = new Texture("data/sprite2.png");
sprite2 = new Sprite(sprite2Texture);
sprite2.setSize(120, 120);
sprite2.setPosition(300, 100);
Texture sprite3Texture = new Texture("data/card.png");
sprite3 = new Sprite(sprite3Texture);
sprite3.setSize(180, 180);
sprite3.setPosition(500, 100);
}
@Override
public void hide() {
// TODO Auto-generated method stub
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}
|
package org.example.controller;
import org.example.db.MySQLConnection;
import org.example.model.Actor;
import org.example.model.Genre;
import org.example.model.Movie;
import org.example.view.WindowMovies;
import java.util.ArrayList;
public class WindowController {
private WindowMovies view;
private MySQLConnection connection;
public WindowController(WindowMovies view) {
this.view = view;
this.connection = MySQLConnection.getInstance();
init();
}
public void init() {
view.getGenero().setOnAction(
(e) -> {
addGenero();
}
);
view.getActor().setOnAction(
(e) -> {
addActor();
}
);
view.getPelicula().setOnAction(
(e) -> {
addPelicula();
}
);
view.getVinculePA().setOnAction(
(e) -> {
vincularPa();
}
);
view.getdPelicula().setOnAction(
(e) -> {
deleteMovie();
}
);
view.getdActor().setOnAction(
(e) -> {
deleteActor();
}
);
view.getdGenero().setOnAction(
(e) -> {
deleteGenero();
}
);
view.getListxGenero().setOnAction(
(e) -> {
listxGenero();
}
);
view.getListActorPe().setOnAction(
(e) -> {
listPxActor();
}
);
view.getListMoviesActor().setOnAction(
(e) -> {
listAxP();
}
);
view.getListAll().setOnAction(
(e) -> {
listAll();
}
);
}
public void addGenero() {
view.windowInsertGenre();
view.getAdd().setOnAction(
(e) -> {
String type = view.getTfType().getText();
Genre genero = new Genre(-1, type);
view.getRespuest().setText("Agregado: " + connection.insertGenero(genero));
view.getTfType().setText("Escribe el nuevo tipo..");
}
);
}
public void addActor() {
view.windowInsertActor();
view.getAdd().setOnAction(
(e) -> {
String nombre = view.getTfType().getText();
Actor actorr = new Actor(-1, nombre);
view.getRespuest().setText("Agregado: " + connection.insertActor(actorr));
view.getTfType().setText("Escribe el nuevo tipo..");
}
);
}
private void addPelicula() {
view.windowInesertMovie();
showGeneros();
view.getAdd().setOnAction(
(e) -> {
String nameMovie = view.getTfType().getText();
String generoID = view.getIdGenero().getText();
int genreID = Integer.parseInt(generoID);
Movie pelicula = new Movie(-1, nameMovie,genreID);
view.getRespuest().setText("Agregada: " + connection.insertPelicula(pelicula, genreID));
view.getTfType().setText(" Escribe nuevo nombre...");
view.getIdGenero().setText("Escribe nuevo ID del genero...");
}
);
}
public void vincularPa() {
view.showVincularPA();
showMovies();
showActors();
view.getAdd().setOnAction(
(e) -> {
int idMovie = Integer.parseInt(view.getTfType().getText());
int idActor = Integer.parseInt(view.getIdGenero().getText());
view.getRespuest().setText("Se vinculo: " + connection.vincularPA(idMovie, idActor));
view.getTfType().setText("Escribe nuevo ID pelicula");
view.getIdGenero().setText("Escribe nuevo ID actor");
}
);
}
public void deleteMovie() {
view.showDelete();
view.getTittleDelete().setText("--------- Eliminar Pelicula ----------");
showMovies();
view.getAdd().setOnAction(
(e) -> {
int idMovie = Integer.parseInt(view.getTfType().getText());
view.getRespuest().setText("Eliminado: " + connection.deleteMovie(idMovie));
view.getTfType().setText("Escribe el ID de la pelicula ...");
view.getGetGeneros().setText("");
showMovies();
}
);
}
public void deleteActor() {
view.showDelete();
view.getTittleDelete().setText("--------- Eliminar Actor ----------");
view.getLabe1().setText("Ingresa el ID del actor");
view.getTfType().setText("Escribe el ID del actor...");
showActors();
view.getAdd().setOnAction(
(e) -> {
int idActor = Integer.parseInt(view.getTfType().getText());
view.getRespuest().setText("Eliminado: " + connection.deleteActor(idActor));
view.getTfType().setText("Escribe el ID del actor...");
view.getGetGeneros().setText("");
showActors();
}
);
}
public void deleteGenero() {
view.showDelete();
view.getTittleDelete().setText("--------- Eliminar Genero ----------");
view.getLabe1().setText("Ingresa el ID del Genero");
view.getTfType().setText("Escribe el ID del Genero...");
showGeneros();
view.getAdd().setOnAction(
(e) -> {
int idGenre = Integer.parseInt(view.getTfType().getText());
view.getRespuest().setText("Eliminado: " + connection.deleteGenre(idGenre));
view.getTfType().setText("Escribe el ID del Genero...");
view.getGetGeneros().setText("");
showGeneros();
}
);
}
public void listxGenero() {
view.showInfo();
view.getTittleDelete().setText("------ Listas de peliculas por genero -------");
showGeneros();
view.getAdd().setOnAction(
(e) -> {
view.getTexArea1().setText("");
int idGenre = Integer.parseInt(view.getTfType().getText());
ArrayList<Movie> moviesxgenero = connection.listxGenero(idGenre);
for (int i = 0; i < moviesxgenero.size(); i++) {
view.getTexArea1().appendText("Nombre pelicula: " + moviesxgenero.get(i).getName() + "\n");
}
view.getTfType().setText("");
}
);
}
public void listPxActor() {
view.showInfo();
view.getTittleDelete().setText("------ Listas de peliculas por Actor -------");
view.getLabe1().setText("Ingresa el ID del actor para ver las peliculas en el cual actua");
view.getTfType().setText("Escribe el Id del actor...");
showActors();
view.getAdd().setOnAction(
(e) -> {
view.getTexArea1().setText("");
int idActor = Integer.parseInt(view.getTfType().getText());
ArrayList<Movie> moviesxgenero = connection.listPxA(idActor);
for (int i = 0; i < moviesxgenero.size(); i++) {
view.getTexArea1().appendText("Nombre pelicula: " + moviesxgenero.get(i).getName() + "\n");
}
view.getTfType().setText("");
}
);
}
public void listAxP() {
view.showInfo();
view.getTittleDelete().setText("------ Listas de Actores por peliculas -------");
view.getLabe1().setText("Ingresa el ID de la pelicula para ver los actores ");
view.getTfType().setText("Escribe el Id de la pelicula...");
showMovies();
view.getAdd().setOnAction(
(e) -> {
view.getTexArea1().setText("");
int idMovie = Integer.parseInt(view.getTfType().getText());
ArrayList<Actor> moviesxgenero = connection.listAxP(idMovie);
for (int i = 0; i < moviesxgenero.size(); i++) {
view.getTexArea1().appendText("Nombre Actor: " + moviesxgenero.get(i).getName() + "\n");
}
view.getTfType().setText("");
}
);
}
public void listAll() {
view.showinfoAll();
view.getTittleDelete().setText("---------- Cartelera -----------");
view.getTexArea1().appendText("---------Cinema Hollywood---------" + "\n");
/* ArrayList<String> infos = connection.infoALl();
for (int i = 0;i<infos.size();i++){
view.getTexArea1().appendText(""+ infos.get(i).toString()+"\n");
}*/
ArrayList<Movie> movies = connection.getAllMovies();
int genero = -1;
String genre = "";
String nameMovie = null;
for (int i = 0; i < movies.size(); i++) {
nameMovie = movies.get(i).getName();
genero = movies.get(i).getGeneroID();
ArrayList<Actor> actors = connection.listAxP(movies.get(i).getId());
genre = connection.getGenre(genero);
String msg = "\nTitulo: " + nameMovie + "\n Genero: " + genre + "\n Actores: ";
for (int k = 0; k < actors.size(); k++) {
msg += actors.get(k).getName() + ", ";
}
msg += "\n------------------------";
view.getTexArea1().appendText(msg);
}
}
public void showMovies() {
ArrayList<Movie> movies = connection.getAllMovies();
view.getGetGeneros().appendText("---------- Peliculas ---------------" + "\n");
for (int i = 0; i < movies.size(); i++) {
int id = movies.get(i).getId();
String nombre = movies.get(i).getName();
view.getGetGeneros().appendText("ID: " + id + " Pelicula: " + nombre + "\n");
}
}
public void showActors() {
view.getGetGeneros().appendText("---------- Actores ---------------" + "\n");
ArrayList<Actor> actors = connection.getAllActors();
for (int i = 0; i < actors.size(); i++) {
int id = actors.get(i).getId();
String nombre = actors.get(i).getName();
view.getGetGeneros().appendText("ID: " + id + " Actor: " + nombre + "\n");
}
}
public void showGeneros() {
view.getGetGeneros().appendText("---------- Generos ---------------" + "\n");
ArrayList<Genre> generos = connection.getAllGenere();
for (int i = 0; i < generos.size(); i++) {
int id = generos.get(i).getId();
String tipo = generos.get(i).getType();
view.getGetGeneros().appendText("ID: " + id + " Genero: " + tipo + "\n");
}
}
}
|
package com.cee.webapp.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.context.annotation.Scope;
@Entity
@Scope(value = "session")
public class User implements Serializable {
private static final long serialVersionUID = 4988491698022262976L;
@Id
@GeneratedValue
private Long id;
@Size(min = 2, max = 30, message = "First name must be between 2 and 30 characters.")
private String firstName;
@Size(min = 0, max = 30, message = "Last name must be less than 30 characters.")
private String lastName;
@NotBlank(message = "Email address is required.")
@Email(message = "Email address must be a valid email address.")
@Size(min = 0, max = 30, message = "Email address must be less than 30 characters.")
private String email;
@Size(min = 0, max = 10, message = "Phone number must be less than 10 numbers.")
private String phone;
@Size(min = 8, max = 20, message = "Password must be between 8 and 16 characters.")
private String password;
//private Set<Role> roles;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName
* the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName
* the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email
* the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone
* the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/*
*//**
* @return the roles
*//*
public Set<Role> getRoles() {
return roles;
}
*//**
* @param roles
* the roles to set
*//*
public void setRoles(Set<Role> roles) {
this.roles = roles;
}*/
}
|
public class GameLogic {
private int count =0;
private boolean atIntro= true;
private boolean atFactionInfo=false;
private boolean isReadingFaction= false;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public boolean isAtIntro() {
return atIntro;
}
public void setAtIntro(boolean atIntro) {
this.atIntro = atIntro;
}
public boolean isAtFactionInfo() {
return atFactionInfo;
}
public void setAtFactionInfo(boolean atFactionInfo) {
this.atFactionInfo = atFactionInfo;
}
public boolean isReadingFaction() {
return isReadingFaction;
}
public void setReadingFaction(boolean isReadingFaction) {
this.isReadingFaction = isReadingFaction;
}
}
|
package com.example.plumtest2;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONObject;
public class barplot extends AppCompatActivity {
ImageView imgView;
TextView textView;
TextView textView2;
TextView textView3;
TextView textView4;
TextView textView5;
Button btn;
String sickCode;
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.barplot);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
Intent intent = getIntent();
sickCode = intent.getExtras().getString("code");
textView = findViewById(R.id.barplotText);
textView2 = findViewById(R.id.barplotText2);
textView3 = findViewById(R.id.warnText);
textView4 = findViewById(R.id.titleCode2);
imgView = (ImageView) findViewById(R.id.barplot);
btn = findViewById(R.id.nextbtn);
textView4.setText(sickCode);
sendImageRequest();
getApi();
}
public void sendImageRequest() {
String url = "http://192.168.219.105:8011/cohort?msg="+sickCode;
ImageLoadTask task = new ImageLoadTask(url,imgView);
task.execute();
}
private void getApi(){
new AsyncTask<Void, Void, String>() {
ProgressDialog progress;
@Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(barplot.this);
progress.setTitle("다운로드");
progress.setMessage("download");
progress.setProgressStyle((ProgressDialog.STYLE_SPINNER));
progress.setCancelable(false);
progress.show();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
StringBuffer sb = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
try {
JSONObject json = new JSONObject(s);
JSONArray rows = json.getJSONArray("data");
int length = rows.length();
for(int i=0; i < length; i ++){
JSONObject result = (JSONObject) rows.get(i);
String sicksym1 = result.getString("a");
String freq = result.getString("Freq");
sb.append( (i+1) +" : " + sicksym1 + "\n");
sb2.append( freq +"명"+ "\n");
Log.d("abcdef", sicksym1);
}
}catch (Exception e ){}
textView.setText(sb.toString());
textView2.setText(sb2.toString());
progress.dismiss();
}
@Override
protected String doInBackground(Void... params) {
String result = "";
try {
//서울시 오픈 API 제공(샘플 주소 json으로 작업)
result = Remote.getData("http://192.168.219.105:8011/cohorttext?msg="+sickCode);
} catch (Exception e) {
e.printStackTrace();
}
Log.d("aaaaaa", result);
return result;
}
}.execute();
}
}
|
package com.geqi.leetcode;
public class ArrayPartitionI {
public int arrayPairSum(int[] nums) {
sort(nums,0,nums.length-1);
int ans=0;
int i=0;
while(i<nums.length){
ans+=nums[i];
i+=2;
}
return ans;
}
public void sort(int[] a,int low,int high){
int start = low;
int end = high;
int key = a[low];
while(end>start){
while(end>start&&a[end]>=key)
end--;
if(a[end]<=key){
int temp = a[end];
a[end] = a[start];
a[start] = temp;
}
while(end>start&&a[start]<=key)
start++;
if(a[start]>=key){
int temp = a[start];
a[start] = a[end];
a[end] = temp;
}
}
if(start>low) sort(a,low,start-1);
if(end<high) sort(a,end+1,high);
}
}
|
package sortimo.formularmanager.databaseoperations;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import sortimo.databaseoperations.Connect;
import sortimo.formularmanager.storage.FormsStatisticsStorage;
public class Boss {
private Connection connect = null;
private PreparedStatement preparedStatement = null;
/**
* Holt alle Formulare die vom jeweiligen Boss approved werden muessen
*
* @param boss
* @return
* @throws Exception
*/
public Map<Integer, FormsStatisticsStorage> getForms(String boss) throws Exception {
Connect conClass = new Connect();
connect = conClass.getConnection();
String sql = "SELECT "
+ "id, "
+ "formularmanager_forms_response.form_id, "
+ "username, "
+ "formularmanager_forms_response.created_at, "
+ "formularmanager_forms_response.modified_at, "
+ "process_state, "
+ "processed_by, "
+ "notes, "
+ "boss_approved, "
+ "boss, "
+ "MAX(CASE WHEN meta_name = 'evaluationType' THEN meta_value END) as evaluationType, "
+ "MAX(CASE WHEN meta_name = 'formTitle' THEN meta_value END) as formTitle "
+ "FROM formularmanager_forms_response "
+ "LEFT JOIN formularmanager_forms_meta "
+ "ON formularmanager_forms_response.form_id = formularmanager_forms_meta.form_id "
+ "WHERE boss = ? "
+ "AND boss_approved IS NULL "
+ "GROUP BY formularmanager_forms_response.id";
preparedStatement = connect.prepareStatement(sql);
preparedStatement.setString(1, boss);
ResultSet rsData = preparedStatement.executeQuery();
Map<Integer, FormsStatisticsStorage> tmpList = new HashMap<>();
while (rsData.next()) {
Integer bossApproved = rsData.getObject("boss_approved") == null ? null : rsData.getInt("boss_approved");
String createdAt = rsData.getString("created_at").substring(0, rsData.getString("created_at").length() - 2) + "";
String modifiedAt = rsData.getString("modified_at").substring(0, rsData.getString("modified_at").length() - 2) + "";
FormsStatisticsStorage bossFormsStorage = new FormsStatisticsStorage();
bossFormsStorage.setResponseId(rsData.getInt("id"));
bossFormsStorage.setFormId(rsData.getInt("form_id"));
bossFormsStorage.setUsername(rsData.getString("username"));
bossFormsStorage.setCreatedAt(createdAt);
bossFormsStorage.setModifiedAt(modifiedAt);
bossFormsStorage.setProcessState(rsData.getString("process_state"));
bossFormsStorage.setProcessedBy(rsData.getString("processed_by"));
bossFormsStorage.setNotes(rsData.getString("notes"));
bossFormsStorage.setBossApproved(bossApproved);
bossFormsStorage.setBoss(rsData.getString("boss"));
bossFormsStorage.setEvaluationType(rsData.getString("evaluationType"));
bossFormsStorage.setFormTitle(rsData.getString("formTitle"));
tmpList.put(rsData.getInt("id"), bossFormsStorage);
}
conClass.close();
return tmpList;
}
/**
* Updated den BossApproved State in der DB
*
* @param request komplettes request Object
* @throws Exception
*/
public void saveBossDecision(HttpServletRequest request) throws Exception {
Connect conClass = new Connect();
connect = conClass.getConnection();
String sql = "UPDATE formularmanager_forms_response "
+ "SET notes = ?, boss_approved = ?"
+ "WHERE id = ?";
preparedStatement = connect.prepareStatement(sql);
preparedStatement.setString(1, request.getParameter("notes"));
preparedStatement.setString(2, request.getParameter("bossDecision"));
preparedStatement.setString(3, request.getParameter("responseId"));
preparedStatement.execute();
}
}
|
package july;
public class WithHalida {
public static void main(String args[]) {
String word = "javva";
String unique = "";
//char [] letters =school.toCharArray();
for (int i = 0; i < word.length(); i++) {
int count = 0;
for (int j = 0; j < word.length(); j++) {
// count=0;
if (word.charAt(i) == word.charAt(j)) {
count++;
}
}
if (count == 1) {
unique+= word.charAt(i) ;
}
//System.out.println(unique);// letter by letter
}
System.out.println(unique);
}
}
|
package com.kingdee.lightapp.oauth;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import net.sf.json.JSONObject;
public class Parameter
implements Serializable, Comparable<Parameter>
{
String name;
String value;
private static final long serialVersionUID = -8708108746980739212L;
public Parameter(String name, String value)
{
this.name = name;
this.value = value;
}
public Parameter(String name, double value) {
this.name = name;
this.value = String.valueOf(value);
}
public Parameter(String name, int value) {
this.name = name;
this.value = String.valueOf(value);
}
public String getName() {
return this.name;
}
public String getValue() {
return this.value;
}
public static Parameter[] getParameterArray(String name, String value) {
return new Parameter[] { new Parameter(name, value) };
}
public static Parameter[] getParameterArray(String name, int value) {
return getParameterArray(name, String.valueOf(value));
}
public static Parameter[] getParameterArray(String name1, String value1, String name2, String value2)
{
return new Parameter[] { new Parameter(name1, value1),
new Parameter(name2, value2) };
}
public static Parameter[] getParameterArray(String name1, int value1, String name2, int value2)
{
return getParameterArray(name1, String.valueOf(value1), name2,
String.valueOf(value2));
}
public int hashCode()
{
int result = this.name.hashCode();
result = 31 * result + this.value.hashCode();
return result;
}
public boolean equals(Object obj)
{
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if ((obj instanceof Parameter)) {
Parameter that = (Parameter)obj;
return (this.name.equals(that.name)) && (this.value.equals(that.value));
}
return false;
}
public String toString()
{
return "Parameter{name='" + this.name + '\'' + ", value='" + this.value +
'}';
}
public int compareTo(Parameter o)
{
Parameter that = o;
int compared = this.name.compareTo(that.name);
if (compared == 0) {
compared = this.value.compareTo(that.value);
}
return compared;
}
public static String encodeParameters(Parameter[] httpParams) {
if (httpParams == null) {
return "";
}
StringBuffer buf = new StringBuffer();
for (int j = 0; j < httpParams.length; j++) {
if (j != 0)
buf.append("&");
try
{
buf.append(URLEncoder.encode(httpParams[j].name, "UTF-8"))
.append("=")
.append(URLEncoder.encode(httpParams[j].value, "UTF-8"));
} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
}
}
return buf.toString();
}
public static Parameter[] convertJSON2ParameterArray(JSONObject parameter)
{
int size = parameter.size();
Parameter[] parameters = new Parameter[size];
int i = 0;
for (Iterator iterator = parameter.keys(); iterator.hasNext(); i++) {
String name = (String)iterator.next();
String value = parameter.getString(name);
parameters[i] = new Parameter(name, value);
}
return parameters;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* BBusinessRuleHeaderId generated by hbm2java
*/
public class BBusinessRuleHeaderId implements java.io.Serializable {
private String businessRuleId;
private long seq;
public BBusinessRuleHeaderId() {
}
public BBusinessRuleHeaderId(String businessRuleId, long seq) {
this.businessRuleId = businessRuleId;
this.seq = seq;
}
public String getBusinessRuleId() {
return this.businessRuleId;
}
public void setBusinessRuleId(String businessRuleId) {
this.businessRuleId = businessRuleId;
}
public long getSeq() {
return this.seq;
}
public void setSeq(long seq) {
this.seq = seq;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof BBusinessRuleHeaderId))
return false;
BBusinessRuleHeaderId castOther = (BBusinessRuleHeaderId) other;
return ((this.getBusinessRuleId() == castOther.getBusinessRuleId())
|| (this.getBusinessRuleId() != null && castOther.getBusinessRuleId() != null
&& this.getBusinessRuleId().equals(castOther.getBusinessRuleId())))
&& (this.getSeq() == castOther.getSeq());
}
public int hashCode() {
int result = 17;
result = 37 * result + (getBusinessRuleId() == null ? 0 : this.getBusinessRuleId().hashCode());
result = 37 * result + (int) this.getSeq();
return result;
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
@Table(name = "PERSON")
@EntityListeners(AuditingEntityListener.class)
@CrossOrigin
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6307786020120269232L;
public Long person_id;
public String firstname;
public String lastname;
public String phone;
public String email;
public String birthdate;
public RunTracker runTracker;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "person_id")
public Long getPersonid() {
return person_id;
}
public void setPersonid(Long person_id) {
this.person_id = person_id;
}
@Column(name = "firstname")
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@Column(name = "lastname")
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Column(name = "phone")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "birthdate")
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
@ManyToOne
@JoinColumn(name = "run_id")
@JsonIgnore
public RunTracker getRunTracker() {
return runTracker;
}
public void setRunTracker(RunTracker runTracker) {
this.runTracker = runTracker;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((birthdate == null) ? 0 : birthdate.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((firstname == null) ? 0 : firstname.hashCode());
result = prime * result + ((lastname == null) ? 0 : lastname.hashCode());
result = prime * result + ((person_id == null) ? 0 : person_id.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
result = prime * result + ((runTracker == null) ? 0 : runTracker.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (birthdate == null) {
if (other.birthdate != null)
return false;
} else if (!birthdate.equals(other.birthdate))
return false;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (firstname == null) {
if (other.firstname != null)
return false;
} else if (!firstname.equals(other.firstname))
return false;
if (lastname == null) {
if (other.lastname != null)
return false;
} else if (!lastname.equals(other.lastname))
return false;
if (person_id == null) {
if (other.person_id != null)
return false;
} else if (!person_id.equals(other.person_id))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
if (runTracker == null) {
if (other.runTracker != null)
return false;
} else if (!runTracker.equals(other.runTracker))
return false;
return true;
}
@Override
public String toString() {
return "Person [person_id=" + person_id + ", firstname=" + firstname + ", lastname=" + lastname + ", phone="
+ phone + ", email=" + email + ", birthdate=" + birthdate + ", runTracker=" + runTracker + "]";
}
public Person(Long person_id, String firstname, String lastname, String phone, String email, String birthdate,
RunTracker runTracker) {
super();
this.person_id = person_id;
this.firstname = firstname;
this.lastname = lastname;
this.phone = phone;
this.email = email;
this.birthdate = birthdate;
this.runTracker = runTracker;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
}
|
package com.tencent.mm.plugin.backup.h;
import com.tencent.mm.bk.a;
public final class s extends a {
public long hbZ;
public long hcw;
public long hcx;
protected final int a(int i, Object... objArr) {
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.T(1, this.hbZ);
aVar.T(2, this.hcw);
aVar.T(3, this.hcx);
return 0;
} else if (i == 1) {
return ((f.a.a.a.S(1, this.hbZ) + 0) + f.a.a.a.S(2, this.hcw)) + f.a.a.a.S(3, this.hcx);
} else {
if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (int a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
if (!super.a(aVar2, this, a)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
s sVar = (s) objArr[1];
switch (((Integer) objArr[2]).intValue()) {
case 1:
sVar.hbZ = aVar3.vHC.rZ();
return 0;
case 2:
sVar.hcw = aVar3.vHC.rZ();
return 0;
case 3:
sVar.hcx = aVar3.vHC.rZ();
return 0;
default:
return -1;
}
}
}
}
}
|
package com.irongs.todos;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.*;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.fortysevendeg.swipelistview.BaseSwipeListViewListener;
import com.fortysevendeg.swipelistview.SwipeListView;
import com.irongs.todoslib.TodoItem;
import com.irongs.todoslib.TodosContract;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public static final int TODO_ENTRY_DIALOG_REQUESTCODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id){
case R.id.action_new_todo_entry:
Intent intent = new Intent(this, TodoEntryDetail.class);
startActivityForResult(intent, TODO_ENTRY_DIALOG_REQUESTCODE);
//AlertDialog dialog = new AlertDialog.Builder(this).setView(R.layout.activity_todo_entry_detail).show();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == TODO_ENTRY_DIALOG_REQUESTCODE){
if(resultCode == RESULT_OK){
ContentValues values = new ContentValues();
values.put(TodosContract.TodoEntry.COLUMN_NAME_TEXT, data.getStringExtra(TodosContract.TodoEntry.COLUMN_NAME_TEXT));
values.put(TodosContract.TodoEntry.COLUMN_NAME_STATUS, 0);
values.put(TodosContract.TodoEntry.COLUMN_NAME_CREATEDAT, System.currentTimeMillis()/1000);
getContentResolver().insert(TodosContract.TodoEntry.TABLE_CONTENTURI, values);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
protected static final String TAG = "MainActivity.PlaceholderFragment";
private SwipeListView todosList;
private static TodoCursorAdapter adapter;
public static final String[] PROJECTION = new String[]{
TodosContract.TodoEntry._ID,
TodosContract.TodoEntry.COLUMN_NAME_TEXT,
TodosContract.TodoEntry.COLUMN_NAME_STATUS,
TodosContract.TodoEntry.COLUMN_NAME_CREATEDAT,
TodosContract.TodoEntry.COLUMN_NAME_COMPLETEDAT
};
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
todosList = (SwipeListView)rootView.findViewById(R.id.todos_list);
adapter = new TodoCursorAdapter(container.getContext(), null, true);
todosList.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
todosList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(container.getContext(), "Clicked on item: " + id, Toast.LENGTH_SHORT).show();
}
});
todosList.setSwipeListViewListener(new BaseSwipeListViewListener()
{
@Override
public void onChoiceChanged(int position, boolean selected)
{
Log.d(TAG, "onChoiceChanged:" + position + ", " + selected);
}
@Override
public void onChoiceEnded()
{
Log.d(TAG, "onChoiceEnded");
}
@Override
public void onChoiceStarted()
{
Log.d(TAG, "onChoiceStarted");
}
@Override
public void onClickBackView(int position)
{
Log.d(TAG, "onClickBackView:" + position);
}
@Override
public void onClickFrontView(int position)
{
Log.d(TAG, "onClickFrontView:" + position);
}
@Override
public void onClosed(int position, boolean fromRight)
{
Log.d(TAG, "onClosed:" + position + "," + fromRight);
}
@Override
public void onDismiss(int[] reverseSortedPositions)
{
Log.d(TAG, "onDismiss");
}
@Override
public void onFirstListItem()
{
Log.d(TAG, "onFirstListItem");
}
@Override
public void onLastListItem()
{
Log.d(TAG, "onLastListItem");
}
@Override
public void onListChanged()
{
Log.d(TAG, "onListChanged");
todosList.closeOpenedItems();
}
@Override
public void onMove(int position, float x)
{
Log.d(TAG, "onMove:" + position + "," + x);
}
@Override
public void onOpened(int position, boolean toRight)
{
Log.d(TAG, "onOpened:" + position + "," + toRight);
}
@Override
public void onStartClose(int position, boolean right)
{
Log.d(TAG, "onStartClose:" + position + "," + right);
}
@Override
public void onStartOpen(int position, int action, boolean right)
{
Log.d(TAG, "onStartOpen:" + position + "," + action + ","
+ right);
}
});
return rootView;
}
@Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(getActivity(), TodosContract.TodoEntry.TABLE_CONTENTURI, PROJECTION, null, null, null);
return loader;
}
@Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data) {
adapter.changeCursor(data);
Log.d("Main", "onLoadFinished");
}
@Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader) {
adapter.changeCursor(null);
Log.d("Main", "onLoaderReset");
}
}
}
|
package com.bijay.myanswer.chapter5;
import com.insightfullogic.java8.exercises.Exercises;
public class Fibonacci {
public Fibonacci() {
}
public long fibonacci(int x) {
return Exercises.replaceThisWithSolution();
}
}
|
package kyle.game.besiege;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import kyle.game.besiege.battle.QuickBattleGame;
public class BattleLauncher {
public static void main (String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.useGL20 = true;
config.title = BesiegeMain.GAME_NAME + " Battle Simulator";
LwjglApplication app = new LwjglApplication(new QuickBattleGame(), config);
config.addIcon("textures/icon-temple.png", Files.FileType.Internal);
config.width = 1280;
config.height = 800;
}
}
|
package com.adelean.elasticsearch.word2vec.model;
import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.ElasticsearchClient;
import org.elasticsearch.common.Table;
public final class ModelListAction extends Action<
ModelListAction.ModelListActionRequest,
ModelListAction.ModelListActionResponse,
ModelListAction.ModelListActionRequest.Builder> {
public static final String NAME = "cluster:admin/word2vec/models/list";
public static final ModelListAction INSTANCE = new ModelListAction();
protected ModelListAction() {
super(NAME);
}
@Override
public ModelListActionRequest.Builder newRequestBuilder(ElasticsearchClient client) {
return new ModelListActionRequest.Builder(client);
}
@Override
public ModelListActionResponse newResponse() {
return new ModelListActionResponse();
}
public static final class ModelListActionRequest extends ActionRequest {
@Override
public ActionRequestValidationException validate() {
return null;
}
static final class Builder extends ActionRequestBuilder<ModelListActionRequest, ModelListActionResponse, Builder> {
Builder(ElasticsearchClient client) {
super(client, INSTANCE, new ModelListActionRequest());
}
}
}
public static final class ModelListActionResponse extends ActionResponse {
private Table modelsTable;
public ModelListActionResponse() {
}
public ModelListActionResponse(Table modelsTable) {
this.modelsTable = modelsTable;
}
public Table getModelsTable() {
return modelsTable;
}
public void setModelsTable(Table modelsTable) {
this.modelsTable = modelsTable;
}
}
}
|
package com.example.user.myapplication.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.user.myapplication.util.Constants;
/**
* Created by kimmin-young on 2016. 3. 3..
*/
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public static final String TABLE = "product";
public static final String NO = "no";
public static final String URL = "url";
public static final String LOC1 = "loc1";
public static final String LOC2 = "loc2";
public static final String POINT = "point";
public static final String SDATE = "sdate";
public static final String FDATE = "fdate";
public static final String TITLE = "title";
public static final String DESCR = "descr";
public static final String DEPT = "dept";
public MySQLiteOpenHelper(Context context) {
super(context, "product", null, 1);
Log.e(Constants.SQLITE, "generated");
}
@Override
public void onCreate(SQLiteDatabase db) {
String query = "create table "+TABLE+
"("+NO+" INTEGER PRIMARY KEY AUTOINCREMENT," +
URL+" TEXT," +
LOC1+" TEXT," +
LOC2+" TEXT," +
POINT+" INTEGER," +
SDATE+" TEXT," +
FDATE+" TEXT," +
TITLE+" TEXT," +
DESCR+" TEXT," +
DEPT+" TEXT);";
Log.e(Constants.SQLITE,query);
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query="drop table if exists "+TABLE;
Log.e(Constants.SQLITE,query);
onCreate(db);
}
}
|
package banking.menus.standard_user;
import banking.exceptions.ExitingException;
import banking.menus.Menu;
public class SingleCardMenu extends Menu {
protected String commands ="((display|edit)-card(-(info|pin))?)";
private static Menu menu = null;
public static Menu getMenu() {
if(menu == null) {
menu = new SingleCardMenu();
}
return menu;
}
private SingleCardMenu() {
}
public boolean parseCommand(String command) throws ExitingException {
if(!super.parseCommand(command)) {
//PARSE UNDER CURRENT MENU
//IF FOUND
//TRUE
//FALSE
return false;
}
return true;
}
public String getName() {
return "";
}
@Override
public void getHelp() {
// TODO Auto-generated method stub
}
}
|
package com.tencent.mm.plugin.h.a.a;
class f$8 implements Runnable {
final /* synthetic */ f hfj;
final /* synthetic */ int hfm;
final /* synthetic */ String hfn;
final /* synthetic */ e hfo;
f$8(f fVar, int i, String str, e eVar) {
this.hfj = fVar;
this.hfm = i;
this.hfn = str;
this.hfo = eVar;
}
public final void run() {
f.d(this.hfj).a(this.hfm, this.hfn, this.hfo);
}
}
|
package com.zhouyi.business.core.dao;
import com.zhouyi.business.core.model.SysLogOperation;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
import java.util.Map;
@Mapper
public interface SysLogOperationMapper {
int deleteByPrimaryKey(String pkId);
int insert(SysLogOperation record);
int insertSelective(SysLogOperation record);
SysLogOperation selectByPrimaryKey(String pkId);
int updateByPrimaryKeySelective(SysLogOperation record);
int updateByPrimaryKey(SysLogOperation record);
/**
* 根据条件分页查询系统操作日志
* @param conditions
* @return
*/
List<SysLogOperation> listSysLogOperationByConditions(Map<String,Object> conditions);
/**
* 根据条件查询系统日志记录数
* @param conditions
* @return
*/
int getSysLogOperationCountByConditions(Map<String,Object> conditions);
} |
package monopoly.model.field;
import monopoly.model.Owner;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
public class PropertyTest {
@Test
public void owner() {
String name = "This is a test name for field.";
final int price = 10;
Owner owner = mock(Owner.class);
Property property = new Property(name, 1, 1, 10, 1, 1, 1, 1, 1, 1, ColorGroup.Purple);
assertFalse(property.hasOwner());
property.setOwner(owner);
assertTrue(property.hasOwner());
assertEquals(owner, property.getOwner());
Property property2 = new Property(owner, name, 1, 1, 10, 1, 1, 1, 1, 1, 1, ColorGroup.Purple);
assertTrue(property2.hasOwner());
assertEquals(owner, property2.getOwner());
}
@Test
public void getPrice() {
String name = "This is a test name for field.";
final int price = 10;
Owner owner = mock(Owner.class);
Property property = new Property(owner, name, 1, 1, 10, 1, 1, 1, 1, 1, 1, ColorGroup.Purple);
assertEquals(price, property.getPrice());
}
@Test
public void getName() {
String name = "This is a test name for field.";
final int price = 10;
Owner owner = mock(Owner.class);
Property property = new Property(owner, name, 1, 1, 10, 1, 1, 1, 1, 1, 1, ColorGroup.Purple);
assertEquals(name, property.getName());
}
} |
package com.zer.redis.test;
import com.zer.redis.chapter.Chapter01;
import org.junit.Test;
/**
* @author zer
* @create 2016-11-24 11:03
*/
public class Chapter01Test {
@Test
public void run() {
new Chapter01().run();
}
}
|
package com.projeto.view.produto;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.TableRowSorter;
import com.projeto.model.models.Produto;
import com.projeto.model.service.ProdutoService;
import com.projeto.view.produto.TabelaProdutoModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.PatternSyntaxException;
public class BuscaProduto extends JDialog {
private static final long serialVersionUID = 3538690718870328680L;
private static final int CODIGO = 0;
private static final int NOME = 1;
private static final int VALOR_VENDA = 2;
private static final int DESCRICAO = 3;
private final JPanel contentPanel = new JPanel();
private JLabel lblNewLabel;
private JTextField textField;
private JScrollPane scrollPane;
private JTable tableProduto;
private TabelaProdutoModel tabelaProdutoModel;
private TableRowSorter<TabelaProdutoModel> sortTabelaProduto;
private List<Produto> listaProduto;
private Integer codigoProduto;
private String nomeProduto;
private double valor_vendaProduto;
private String descricaoProduto;
private boolean selectProduto;
public void setSelectProduto(boolean selectProduto) {
this.selectProduto = selectProduto;
}
public BuscaProduto(JFrame frame, boolean modal) {
super(frame, modal);
initComponents();
setResizable(false);
iniciarDados();
}
private void iniciarDados() {
listaProduto = new ArrayList<Produto>();
}
private void initComponents() {
setBounds(100, 100, 611, 411);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
lblNewLabel = new JLabel("Pesquisar Nome do Produto:");
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
String filtro = textField.getText();
filtraNomeProduto(filtro);
}
});
textField.setColumns(10);
scrollPane = new JScrollPane();
GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
gl_contentPanel.setHorizontalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addComponent(lblNewLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, 401, GroupLayout.PREFERRED_SIZE))
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 541, GroupLayout.PREFERRED_SIZE))
.addContainerGap(34, Short.MAX_VALUE))
);
gl_contentPanel.setVerticalGroup(
gl_contentPanel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPanel.createSequentialGroup()
.addGap(22)
.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
.addComponent(lblNewLabel)
.addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 220, GroupLayout.PREFERRED_SIZE)
.addContainerGap(61, Short.MAX_VALUE))
);
tableProduto = new JTable();
tabelaProdutoModel = new TabelaProdutoModel();
tabelaProdutoModel.setListaProduto(carregarListaProduto());
tableProduto.setModel(tabelaProdutoModel);
scrollPane.setViewportView(tableProduto);
tableProduto.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
sortTabelaProduto = new TableRowSorter<TabelaProdutoModel>(tabelaProdutoModel);
tableProduto.setRowSorter(sortTabelaProduto);
tableProduto.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
contentPanel.setLayout(gl_contentPanel);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selecionaProduto();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setSelectProduto(false);
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
protected void selecionaProduto() {
if(tableProduto.getSelectedRow() != -1 && tableProduto.getSelectedRow() < tabelaProdutoModel.getRowCount()) {
setCodigoProduto(Integer.valueOf(tableProduto.getValueAt(tableProduto.getSelectedRow(), CODIGO).toString()));
setNomeProduto(tableProduto.getValueAt(tableProduto.getSelectedRow(), NOME).toString());
setValor_vendaProduto(Double.valueOf(tableProduto.getValueAt(tableProduto.getSelectedRow(), VALOR_VENDA).toString()));
setDescricaoProduto(tableProduto.getValueAt(tableProduto.getSelectedRow(), DESCRICAO).toString());
setSelectProduto(true);
dispose();
} else {
setSelectProduto(false);
}
}
private List<Produto> carregarListaProduto() {
ProdutoService produtoService = new ProdutoService();
return produtoService.findAll();
}
private void filtraNomeProduto(String filtro) {
RowFilter<TabelaProdutoModel, Object> rowFilter = null;
try {
rowFilter = RowFilter.regexFilter(filtro);
} catch(PatternSyntaxException e) {
return;
}
sortTabelaProduto.setRowFilter(rowFilter);
}
public Integer getCodigoProduto() {
return codigoProduto;
}
public void setCodigoProduto(Integer codigoProduto) {
this.codigoProduto = codigoProduto;
}
public String getNomeProduto() {
return nomeProduto;
}
public void setNomeProduto(String nomeProduto) {
this.nomeProduto = nomeProduto;
}
public double getValor_vendaProduto() {
return valor_vendaProduto;
}
public void setValor_vendaProduto(double valor_vendaProduto) {
this.valor_vendaProduto = valor_vendaProduto;
}
public String getDescricaoProduto() {
return descricaoProduto;
}
public void setDescricaoProduto(String descricaoProduto) {
this.descricaoProduto = descricaoProduto;
}
public boolean isSelectProduto() {
return selectProduto;
}
}
|
/*
* 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 pe.gob.onpe.adan.model.adan;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
*
* @author bvaldez
*/
@Entity
@Table(name = "TAB_CONFIGURACION")
public class Configuracion {
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_CONFIGURACION")
@SequenceGenerator(name = "SEQ_CONFIGURACION", sequenceName = "SEQ_CONFIGURACION_PK")
@Column(name = "N_CONFIGURACION_PK")
private int id;
@Column(name = "C_DESCRIPCION")
private String descripcion;
@Column(name = "C_DATO")
private String dato;
@Column(name = "N_CANT_COLUMNAS")
private int cantColumnas;
@Column(name = "C_COLUM_RPT")
private String columRpt;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getDato() {
return dato;
}
public void setDato(String dato) {
this.dato = dato;
}
public int getCantColumnas() {
return cantColumnas;
}
public void setCantColumnas(int cantColumnas) {
this.cantColumnas = cantColumnas;
}
public String getColumRpt() {
return columRpt;
}
public void setColumRpt(String columRpt) {
this.columRpt = columRpt;
}
}
|
package br.com.ite.fragments;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import java.io.IOException;
import br.com.ite.R;
import br.com.ite.interfaces.LoginAPI;
import br.com.ite.interfaces.OnLoginCallback;
import br.com.ite.models.Student;
import br.com.ite.utils.GlobalNames;
import br.com.ite.utils.SnackAlert;
import br.com.ite.utils.network.NetworkUtils;
import br.com.ite.utils.network.ServiceGenerator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by leonardo.borges on 26/01/2017.
*/
public class LoginFragment extends AppCompatDialogFragment {
private EditText login;
private EditText password;
private boolean isShowingPassword = false;
private boolean loginSucceed = false;
private OnLoginCallback callback = null;
public enum LOGIN_RESULT {
SUCCESS,
FAILED
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View fragment = inflater.inflate(R.layout.login_fragment, parent, false);
login = (EditText) fragment.findViewById(R.id.login_student_id);
setPasswordVisibility(fragment);
Button enter = (Button) fragment.findViewById(R.id.login_enter);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
validateData(v);
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (getArguments() != null) {
Bundle args = getArguments();
callback = (OnLoginCallback) args.getSerializable(GlobalNames.ITE_LOGIN_CALLBACK);
}
return fragment;
}
private void validateData(View v) throws IOException {
// Close keyboard to show SnackBar message (if error occurs)
InputMethodManager imm = (InputMethodManager) getActivity().getApplicationContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView()
.getRootView().getWindowToken(), 0);
if (login.getText().toString().trim().isEmpty()) {
SnackAlert.errorMessage(v, getString(R.string.loginStudentIdObligatory));
login.requestFocus();
}
else if (password.getText().toString().isEmpty()) {
SnackAlert.errorMessage(v, getString(R.string.loginPasswordObligatory));
password.requestFocus();
}
else {
authentication(v);
}
}
private void authentication(final View v) throws IOException {
if (!NetworkUtils.checkInternetConnection(getActivity())) return;
LoginAPI loginApi = ServiceGenerator.createService(LoginAPI.class);
Call<Student> call = loginApi.postLogin(GlobalNames.ITE_CONTENT_TYPE_URLENCODED,
login.getText().toString(),
password.getText().toString());
call.enqueue(new Callback<Student>() {
@Override
public void onResponse(Call<Student> call, Response<Student> response) {
if (response.code() == 200 && response.body() != null) {
loginSucceed = true;
SharedPreferences preferences = getActivity()
.getSharedPreferences(GlobalNames.ITE_PREFERENCES, Context.MODE_PRIVATE);
preferences.edit().putString(GlobalNames.ITE_PREFERENCES_USER_ID,
login.getText().toString()).commit();
preferences.edit().putString(GlobalNames.ITE_PREFERENCES_USER_PASSWORD,
password.getText().toString()).commit();
preferences.edit().putBoolean(GlobalNames.ITE_PREFERENCES_IS_LOGGED,
true).commit();
if (getDialog() != null) {
dismiss();
}
else {
setCallback();
}
}
else {
loginSucceed = false;
SnackAlert.errorMessage(v, getString(R.string.loginEmptyStudentError));
}
}
@Override
public void onFailure(Call<Student> call, Throwable t) {
loginSucceed = false;
setCallback();
SnackAlert.errorMessage(v, getString(R.string.loginAuthenticationFailed));
}
});
}
@Override
public void onDismiss(final DialogInterface dialog) {
if (callback != null) {
setCallback();
}
}
private void setCallback() {
if (loginSucceed) {
callback.onLoginComplete(LOGIN_RESULT.SUCCESS);
}
else {
callback.onLoginComplete(LOGIN_RESULT.FAILED);
}
}
private void setPasswordVisibility(View fragment) {
password = (EditText) fragment.findViewById(R.id.login_password);
final ImageView passwordVisibility = (ImageView) fragment
.findViewById(R.id.login_password_visibility);
if (password != null && passwordVisibility != null) {
password.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
passwordVisibility.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
}
});
// Set password visibility (eye) behavior
passwordVisibility.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (password.getSelectionStart() != 0) {
// Change input type will reset cursor position, so we want to save it
final Integer cursor = password.getSelectionStart();
if (!isShowingPassword) {
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
isShowingPassword = true;
passwordVisibility.setImageResource(R.drawable.ic_visibility_on);
} else {
password.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
isShowingPassword = false;
passwordVisibility.setImageResource(R.drawable.ic_visibility_off);
}
passwordVisibility.setColorFilter(getActivity()
.getApplicationContext().getResources()
.getColor(R.color.darkGray), PorterDuff.Mode.SRC_ATOP);
if (cursor != null) {
password.setSelection(cursor);
} else {
password.setSelection(0);
}
}
}
});
}
}
}
|
package za.ac.cput.demospring;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.util.ArrayList;
public class CourseTest {
private Course course,course1;
private Course degree;
private ArrayList<Subject> subjects;
@Before
public void setUp() throws Exception {
subjects = new ArrayList<>();
subjects.add(new Subject.Builder().subId(122).name("Communication Network").isCompulsory(false).build());
subjects.add(new Subject.Builder().subId(123).name("Multimedia").isCompulsory(false).build());
subjects.add(new Subject.Builder().subId(122).name("Project Management").isCompulsory(false).build());
subjects.add(new Subject.Builder().subId(122).name("Professional Practise").isCompulsory(false).build());
course = new Course
.Builder()
.courseNum(214)
.name("Information Technology")
.duration("3 years")
.subjects(subjects)
.build();
course1 = new Course
.Builder()
.courseNum(214)
.name("Information Technology")
.duration("3 years")
.subjects(subjects)
.build();
}
@Ignore
@Test
public void getCourseNum() {
Assert.assertEquals(course.getCourseNum(),215);
}
@Test(expected = AssertionError.class)
public void getName() {
Assert.assertEquals(course.getName(),"Information Technology");
}
@Test(timeout = 10000)
public void getSubjects() {
Assert.assertEquals(course.getSubjects(),null);while (true);
}
@Test
public void getDuration() {
Assert.assertEquals(course.getDuration(),"3 years");
}
@Test
public void testObjectEquality(){
Assert.assertEquals(course1,course);
}
/*
* this test tests object identity
* it also has a timeout,that is it will give error after the elapsed time expires*/
@Test(timeout = 10000)
public void testObjectIdentity(){
course1 = course;
Assert.assertSame(course1,course);
while (true);
}
} |
package fr.bodysplash.bwish.server.entrepot;
import java.util.List;
import fr.bodysplash.bwish.domain.Personne;
public interface EntrepotPersonnes {
void ajouter(Personne julie);
List<Personne> getToutes();
Personne getParClef(String key);
void supprimer(Personne personne);
}
|
package com.spring.boot.rocks.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.spring.boot.rocks.model.AppRole;
import com.spring.boot.rocks.repository.RoleRepository;
@Service("roleService")
@Transactional(timeout = 5)
public class AppRoleServiceImpl implements AppRoleService {
@Autowired
RoleRepository roleRepo;
@Override
public AppRole findByid(int id) {
return roleRepo.findById(id);
}
}
|
package com.stem.util;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JaxbUtlils {
public static String bean2Xml(Object obj){
JAXBContext context;
String xml = "";
try{
context = JAXBContext.newInstance(obj.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
StringWriter sw = new StringWriter();
marshaller.marshal(obj, sw);
xml = sw.toString();
sw.close();
sw = null;
} catch (JAXBException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return xml;
}
}
|
package com.cannapaceus.grader;
import com.cannapaceus.qbank.Question;
import com.cannapaceus.qbank.eQuestionAssignmentType;
import com.cannapaceus.qbank.eQuestionLevel;
import com.cannapaceus.qbank.eQuestionType;
import java.sql.*;
import java.util.*;
public class DBService {
private static DBService instance = null;
private String conString = "jdbc:h2:~/IGP;";
private String user;
private String pass;
public static DBService getInstance() {
if (instance == null)
instance = new DBService();
return instance;
}
private DBService() { };
public String loginDB(String username, String password) {
String errMessage = null;
user = username;
pass = password;
errMessage = initConnection();
return errMessage;
}
private String initConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(conString + "IFEXISTS=TRUE", user, pass);
return null;
} catch (SQLException e) {
if (e.getErrorCode() == 90013) {
return "Database does not exist";
} else if (e.getErrorCode() == 28000) {
return "Incorrect username or password";
} else {
e.printStackTrace();
}
return "Failed to connect to Database";
} catch (Exception e) {
e.printStackTrace();
return "Failed to connect to Database";
}finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
}
public void databaseSetup() {
Connection con = null;
Statement stm = null;
try {
con = DriverManager.getConnection(conString, user, pass);
stm = con.createStatement();
stm.execute("CREATE TABLE TERMS (\n" +
"TERMID IDENTITY,\n" +
"ESEASON ENUM ('Winter', 'Spring', 'Summer', 'Fall'),\n" +
"IYEAR INT,\n" +
"BARCHIVED BOOLEAN\n" +
");");
stm.execute("CREATE TABLE COURSES ( \n" +
"COURSEID IDENTITY, \n" +
"SCOURSENAME VARCHAR (255), \n" +
"SCOURSEID VARCHAR (50),\n" +
"SCOURSEDEPT VARCHAR (50),\n" +
"FMEAN REAL, \n" +
"FMEDIAN REAL, \n" +
"FMODE REAL, \n" +
"FSTDDEV REAL, \n" +
"BARCHIVED BOOLEAN, \n" +
"ITERM BIGINT NOT NULL, \n" +
"FSCALE REAL, \n" +
"IDROPUNCAT INT \n" +
");");
stm.execute("CREATE TABLE CATEGORIES (\n" +
"CATEGORYID IDENTITY,\n" +
"SCATEGORYNAME VARCHAR (255),\n" +
"FWEIGHT REAL,\n" +
"IDROPPED INT, \n" +
"ICOURSE BIGINT NOT NULL\n" +
");");
stm.execute("CREATE TABLE ASSIGNMENTS (\n" +
"ASSIGNMENTID IDENTITY,\n" +
"SASSIGNMENTNAME VARCHAR (255),\n" +
"DTDUEDATE DATE,\n" +
"DTASSIGNEDDATE DATE,\n" +
"FMEAN REAL,\n" +
"FMEDIAN REAL,\n" +
"FMODE REAL,\n" +
"FSTDDEV REAL,\n" +
"BDROPPED BOOLEAN,\n" +
"FMAXSCORE REAL,\n" +
"FWEIGHT REAL,\n" +
"ICATEGORY BIGINT,\n" +
"ICOURSE BIGINT NOT NULL\n" +
");");
stm.execute("CREATE TABLE GRADES (\n" +
"GRADEID IDENTITY,\n" +
"FGRADE REAL,\n" +
"BSUBMITTED BOOLEAN,\n" +
"BOVERDUE BOOLEAN,\n" +
"BMISSING BOOLEAN,\n" +
"BDROPPED BOOLEAN,\n" +
"IASSIGNMENT BIGINT NOT NULL,\n" +
"ISTUDENT BIGINT NOT NULL,\n" +
"ICOURSE BIGINT NOT NULL,\n" +
");");
stm.execute("CREATE TABLE STUDENTS (\n" +
"STUDENTID IDENTITY,\n" +
"SFIRSTMINAME VARCHAR(255),\n" +
"SLASTNAME VARCHAR(255),\n" +
"SSTUDENTID VARCHAR(50),\n" +
"SEMAIL VARCHAR(255),\n" +
"FAVERAGE REAL,\n" +
"ICOURSE BIGINT NOT NULL\n" +
");");
stm.execute("CREATE TABLE QUESTIONS (\n" +
"QUESTIONID IDENTITY,\n" +
"SQUESTION TEXT,\n" +
"EQUESTIONTYPE ENUM ('MC', 'FITB', 'TOF', 'SA', 'LA'),\n" +
"EQUESTIONLEVEL ENUM ('EASY', 'MEDIUM', 'HARD', 'HOTS'),\n" +
"EQUESTIONASSIGNMENTTYPE ENUM ('TEST', 'QUIZ', 'HW', 'OTHER'),\n" +
"FMINS REAL,\n" +
"ARRSANSWERS ARRAY,\n" +
"FSCORE REAL,\n" +
"ICOURSE BIGINT NOT NULL\n" +
");");
stm.execute("CREATE TABLE SETTINGS (\n" +
"EMAIL VARCHAR(255),\n" +
"EMPASS VARCHAR(255)\n" +
");");
stm.execute("INSERT INTO SETTINGS " +
"(EMAIL, EMPASS) " +
"VALUES " +
"('', '')");
} catch (Exception e) {
e.printStackTrace();
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
}
/**
* Function to store a term in the database and set the DBID of the term that was passed in
* @param termToStore
* @return true if the term was stored successfully
*/
public boolean storeTerm(Term termToStore) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "INSERT INTO TERMS " +
"(ESEASON, IYEAR, BARCHIVED) " +
"VALUES " +
"(?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setString(1, termToStore.getSeason().toString());
stm.setInt(2, termToStore.getYear());
stm.setBoolean(3, termToStore.getArchivedStatus());
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
termToStore.setDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
/**
* Function to store a course in the database and set the DBID of the course that was passed in
* @param courseToStore
* @param lTermID ID of the term that the course belongs to
* @return true if the course was stored successfully
*/
public boolean storeCourse(Course courseToStore, long lTermID) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "INSERT INTO COURSES " +
"(SCOURSENAME, SCOURSEID, SCOURSEDEPT, FMEAN, FMEDIAN, FMODE, FSTDDEV, BARCHIVED, ITERM, FSCALE, IDROPUNCAT) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setString(1, courseToStore.getCourseName());
stm.setString(2, courseToStore.getCourseID());
stm.setString(3, courseToStore.getDepartment());
stm.setFloat(4, courseToStore.getStCourseStats().getMean()); //TODO: stm.setFloat(4, courseToStore.getStatistics().getMean());
stm.setFloat(5, courseToStore.getStCourseStats().getMedian()); //TODO: stm.setFloat(5, courseToStore.getStatistics().getMedian());
stm.setFloat(6, courseToStore.getStCourseStats().getMode()); //TODO: stm.setFloat(6, courseToStore.getStatistics().getMode());
stm.setFloat(7, courseToStore.getStCourseStats().getStandardDev()); //TODO: stm.setFloat(7, courseToStore.getStatistics().getStdDev());
stm.setBoolean(8, courseToStore.getBArchived());
stm.setLong(9, lTermID);
stm.setFloat(10, courseToStore.getScale());
stm.setInt(11, courseToStore.getDropUncategorized());
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
courseToStore.setDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
/**
* Function to store a category in the database and set the DBID of the category that was passed in
* @param categoryToStore
* @param lCourseID ID of the course that the category belongs to
* @return true if the category was stored successfully
*/
public boolean storeCategory(Category categoryToStore, long lCourseID) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "INSERT INTO CATEGORIES " +
"(SCATEGORYNAME, FWEIGHT, IDROPPED, ICOURSE) " +
"VALUES " +
"(?, ?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setString(1, categoryToStore.getName());
stm.setFloat(2, categoryToStore.getWeight());
stm.setInt(3, categoryToStore.getDropped());
stm.setLong(4, lCourseID);
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
categoryToStore.setDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
/**
* Function to store an assignment in the database and set the DBID of the assignment that was passed in
* @param assignmentToStore
* @param lCourseID ID of the course that the assignment belongs to
* @return true if the assignment was stored successfully
*/
public boolean storeAssignment(Assignment assignmentToStore, long lCourseID) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
Category catCopy = assignmentToStore.getCategoryReference();
long lCategoryID = 0;
if (catCopy != null) {
lCategoryID = catCopy.getDBID();
}
try {
String sql = "INSERT INTO ASSIGNMENTS " +
"(SASSIGNMENTNAME, DTDUEDATE, DTASSIGNEDDATE, FMEAN, FMEDIAN, FMODE, FSTDDEV, BDROPPED, FMAXSCORE, " +
"FWEIGHT, ICATEGORY, ICOURSE) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setString(1, assignmentToStore.getAssignmentName());
stm.setDate(2, java.sql.Date.valueOf(assignmentToStore.getDueDate()));
stm.setDate(3, java.sql.Date.valueOf(assignmentToStore.getAssignedDate()));
stm.setFloat(4, assignmentToStore.getStAssignmentStats().getMean());
stm.setFloat(5, assignmentToStore.getStAssignmentStats().getMedian());
stm.setFloat(6, assignmentToStore.getStAssignmentStats().getMode());
stm.setFloat(7, assignmentToStore.getStAssignmentStats().getStandardDev());
stm.setBoolean(8, assignmentToStore.getDroppedAssignment());
stm.setFloat(9, assignmentToStore.getMaxScore());
if(assignmentToStore.getWeight()==null)
{
stm.setNull(10, Types.FLOAT);
}
else {
stm.setFloat(10, assignmentToStore.getWeight());
}
stm.setLong(11, lCategoryID);
stm.setLong(12, lCourseID);
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
assignmentToStore.setDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
/**
* Function to store a student in the database and set the DBID of the student that was passed in
* @param studentToStore
* @param lCourseID ID of the course that the student belongs to
* @return true if the student was stored successfully
*/
public boolean storeStudent(Student studentToStore, long lCourseID) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "INSERT INTO STUDENTS " +
"(SFIRSTMINAME, SLASTNAME, SSTUDENTID, SEMAIL, FAVERAGE, ICOURSE) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setString(1, studentToStore.getFirstMIName());
stm.setString(2, studentToStore.getLastName());
stm.setString(3, studentToStore.getStudentID());
stm.setString(4, studentToStore.getStudentEmail());
stm.setFloat(5, studentToStore.getAverageGrade());
stm.setLong(6, lCourseID);
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
studentToStore.setDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
/**
* Function to store a grade in the database and set the DBID of the grade that was passed in
* @param gradeToStore
* @param lCourseID ID of the course that the grade belongs to
* @return true if the grade was stored successfully
*/
public boolean storeGrade(Grade gradeToStore, long lCourseID) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
Assignment assign = gradeToStore.getAssignmentReference();
Student stu = gradeToStore.getStudentReference();
long lAssignmentID = 0;
long lStudentID = 0;
if (assign != null) {
lAssignmentID = assign.getDBID();
}
if (stu != null) {
lStudentID = stu.getDBID();
}
try {
String sql = "INSERT INTO GRADES " +
"(FGRADE, BSUBMITTED, BOVERDUE, BMISSING, BDROPPED, IASSIGNMENT, ISTUDENT, ICOURSE) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setFloat(1, gradeToStore.getGrade());
stm.setBoolean(2, gradeToStore.getSubmitted());
stm.setBoolean(3, gradeToStore.getOverdue());
stm.setBoolean(4, gradeToStore.getMissing());
stm.setBoolean(5, gradeToStore.getDropped());
stm.setLong(6, lAssignmentID);
stm.setLong(7, lStudentID);
stm.setLong(8, lCourseID);
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
gradeToStore.setDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public boolean storeQuestion(Question questionToStore, long lCourseID) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "INSERT INTO QUESTIONS " +
"(SQUESTION, EQUESTIONTYPE, EQUESTIONLEVEL, EQUESTIONASSIGNMENTTYPE, FMINS, ARRSANSWERS, FSCORE, ICOURSE) " +
"VALUES " +
"(?, ?, ?, ?, ?, ?, ?, ?)";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
Array arr = null;
if (questionToStore.getAnswers() != null)
arr = con.createArrayOf("VARCHAR", questionToStore.getAnswers().toArray());
stm.setString(1, questionToStore.getQuestion());
stm.setInt(2, questionToStore.getQuestionType().getInt());
stm.setInt(3, questionToStore.getQuestionLevel().getInt());
stm.setInt(4, questionToStore.getQuestionAssignmentType().getInt());
stm.setFloat(5, questionToStore.getToDoTime());
stm.setArray(6, arr);
stm.setFloat(7, questionToStore.getScore());
stm.setLong(8, lCourseID);
stm.executeUpdate();
rs = stm.getGeneratedKeys();
rs.next();
questionToStore.setlDBID(rs.getLong(1));
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean updateTerm(Term t) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE TERMS " +
"SET ESEASON = ?, IYEAR = ?, BARCHIVED = ? " +
"WHERE TERMID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, t.getSeason().toString());
stm.setInt(2, t.getYear());
stm.setBoolean(3, t.getArchivedStatus());
stm.setLong(4, t.getDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean updateCourse(Course c) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE COURSES " +
"SET SCOURSENAME = ?, SCOURSEID = ?, SCOURSEDEPT = ?, FMEAN = ?, " +
"FMEDIAN = ?, FMODE = ?, FSTDDEV = ?, BARCHIVED = ?, FSCALE = ?, IDROPUNCAT = ? " +
"WHERE COURSEID = ? ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, c.getCourseName());
stm.setString(2, c.getCourseID());
stm.setString(3, c.getDepartment());
stm.setFloat(4, c.getStCourseStats().getMean()); //TODO: stm.setFloat(4, courseToStore.getStatistics().getMean());
stm.setFloat(5, c.getStCourseStats().getMedian()); //TODO: stm.setFloat(5, courseToStore.getStatistics().getMedian());
stm.setFloat(6, c.getStCourseStats().getMode()); //TODO: stm.setFloat(6, courseToStore.getStatistics().getMode());
stm.setFloat(7, c.getStCourseStats().getStandardDev()); //TODO: stm.setFloat(7, courseToStore.getStatistics().getStdDev());
stm.setBoolean(8, c.getBArchived());
stm.setFloat(9,c.getScale());
stm.setInt(10, c.getDropUncategorized());
stm.setLong(11, c.getDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean updateCategory(Category cat) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE CATEGORIES " +
"SET SCATEGORYNAME = ?, FWEIGHT = ?, IDROPPED = ? " +
"WHERE CATEGORYID = ? ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, cat.getName());
stm.setFloat(2, cat.getWeight());
stm.setLong(3, cat.getDropped());
stm.setLong(4, cat.getDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean updateStudent(Student s) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE STUDENTS " +
"SET SFIRSTMINAME = ?, SLASTNAME = ?, SSTUDENTID = ?, SEMAIL = ?, FAVERAGE = ? " +
"WHERE STUDENTID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, s.getFirstMIName());
stm.setString(2, s.getLastName());
stm.setString(3, s.getStudentID());
stm.setString(4, s.getStudentEmail());
stm.setFloat(5, s.getAverageGrade());
stm.setLong(6, s.getDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean updateAssignment(Assignment a) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
Category catCopy = a.getCategoryReference();
long lCategoryID = 0;
if (catCopy != null) {
lCategoryID = catCopy.getDBID();
}
try {
String sql = "UPDATE ASSIGNMENTS " +
"SET SASSIGNMENTNAME = ?, DTDUEDATE = ?, DTASSIGNEDDATE = ?, FMEAN = ?, FMEDIAN = ?, " +
"FMODE = ?, FSTDDEV = ?, BDROPPED = ?, FMAXSCORE = ?, FWEIGHT = ?, ICATEGORY = ? " +
"WHERE ASSIGNMENTID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, a.getAssignmentName());
stm.setDate(2, java.sql.Date.valueOf(a.getDueDate()));
stm.setDate(3, java.sql.Date.valueOf(a.getAssignedDate()));
stm.setFloat(4, a.getStAssignmentStats().getMean());
stm.setFloat(5, a.getStAssignmentStats().getMedian());
stm.setFloat(6, a.getStAssignmentStats().getMode());
stm.setFloat(7, a.getStAssignmentStats().getStandardDev());
stm.setBoolean(8, a.getDroppedAssignment());
stm.setFloat(9, a.getMaxScore());
if(a.getWeight()==null)
{
stm.setNull(10, Types.FLOAT);
}
else {
stm.setFloat(10, a.getWeight());
}
stm.setLong(11, lCategoryID);
stm.setLong(12, a.getDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean updateGrade(Grade g) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
Assignment assignCopy = g.getAssignmentCopy();
Student stuCopy = g.getStudentCopy();
long lAssignmentID = 0;
long lStudentID = 0;
if (assignCopy != null) {
lAssignmentID = assignCopy.getDBID();
}
if (stuCopy != null) {
lStudentID = stuCopy.getDBID();
}
try {
String sql = "UPDATE GRADES " +
"SET FGRADE = ?, BSUBMITTED = ?, BOVERDUE = ?, BMISSING = ?, " +
"BDROPPED = ?, IASSIGNMENT = ?, ISTUDENT = ? " +
"WHERE GRADEID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setFloat(1, g.getGrade());
stm.setBoolean(2, g.getSubmitted());
stm.setBoolean(3, g.getOverdue());
stm.setBoolean(4, g.getMissing());
stm.setBoolean(5, g.getDropped());
stm.setLong(6, lAssignmentID);
stm.setLong(7, lStudentID);
stm.setLong(8, g.getDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public boolean updateQuestion(Question q) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE QUESTIONS " +
"SET SQUESTION = ?, EQUESTIONTYPE = ?, EQUESTIONLEVEL = ?, EQUESTIONASSIGNMENTTYPE = ?, " +
"FMINS = ?, ARRSANSWERS = ?, FSCORE = ? " +
"WHERE QUESTIONID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
Object[] arr = null;
if (q.getAnswers() != null)
arr = q.getAnswers().toArray();
stm.setString(1, q.getQuestion());
stm.setInt(2, q.getQuestionType().getInt());
stm.setInt(3, q.getQuestionLevel().getInt());
stm.setInt(4, q.getQuestionAssignmentType().getInt());
stm.setFloat(5, q.getToDoTime());
stm.setObject(6, arr);
stm.setFloat(7, q.getScore());
stm.setLong(8, q.getlDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public boolean updateEmail(String s) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE SETTINGS " +
"SET EMAIL = ? ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, s);
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public boolean updateEmailPass(String s) {
boolean retValue = true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "UPDATE SETTINGS " +
"SET EMPASS = ? ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setString(1, s);
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean deleteTerm(Term t) {
boolean retValue = true;
if (t.getDBID() == 0)
return true;
for (Course c : t.getCourses()) {
if (!deleteCourse(c))
retValue = false;
}
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "DELETE FROM TERMS " +
"WHERE TERMID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setLong(1, t.getDBID());
stm.executeUpdate();
t.setDBID(0);
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean deleteCourse(Course c) {
boolean retValue = true;
if (c.getDBID() == 0)
return true;
for (Student s : c.getlStudents()) {
if (!deleteStudent(s))
retValue = false;
}
for (Category cat : c.getlCategories()) {
if (!deleteCategory(cat))
retValue = false;
}
for (Assignment a : c.getlAssignments()) {
if (!deleteAssignment(a))
retValue = false;
}
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "DELETE FROM COURSES " +
"WHERE COURSEID = ? ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setLong(1, c.getDBID());
stm.executeUpdate();
c.setDBID(0);
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean deleteCategory(Category cat) {
boolean retValue = true;
if (cat.getDBID() == 0)
return true;
for (Assignment a : cat.getAssignments()) {
a.setCategory(null);
}
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "DELETE FROM CATEGORIES " +
"WHERE CATEGORYID = ? ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setLong(1, cat.getDBID());
stm.executeUpdate();
cat.setDBID(0);
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean deleteStudent(Student s) {
boolean retValue = true;
if (s.getDBID() == 0)
return true;
for (Grade g : s.getGrades()) {
if (!deleteGrade(g))
retValue = false;
}
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "DELETE FROM STUDENTS " +
"WHERE STUDENTID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setLong(1, s.getDBID());
stm.executeUpdate();
s.setDBID(0);
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean deleteAssignment(Assignment a) {
boolean retValue = true;
if (a.getDBID() == 0)
return true;
for (Grade g : a.getGrades()) {
if (!deleteGrade(g))
retValue = false;
}
Connection con = null;
PreparedStatement stm = null;
Category catCopy = a.getCategoryReference();
long lCategoryID = 0;
if (catCopy != null) {
lCategoryID = catCopy.getDBID();
}
try {
String sql = "DELETE FROM ASSIGNMENTS " +
"WHERE ASSIGNMENTID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setLong(1, a.getDBID());
stm.executeUpdate();
a.setDBID(0);
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
private boolean deleteGrade(Grade g) {
boolean retValue = true;
if (g.getDBID() == 0)
return true;
Connection con = null;
PreparedStatement stm = null;
Assignment assignCopy = g.getAssignmentCopy();
Student stuCopy = g.getStudentCopy();
long lAssignmentID = 0;
long lStudentID = 0;
if (assignCopy != null) {
lAssignmentID = assignCopy.getDBID();
}
if (stuCopy != null) {
lStudentID = stuCopy.getDBID();
}
try {
String sql = "DELETE FROM GRADES " +
"WHERE GRADEID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setLong(1, g.getDBID());
stm.executeUpdate();
g.setDBID(0);
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public boolean deleteQuestion(Question q) {
boolean retValue = true;
if (q.getlDBID() == 0)
return true;
Connection con = null;
PreparedStatement stm = null;
try {
String sql = "DELETE FROM QUESTIONS " +
"WHERE QUESTIONID = ?";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stm.setLong(1, q.getlDBID());
stm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
retValue = false;
}finally {
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public ArrayList<Term> retrieveTerms() {
ArrayList<Term> retValue = new ArrayList<>();
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
ResultSet rsc = null;
try {
//Get the course with the ID passed in
String sql = "SELECT * FROM TERMS ORDER BY IYEAR, ESEASON";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
rs = stm.executeQuery();
if (rs != null) {
while (rs.next()) {
Term temp = new Term(rs.getInt(3), eSeason.values()[rs.getShort(2)]);
temp.setDBID(rs.getLong(1));
sql = "SELECT * FROM COURSES " +
"WHERE COURSES.ITERM = ? " +
"ORDER BY SCOURSENAME";
stm = con.prepareStatement(sql);
stm.setLong(1, temp.getDBID());
rsc = stm.executeQuery();
if (rsc != null) {
while(rsc.next()) {
Course tempCourse = new Course(rsc.getString(2),
rsc.getString(3),
rsc.getString(4));
tempCourse.setDBID(rsc.getLong(1));
temp.addCourse(tempCourse);
}
}
Collections.sort(temp.getCourses(), Course.nameComparator);
retValue.add(temp);
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (rsc != null) {
try {
rsc.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
Collections.sort(retValue, Term.termComparator);
return retValue;
}
public Course retrieveCourseData(long lCourseID) {
Course retValue = null;
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
//Get the course with the ID passed in
String sql = "SELECT TOP(1) * FROM COURSES " +
"WHERE COURSES.COURSEID = ? " +
"ORDER BY SCOURSENAME";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setLong(1, lCourseID);
rs = stm.executeQuery();
if (rs != null && rs.next()) {
retValue = new Course(rs.getString(2),
rs.getString(3),
rs.getString(4));
retValue.setDBID(rs.getLong(1));
Statistics tempStats = new Statistics();
tempStats.setMean(rs.getFloat(5));
tempStats.setMedian(rs.getFloat(6));
tempStats.setMode(rs.getFloat(7));
tempStats.setStandardDev(rs.getFloat(8));
retValue.setStCourseStats(tempStats);
retValue.setBArchived(rs.getBoolean(9));
retValue.setScale(rs.getFloat(11));
retValue.setDropUncategorized(rs.getInt(12));
//Get categories for the course
sql = "SELECT * FROM CATEGORIES " +
"WHERE CATEGORIES.ICOURSE = ? " +
"ORDER BY SCATEGORYNAME";
stm = con.prepareStatement(sql);
stm.setLong(1, lCourseID);
rs = stm.executeQuery();
if (rs != null) {
while(rs.next()) {
Category temp = new Category(rs.getString(2), rs.getFloat(3), rs.getInt(4));
temp.setDBID(rs.getLong(1));
retValue.addCategory(temp);
}
}
//Get Assignments for the course
sql = "SELECT * FROM ASSIGNMENTS " +
"WHERE ASSIGNMENTS.ICOURSE = ? " +
"ORDER BY SASSIGNMENTNAME";
stm = con.prepareStatement(sql);
stm.setLong(1, lCourseID);
rs = stm.executeQuery();
if (rs != null) {
while(rs.next()) {
//Set the assignment's category to the appropriate category in the course's list
long tempCatID = rs.getLong(12);
Category tempCat = null;
for (Category cat : retValue.getlCategories()) {
if(cat.getDBID() == tempCatID) {
tempCat = cat;
break;
}
}
Assignment temp;
rs.getFloat(11);
if(rs.wasNull()) {
temp = new Assignment(rs.getString(2),
rs.getDate(3).toLocalDate(),
rs.getDate(4).toLocalDate(),
rs.getBoolean(9),
rs.getFloat(10),
tempCat,
null);
}
else {
temp = new Assignment(rs.getString(2),
rs.getDate(3).toLocalDate(),
rs.getDate(4).toLocalDate(),
rs.getBoolean(9),
rs.getFloat(10),
tempCat,
rs.getFloat(11));
}
tempStats = new Statistics();
tempStats.setMean(rs.getFloat(5));
tempStats.setMedian(rs.getFloat(6));
tempStats.setMode(rs.getFloat(7));
tempStats.setStandardDev(rs.getFloat(8));
temp.setStAssignmentStats(tempStats);
if (tempCat != null) {
tempCat.addAssignment(temp);
}
temp.setDBID(rs.getLong(1));
retValue.addAssignment(temp);
}
}
//Get categories for the course
sql = "SELECT * FROM STUDENTS " +
"WHERE STUDENTS.ICOURSE = ? " +
"ORDER BY SLASTNAME, SFIRSTMINAME";
stm = con.prepareStatement(sql);
stm.setLong(1, lCourseID);
rs = stm.executeQuery();
if (rs != null) {
while(rs.next()) {
Student temp = new Student(rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5));
temp.setAverageGrade(rs.getFloat(6));
temp.setDBID(rs.getLong(1));
retValue.addStudent(temp);
}
}
//Get Assignments for the course
sql = "SELECT * FROM GRADES " +
"WHERE GRADES.ICOURSE = ? ";
stm = con.prepareStatement(sql);
stm.setLong(1, lCourseID);
rs = stm.executeQuery();
if (rs != null) {
while(rs.next()) {
//Set the grade's student and assignment to the appropriate student and assignment in the course's list
long tempStuID = rs.getLong(8);
long tempAssignID = rs.getLong(7);
Student tempStu = null;
Assignment tempAssign = null;
for (Student stu : retValue.getlStudents()) {
if(stu.getDBID() == tempStuID) {
tempStu = stu;
break;
}
}
for (Assignment assign : retValue.getlAssignments()) {
if(assign.getDBID() == tempAssignID) {
tempAssign = assign;
break;
}
}
Grade temp = new Grade(rs.getFloat(2), tempStu, tempAssign);
temp.setSubmitted(rs.getBoolean(3));
temp.setOverdue(rs.getBoolean(4));
temp.setMissing(rs.getBoolean(5));
temp.setDropped(rs.getBoolean(6));
temp.setDBID(rs.getLong(1));
tempStu.addGrade(temp);
tempAssign.addGrade(temp);
retValue.addGrade(temp);
}
}
Collections.sort(retValue.getlCategories(), Category.nameComparator);
Collections.sort(retValue.getlAssignments(), Assignment.nameComparator);
Collections.sort(retValue.getlStudents(), Student.nameComparator);
Collections.sort(retValue.getlGrades(), Grade.nameComparator);
for (Category cat : retValue.getlCategories()) {
Collections.sort(cat.getAssignments(), Assignment.nameComparator);
}
for (Assignment a : retValue.getlAssignments()) {
Collections.sort(a.getGrades(), Grade.nameComparator);
}
for (Student s : retValue.getlStudents()) {
Collections.sort(s.getGrades(), Grade.nameComparator);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public ArrayList<Term> retrieveModel() {
ArrayList<Term> retValue = new ArrayList<>();
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
ResultSet rsc = null;
try {
//Get the course with the ID passed in
String sql = "SELECT * FROM TERMS ORDER BY IYEAR, ESEASON";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
rs = stm.executeQuery();
if (rs != null) {
while (rs.next()) {
Term temp = new Term(rs.getInt(3), eSeason.values()[rs.getShort(2)]);
temp.setDBID(rs.getLong(1));
sql = "SELECT * FROM COURSES " +
"WHERE COURSES.ITERM = ? " +
"ORDER BY SCOURSENAME";
stm = con.prepareStatement(sql);
stm.setLong(1, temp.getDBID());
rsc = stm.executeQuery();
if (rsc != null) {
while(rsc.next()) {
Course tempCourse = retrieveCourseData(rsc.getLong(1));
temp.addCourse(tempCourse);
}
}
retValue.add(temp);
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (rsc != null) {
try {
rsc.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public ArrayList<Question> retrieveQuestions(long lCourseID) {
ArrayList<Question> retValue = new ArrayList<>();
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
//Get the course with the ID passed in
String sql = "SELECT * FROM QUESTIONS WHERE ICOURSE = ? ORDER BY EQUESTIONTYPE";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
stm.setLong(1, lCourseID);
rs = stm.executeQuery();
if (rs != null) {
while (rs.next()) {
ArrayList<String> lAnswers;
if (rs.getArray(7) != null) {
Array arr = rs.getArray(7);
Object[] sArr = (Object[])arr.getArray();
lAnswers = new ArrayList<>();
for (int i = 0; i < sArr.length; ++i) {
lAnswers.add(sArr[i].toString());
}
} else {
lAnswers = new ArrayList<>();
}
Question temp = new Question(rs.getString(2),
rs.getFloat(8),
lAnswers,
eQuestionType.fromInt(rs.getInt(3)),
eQuestionAssignmentType.fromInt(rs.getInt(5)),
eQuestionLevel.fromInt(rs.getInt(4)),
rs.getFloat(6));
temp.setlDBID(rs.getLong(1));
retValue.add(temp);
}
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public String retrieveEmail() {
String retValue = "";
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "SELECT TOP(1) EMAIL FROM SETTINGS ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
rs = stm.executeQuery();
if (rs != null) {
rs.next();
retValue = rs.getString(1);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public String retrieveEmailPass() {
String retValue = "";
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
String sql = "SELECT TOP(1) EMPASS FROM SETTINGS ";
con = DriverManager.getConnection(conString, user, pass);
stm = con.prepareStatement(sql);
rs = stm.executeQuery();
if (rs != null) {
rs.next();
retValue = rs.getString(1);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) { /* ignored */}
}
if (stm != null) {
try {
stm.close();
} catch (SQLException e) { /* ignored */}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) { /* ignored */}
}
}
return retValue;
}
public void storeNewObjects(ArrayList<Object> lObjects, ArrayList<Term> lTerms) {
for (Term t : lTerms) { //Traverse all terms and store every object in lObjects
//Need to traverse because the parent's DBID is needed
if (lObjects.contains(t)) {
storeTerm(t);
}
for (Course c : t.getCourses()) {
if (lObjects.contains(c)) {
storeCourse(c, t.getDBID());
}
for (Student s : c.getlStudents()) {
if (lObjects.contains(s)) {
storeStudent(s, c.getDBID());
}
}
for (Category cat : c.getlCategories()) {
if (lObjects.contains(cat)) {
storeCategory(cat, c.getDBID());
}
}
for (Assignment a : c.getlAssignments()) {
if (lObjects.contains(a)) {
storeAssignment(a, c.getDBID());
}
}
for (Grade g : c.getlGrades()) {
if (lObjects.contains(g)) {
storeGrade(g, c.getDBID());
}
}
}
}
}
public void updateObjects(ArrayList<Object> lObjects) {
for (Object o : lObjects) {
if (o instanceof Term) {
updateTerm((Term) o);
} else if (o instanceof Course) {
updateCourse((Course) o);
} else if (o instanceof Category) {
updateCategory((Category) o);
} else if (o instanceof Student) {
updateStudent((Student) o);
} else if (o instanceof Assignment) {
updateAssignment((Assignment) o);
} else if (o instanceof Grade) {
updateGrade((Grade) o);
}
}
}
public void deleteObjects(ArrayList<Object> lObjects) {
for (Object o : lObjects) {
if (o instanceof Term) {
deleteTerm((Term) o);
} else if (o instanceof Course) {
deleteCourse((Course) o);
} else if (o instanceof Category) {
deleteCategory((Category) o);
} else if (o instanceof Student) {
deleteStudent((Student) o);
} else if (o instanceof Assignment) {
deleteAssignment((Assignment) o);
} else if (o instanceof Grade) {
deleteGrade((Grade) o);
}
}
}
}
|
package com.newsblur.fragment;
import android.app.LoaderManager;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import com.newsblur.activity.ItemsList;
import com.newsblur.service.NBSyncService;
import com.newsblur.util.FeedSet;
import com.newsblur.util.FeedUtils;
public abstract class ItemSetFragment extends NbFragment implements LoaderManager.LoaderCallbacks<Cursor> {
public static int ITEMLIST_LOADER = 0x01;
protected ItemsList activity;
protected boolean cursorSeenYet = false;
private boolean stopLoading = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = (ItemsList) getActivity();
if (getFeedSet() == null) {
com.newsblur.util.Log.w(this.getClass().getName(), "item list started without FeedSet.");
activity.finish();
return;
}
// warm up the sync service as soon as possible since it will init the story session DB
triggerRefresh(1, null);
}
@Override
public void onStart() {
super.onStart();
stopLoading = false;
getLoaderManager().initLoader(ITEMLIST_LOADER, null, this);
}
@Override
public void onPause() {
// a pause/resume cycle will depopulate and repopulate the list and trigger bad scroll
// readings and cause zero-index refreshes, wasting massive cycles. hold the refresh logic
// until the loaders reset
cursorSeenYet = false;
super.onPause();
}
@Override
public void onResume() {
if (!isAdapterValid()) {
Log.e(this.getClass().getName(), "stale fragment loaded, falling back.");
getActivity().finish();
}
super.onResume();
}
/**
* Sanity check the adapter, iff it exists. If false, the activity will finish.
*/
protected abstract boolean isAdapterValid();
protected void triggerRefresh(int desiredStoryCount, Integer totalSeen) {
// ask the sync service for as many stories as we want
boolean gotSome = NBSyncService.requestMoreForFeed(getFeedSet(), desiredStoryCount, totalSeen);
// if the service thinks it can get more, or if we haven't even seen a cursor yet, start the service
if (gotSome || (totalSeen == null)) triggerSync();
}
/**
* Signal that all futher cursor loads should be ignored
*/
public void stopLoader() {
stopLoading = true;
}
/**
* Indicate that the DB was cleared.
*/
public void resetEmptyState() {
resetAdapter();
cursorSeenYet = false;
FeedUtils.dbHelper.clearStorySession();
}
public abstract void setLoading(boolean isLoading);
private void updateLoadingMessage() {
boolean isMuted = getFeedSet().isMuted();
boolean isLoading = NBSyncService.isFeedSetSyncing(getFeedSet(), activity);
updateLoadingMessage(isMuted, isLoading);
}
protected abstract void updateLoadingMessage(boolean isMuted, boolean isLoading);
public abstract void scrollToTop();
protected FeedSet getFeedSet() {
return activity.getFeedSet();
}
public void hasUpdated() {
if (isAdded() && !getFeedSet().isMuted()) {
getLoaderManager().restartLoader(ITEMLIST_LOADER , null, this);
}
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
FeedSet fs = getFeedSet();
if (fs == null) {
Log.e(this.getClass().getName(), "can't create fragment, no feedset ready");
// this is probably happening in a finalisation cycle or during a crash, pop the activity stack
try {
getActivity().finish();
} catch (Exception e) {
;
}
return null;
} else if (fs.isMuted()) {
updateLoadingMessage();
return null;
} else {
return FeedUtils.dbHelper.getActiveStoriesLoader(getFeedSet());
}
}
@Override
public synchronized void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if (stopLoading) return;
if (cursor != null) {
createAdapter(cursor);
if (! NBSyncService.isFeedSetReady(getFeedSet())) {
// the DB hasn't caught up yet from the last story list; don't display stale stories.
com.newsblur.util.Log.i(this.getClass().getName(), "stale load");
setShowNone(true);
setLoading(true);
triggerRefresh(1, null);
} else {
cursorSeenYet = true;
com.newsblur.util.Log.d(this.getClass().getName(), "loaded cursor with count: " + cursor.getCount());
if (cursor.getCount() < 1) {
triggerRefresh(1, 0);
}
setShowNone(false);
}
updateAdapter(cursor);
}
updateLoadingMessage();
}
/**
* Create and set the adapter iff it is still null.
*/
protected abstract void createAdapter(Cursor cursor);
protected abstract void updateAdapter(Cursor cursor);
protected abstract void resetAdapter();
protected abstract void setShowNone(boolean showNone);
@Override
public void onLoaderReset(Loader<Cursor> loader) {
resetAdapter();
}
public abstract void setTextSize(Float size);
}
|
/*
* 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 pe.gob.onpe.adan.service.Adan;
import java.util.ArrayList;
/**
*
* @author bvaldez
*/
public interface ProceduresService {
String executeAsignacionElector(String dni, String oldLocal, String newLocal, String user);
String executeReAsignacionMesa(String mesa, String oldLocal, String newLocal, String user);
Integer executeGenerateLepa(String user, int process);
Integer executeGenerateManualLepa(String user, int process);
Integer executeLesaToSige(String user);
Integer executeUpdateSige(String user);
Integer executeAssignHistory(String user, int process);
Integer executeAssignHistory2(String user, int process);
Integer executeConformationBdonpe(String user, int process);
String getPercentageLepa();
boolean cleanProcedure();
String validateUbigeos(int type, int status);
}
|
/**
* Created by Nicu Osan on 29.03.2017.
*/
public class Problema5 {
/*5. Se dau doua numere a si n. sa se afiseze numarul a la puterea n */
public static void main(String[] args) {
int a = 3;
int b = 3;
int sum = a;
for (int i = 0; i < b-1; i++) {
sum = sum * a;
}
System.out.println("Nr este: " +sum);
}
}
|
/*
* ---------------------------------------------------------------------------------------------------------------------
* Brigham Young University - Project MEDIA StillFace DataCenter
* ---------------------------------------------------------------------------------------------------------------------
* The contents of this file contribute to the ProjectMEDIA DataCenter for managing and analyzing data obtained from the
* results of StillFace observational experiments.
*
* This code is free, open-source software. You may distribute or modify the code, but Brigham Young University or any
* parties involved in the development and production of this code as downloaded from the remote repository are not
* responsible for any repercussions that come as a result of the modifications.
*/
package com.byu.pmedia.tasks;
import com.byu.pmedia.database.StillFaceDAO;
import com.byu.pmedia.model.StillFaceData;
import com.byu.pmedia.model.StillFaceImport;
import com.byu.pmedia.model.StillFaceModel;
import com.byu.pmedia.model.StillFaceVideoData;
import com.byu.pmedia.parser.StillFaceCSVParser;
import javafx.concurrent.Task;
import java.io.File;
import java.util.logging.Logger;
/**
* StillFaceImportTask
* Implementation of the IStillFaceTask interface. Wraps the execution of importing new still face data from a CSV file
* into the database. This task is executed on a separate thread from the GUI.
*
* @author Braden Hitchcock
*/
public class StillFaceImportTask implements IStillFaceTask {
/* Grab an instance of the logger */
private final static Logger logger =Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
/* The file to import data from (CSV) */
private File importFile;
/* The import data object containing information about he new import entry */
private StillFaceImport importData;
/* The database access object used to modify the database */
private StillFaceDAO dao;
/* Callback functionality provided by the developer */
private StillFaceTaskCallback callback;
public StillFaceImportTask(File importFile, StillFaceImport importData, StillFaceTaskCallback callback){
this.importFile = importFile;
this.importData = importData;
this.dao = StillFaceDAO.generateFromConfig();
this.callback = callback;
}
/**
* Execute the task. Attempts to import new data into the database from a CSV file
*/
@Override
public void execute() {
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
onImportFromFile();
return null;
}
@Override
protected void succeeded() {
callback.onSuccess();
super.succeeded();
}
@Override
protected void failed() {
callback.onFail(this.getException());
super.failed();
}
};
new Thread(task).start();
}
/**
* Where the import happens. Takes the data from a CSV file and populates a list of StillFaceData objects. Then
* it will attempt to first write the import data to the database. After successfully inserting a new import
* entry, it will use the generated key to populate the import id field of the StillFaceData objects and then
* write them to the database. If there is an error encountered during the process, it will rollback the changes
* to the state of the database before the attempt to import occurred.
*
* @throws Exception If an error occurs, this will trigger the failed() method in the thread to be called and the
* developer's provided onFail() implementation to be called
*/
private void onImportFromFile() throws Exception {
logger.fine("Performing import task...");
StillFaceVideoData videoData = new StillFaceVideoData();
new StillFaceCSVParser().parseFromCSVIntoCodedVideoData(importFile.getAbsolutePath(), videoData);
dao.lockConnection();
int key = dao.insertImportData(importData);
if(key > 0){
logger.fine("Import entry created, importing data...");
for(StillFaceData data : videoData.getData()){
data.setImportID(key);
int dKey = dao.insertCodeData(data);
if(dKey < 0){
dao.cleanImportData(key);
throw new Exception("Import data failed while importing file");
}
}
StillFaceModel.getInstance().refreshImportData();
StillFaceModel.getInstance().refreshCodeData();
StillFaceModel.getInstance().refreshCodes();
logger.fine("Import task completed");
}
else{
logger.severe("Unable to insert data into database");
throw new Exception("Import failed while loading file information");
}
dao.unlockConnection();
}
}
|
package developer.skylight.com.retrofitdemo.constant;
/**
* Created by Akash Wangalwar on 17-01-2017.
*/
public class RConstant {
public static final String NAME = "name";
public static final String IMG = "img";
}
|
package pe.egcc.controller;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pe.egcc.eureka.service.RegistroService;
@WebServlet("/RegistroController")
public class RegistroController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Datos
String oficina = request.getParameter("oficina");
String registro = request.getParameter("registro");
String partida = request.getParameter("partida");
String tipoDoc = request.getParameter("tipoDoc");
String numeDoc = request.getParameter("numeDoc");
// Proceso
RegistroService regiService = new RegistroService();
regiService.spNuevaRegistro(oficina, registro, partida, tipoDoc, numeDoc);
request.setAttribute("message", regiService.getMensaje());
// Forward
List<Map<String, ?>> lista = regiService.traerRegistros();
request.setAttribute("lista", lista);
RequestDispatcher rd = request.getRequestDispatcher("registros.jsp");
rd.forward(request, response);
}
}
|
package tasks;
/**
* Todo Task object, contains methods pertaining to the Todo Task.
*/
public class TodoTask extends Task {
/**
* Constructor of a todo task.
*
* @param description Description of the todo task.
*/
public TodoTask(String description) {
super(description);
}
/**
* Returns the Todo task formatted with the task type and whether it is done or not.
*
* @return Todo task in String form.
*/
@Override
public String toString() {
return String.format("%s%s", "[T]", super.toString());
}
}
|
/**
* 1603. Design Parking System
* Easy
* 热身题都算不上吧
*/
class ParkingSystem {
private int big;
private int medium;
private int small;
public ParkingSystem(int big, int medium, int small) {
this.big = big;
this.medium = medium;
this.small = small;
}
public boolean addCar(int carType) {
switch (carType) {
case 1:
return big > 0 && big-- > 0;
case 2:
return medium > 0 && medium-- > 0;
case 3:
return small > 0 && small-- > 0;
default:
return false;
}
}
}
public class Solution {
private static final int BIG = 1;
private static final int MEDIUM = 2;
private static final int SMALL = 3;
public static void main(String[] args) {
// Your ParkingSystem object will be instantiated and called as such:
ParkingSystem ps = new ParkingSystem(1, 1, 0);
System.out.println(ps.addCar(BIG));
System.out.println(ps.addCar(MEDIUM));
System.out.println(ps.addCar(SMALL));
System.out.println(ps.addCar(BIG));
}
} |
package com.seemoreinteractive.virtualshot.helper;
import android.os.AsyncTask;
import android.widget.Toast;
import com.gmail.yuyang226.flickr.Flickr;
import com.gmail.yuyang226.flickr.oauth.OAuth;
import com.gmail.yuyang226.flickr.oauth.OAuthInterface;
import com.seemoreinteractive.virtualshot.FlickrActivity;
public class GetFlickrToken extends AsyncTask<String, Integer, OAuth>{
private FlickrActivity activity;
public GetFlickrToken(FlickrActivity context) {
this.activity = context;
}
@Override
protected OAuth doInBackground(String... params) {
String oauthToken = params[0];
String oauthTokenSecret = params[1];
String verifier = params[2];
Flickr f = FlickrHelper.getInstance().getFlickr();
OAuthInterface oauthApi = f.getOAuthInterface();
try {
return oauthApi.getAccessToken(oauthToken, oauthTokenSecret,verifier);
} catch (Exception e) {
Toast.makeText(activity, "Error:GetFlickrToken doInBackground - during OAUth retrieve request token", Toast.LENGTH_LONG).show();
return null;
}
}
@Override
protected void onPostExecute(OAuth result) {
if (activity != null) {
activity.onOAuthDone(result);
}
}
}
|
package com.supconit.kqfx.web.fxzf.search.entities;
import hc.base.domains.PK;
import java.util.List;
/**
* 业户信息
*/
public class YhInfo implements PK<String> {
private static final long serialVersionUID = 1L;
private String id;
/** 经营类型 */
private String operationType;
/** 业户名称 */
private String yhName;
/** 业户地址 */
private String yhAddress;
/** 经济类型 */
private String economicType;
/** 受理编号 */
private String acceptNo;
/** 邮政编号 */
private String postalNo;
/** 经营范围 */
private String operationArea;
/** 行政区化代码 */
private String regionCode;
/** 行政区化名称 */
private String regionName;
/** 法人代表 */
private String legalPersion;
/** 法人代表电话 */
private String legalTelephone;
/** 法人代表手机 */
private String legalCellphone;
/** 法人证件号 */
private String legalCertificate;
/** 负责人 */
private String principalPersion;
/** 经办人 */
private String agentPersion;
/** 电话号码 */
private String telephoneNo;
/** 传真号码 */
private String faxNo;
/** 手机号码 */
private String cellphoneNo;
/** 电子邮箱 */
private String email;
/** 经营许可证号 */
private String certificateNo;
/** 有效期起 */
@com.alibaba.fastjson.annotation.JSONField(format = "yyyy-MM-dd")
private java.util.Date indateBegin;
/** 有效期止 */
@com.alibaba.fastjson.annotation.JSONField(format = "yyyy-MM-dd")
private java.util.Date indateEnd;
/** 工商执照 */
private String businessLicenseNo;
/** 工商管理部门 */
private String commerceDepartment;
/** 工商执照发证日期 */
@com.alibaba.fastjson.annotation.JSONField(format = "yyyy-MM-dd")
private java.util.Date businessLicenseDate;
/** 注册资金 */
private Long registeredFund;
/** 户籍地运管机构 */
private String domicilePipe;
/** 是否营运 */
private String operationState;
/** 经度 */
private Double longitude;
/** 纬度 */
private Double latidute;
/** YH_CL_SL */
private Long yhClSl;
/** YH_RY_SL */
private Long yhRySl;
/** YHLX_OTHER_FLAG */
private Integer yhlxOtherFlag;
/** 车辆信息列表 */
private List<VehicleInfo> vehicleList;
/** 非现执法实体类 */
private Fxzf fxzf;
/** 违法次数 */
private Integer illegalTimes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getOperationType() {
return operationType;
}
public void setOperationType(String operationType) {
this.operationType = operationType;
}
public String getYhName() {
return yhName;
}
public void setYhName(String yhName) {
this.yhName = yhName;
}
public String getYhAddress() {
return yhAddress;
}
public void setYhAddress(String yhAddress) {
this.yhAddress = yhAddress;
}
public String getEconomicType() {
return economicType;
}
public void setEconomicType(String economicType) {
this.economicType = economicType;
}
public String getAcceptNo() {
return acceptNo;
}
public void setAcceptNo(String acceptNo) {
this.acceptNo = acceptNo;
}
public String getPostalNo() {
return postalNo;
}
public void setPostalNo(String postalNo) {
this.postalNo = postalNo;
}
public String getOperationArea() {
return operationArea;
}
public void setOperationArea(String operationArea) {
this.operationArea = operationArea;
}
public String getRegionCode() {
return regionCode;
}
public void setRegionCode(String regionCode) {
this.regionCode = regionCode;
}
public String getRegionName() {
return regionName;
}
public void setRegionName(String regionName) {
this.regionName = regionName;
}
public String getLegalPersion() {
return legalPersion;
}
public void setLegalPersion(String legalPersion) {
this.legalPersion = legalPersion;
}
public String getLegalTelephone() {
return legalTelephone;
}
public void setLegalTelephone(String legalTelephone) {
this.legalTelephone = legalTelephone;
}
public String getLegalCellphone() {
return legalCellphone;
}
public void setLegalCellphone(String legalCellphone) {
this.legalCellphone = legalCellphone;
}
public String getLegalCertificate() {
return legalCertificate;
}
public void setLegalCertificate(String legalCertificate) {
this.legalCertificate = legalCertificate;
}
public String getPrincipalPersion() {
return principalPersion;
}
public void setPrincipalPersion(String principalPersion) {
this.principalPersion = principalPersion;
}
public String getAgentPersion() {
return agentPersion;
}
public void setAgentPersion(String agentPersion) {
this.agentPersion = agentPersion;
}
public String getTelephoneNo() {
return telephoneNo;
}
public void setTelephoneNo(String telephoneNo) {
this.telephoneNo = telephoneNo;
}
public String getFaxNo() {
return faxNo;
}
public void setFaxNo(String faxNo) {
this.faxNo = faxNo;
}
public String getCellphoneNo() {
return cellphoneNo;
}
public void setCellphoneNo(String cellphoneNo) {
this.cellphoneNo = cellphoneNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCertificateNo() {
return certificateNo;
}
public void setCertificateNo(String certificateNo) {
this.certificateNo = certificateNo;
}
public java.util.Date getIndateBegin() {
return indateBegin;
}
public void setIndateBegin(java.util.Date indateBegin) {
this.indateBegin = indateBegin;
}
public java.util.Date getIndateEnd() {
return indateEnd;
}
public void setIndateEnd(java.util.Date indateEnd) {
this.indateEnd = indateEnd;
}
public String getBusinessLicenseNo() {
return businessLicenseNo;
}
public void setBusinessLicenseNo(String businessLicenseNo) {
this.businessLicenseNo = businessLicenseNo;
}
public String getCommerceDepartment() {
return commerceDepartment;
}
public void setCommerceDepartment(String commerceDepartment) {
this.commerceDepartment = commerceDepartment;
}
public java.util.Date getBusinessLicenseDate() {
return businessLicenseDate;
}
public void setBusinessLicenseDate(java.util.Date businessLicenseDate) {
this.businessLicenseDate = businessLicenseDate;
}
public Long getRegisteredFund() {
return registeredFund;
}
public void setRegisteredFund(Long registeredFund) {
this.registeredFund = registeredFund;
}
public String getDomicilePipe() {
return domicilePipe;
}
public void setDomicilePipe(String domicilePipe) {
this.domicilePipe = domicilePipe;
}
public String getOperationState() {
return operationState;
}
public void setOperationState(String operationState) {
this.operationState = operationState;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public Double getLatidute() {
return latidute;
}
public void setLatidute(Double latidute) {
this.latidute = latidute;
}
public Long getYhClSl() {
return yhClSl;
}
public void setYhClSl(Long yhClSl) {
this.yhClSl = yhClSl;
}
public Long getYhRySl() {
return yhRySl;
}
public void setYhRySl(Long yhRySl) {
this.yhRySl = yhRySl;
}
public Integer getYhlxOtherFlag() {
return yhlxOtherFlag;
}
public void setYhlxOtherFlag(Integer yhlxOtherFlag) {
this.yhlxOtherFlag = yhlxOtherFlag;
}
public List<VehicleInfo> getVehicleList() {
return vehicleList;
}
public void setVehicleList(List<VehicleInfo> vehicleList) {
this.vehicleList = vehicleList;
}
public Fxzf getFxzf() {
return fxzf;
}
public void setFxzf(Fxzf fxzf) {
this.fxzf = fxzf;
}
public Integer getIllegalTimes() {
return illegalTimes;
}
public void setIllegalTimes(Integer illegalTimes) {
this.illegalTimes = illegalTimes;
}
}
|
package com.shopping.etrade.model;
import java.util.List;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.shopping.etrade.dto.CardDTO;
import com.shopping.etrade.model.base.IdVersion;
import com.shopping.etrade.model.base.Money;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Entity
@Table(name = "card")
public class Card extends IdVersion {
@AttributeOverrides({ @AttributeOverride(name = "amount", column = @Column(name = "shipping_amount")),
@AttributeOverride(name = "currency", column = @Column(name = "shipping_amount_currency")) })
private Money shippingAmount;
@AttributeOverrides({ @AttributeOverride(name = "amount", column = @Column(name = "campapign_discound_amount")),
@AttributeOverride(name = "currency", column = @Column(name = "campaign_discound_amount_currency")) })
private Money campaignDiscount;
@AttributeOverrides({ @AttributeOverride(name = "amount", column = @Column(name = "coupon_discound_amount")),
@AttributeOverride(name = "currency", column = @Column(name = "coupon_discound_amount_currency")) })
private Money couponDiscount;
@AttributeOverrides({ @AttributeOverride(name = "amount", column = @Column(name = "basket_amount")),
@AttributeOverride(name = "currency", column = @Column(name = "basket_amount_currency")) })
private Money basketAmount;
@OneToMany(mappedBy="card", fetch = FetchType.EAGER)
private List<CardProduct> cardProductList;
public static CardDTO toDTO(Card card) {
CardDTO cardDTO = new CardDTO();
cardDTO.setCampaignDiscount(Money.toMoneyDTO(card.getCampaignDiscount()));
cardDTO.setCouponDiscount(Money.toMoneyDTO(card.getCouponDiscount()));
cardDTO.setId(card.getId());
cardDTO.setBasketAmount((Money.toMoneyDTO(card.getBasketAmount())));
cardDTO.setShippingAmount(Money.toMoneyDTO(card.getShippingAmount()));
return cardDTO;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.