text
stringlengths
10
2.72M
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.game; /** * Noark的一些常用配置类. * * @author 小流氓[176543888@qq.com] * @since 3.0 */ public class NoarkConstant { /** * 激活Noark的Profile的Key. */ public static final String NOARK_PROFILES_ACTIVE = "noark.profiles.active"; /** * Noark版本的配置,系统自动生成,不可配置. */ public static final String NOARK_VERSION = "noark.version"; /** * 加密公钥,用于配置文件时自定义RSA */ public static final String CRYPTO_RSA_PUBLICKEY = "crypto.rsa.publickey"; /** * 游戏BI数据上报功能是否开启:默认=true */ public static final String BI_REPORT_ACTIVE = "game.bi.report.active"; /** * Nacos服务是否开启,默认为关闭状态 */ public static final String NACOS_ENABLED = "noark.nacos.enabled"; /** * Nacos的服务地址 */ public static final String NACOS_SERVER_ADDR = "noark.nacos.server-addr"; /** * Nacos的账号 */ public static final String NACOS_USERNAME = "noark.nacos.username"; /** * Nacos的密码 */ public static final String NACOS_PASSWORD = "noark.nacos.password"; /** * Nacos的命名空间 */ public static final String NACOS_NAMESPACES = "noark.nacos.namespaces"; /** * Noark配置中心服务是否开启,默认为关闭状态 */ public static final String CONFIG_CENTRE_ENABLED = "noark.config.centre.enabled"; /** * Noark配置中心服务地址 */ public static final String CONFIG_CENTRE_CLASS = "noark.config.centre.class"; /** * 当前游戏进程PID文件位置。 * <p> * pid.file=/data/server01/game.pid */ public static final String PID_FILE = "pid.file"; /** * 配置区服ID的Key */ public static final String SERVER_ID = "server.id"; /** * 配置区服名称的Key */ public static final String SERVER_NAME = "server.name"; /** * 配置区服是否可以调试的Key */ public static final String SERVER_DEBUG = "server.debug"; /** * 配置区服所需策划模板文件的路径 */ public static final String TEMPLATE_PATH = "template.path"; /** * 停服信号启用,开启一个等待输入停服信息 * <p> * 默认情况:Window系统默开启,Linux默认关闭<br> * 如果配置了当前值,则强制使用配置值 */ public static final String SHUTDOWN_SIGNAL_ENABLED = "shutdown.signal.enabled"; /** * Banner默认图案为Noark的Logo */ public static final String BANNER_DEFAULT = "noark.banner"; }
package com.checklist.changetask; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.checklist.R; import com.checklist.model.Task; public class ChangeTaskFragment extends Fragment implements ChangeTaskContract.View{ public static final String CHANGE_TAG = "Change_Tag"; private ChangeTaskContract.Presenter presenter; private EditText editText; private String id; private Task task; public static ChangeTaskFragment getInstance(String id){ ChangeTaskFragment changeTaskFragment = new ChangeTaskFragment(); Bundle bundle = new Bundle(); bundle.putString(CHANGE_TAG, id); changeTaskFragment.setArguments(bundle); return changeTaskFragment; } @Override public void setPresenter(ChangeTaskContract.Presenter presenter) { this.presenter = presenter; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); setRetainInstance(true); if (getArguments() != null) id = getArguments().getString(CHANGE_TAG); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.add_task, null); if (getActivity() != null) { getActivity().setTitle(getResources().getString(R.string.change_title)); ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); } editText = (EditText) view.findViewById(R.id.editText); presenter.initRealm(); presenter.getTask(id); return view; } @Override public void setData(Task element) { task = element; editText.setText(task.getDescription()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_change, menu); menu.findItem(R.id.action_add).setVisible(false); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_change){ String textInEditText = editText.getText().toString().trim(); if (textInEditText.isEmpty() && getView() != null){ Snackbar.make(getView(), getResources().getString(R.string.not_be_empty), Snackbar.LENGTH_LONG).show(); } else if(textInEditText.equals(task.getDescription()) && getView() != null){ Snackbar.make(getView(), getResources().getString(R.string.change_task), Snackbar.LENGTH_LONG).show(); } else { Task element = new Task(task.getId(), textInEditText, task.getDate()); presenter.changeData(element); close(); } } return super.onOptionsItemSelected(item); } private void close(){ if (getActivity() != null){ ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false); getActivity().getSupportFragmentManager().popBackStackImmediate(); } } @Override public void onDestroyView() { super.onDestroyView(); presenter.closeRealm(); } }
package com.perfect.web.service; import com.perfect.entity.Permission; import com.baomidou.mybatisplus.service.IService; /** * <p> * 权限表 服务类 * </p> * * @author Ben. * @since 2017-03-15 */ public interface PermissionService extends IService<Permission> { }
package com.outlook.base; import java.lang.reflect.Method; import java.util.Iterator; import java.util.List; import java.util.Map; import org.dom4j.Element; import org.testng.annotations.DataProvider; import com.outlook.constant.Path; public class DataDriveBase { private void initial() { if(px == null) { px = new ParseXml(Path.TESTDATA + this.getClass().getName() + ".xml"); } } private void getCommonMap() { if(commonMap == null) { Element element = px.getElementObject("/*/common"); commonMap = px.getChildNodesByElement(element); } } @DataProvider public Object[][] providerMethod(Method method) { this.initial(); this.getCommonMap(); String methodName = method.getName(); List<Element> elements = px.getElementObjects("/*/" + methodName); Object[][] object = new Object[elements.size()][]; for(int i = 0; i < elements.size(); i ++) { Map<String, String> mergeCommonMap = this.getMergeMapData(px.getChildNodesByElement(elements.get(i)), commonMap); Map<String, String> mergeGlobalMap = this.getMergeMapData(mergeCommonMap, GlobalInfo.global); Object[] temp = new Object[] {mergeGlobalMap}; object[i] = temp; } return object; } private Map<String, String> getMergeMapData(Map<String, String> map1, Map<String, String> map2) { Iterator<String> it = map2.keySet().iterator(); while(it.hasNext()) { String key = it.next(); String value = map2.get(key); if(!map1.containsKey(key)) { map1.put(key, value); } } return map1; } private ParseXml px; private Map<String, String> commonMap; }
/** * Created with IntelliJ IDEA. * User: dexctor * Date: 12-12-29 * Time: 上午9:00 * To change this template use File | Settings | File Templates. */ public class Edge implements Comparable<Edge> { private int v; private int w; private double weight; public Edge(int v, int w, double weight) { this.v = v; this.w = w; this.weight = weight; } public int either() { return v; } public int other(int p) { if(this.v == p) return w; else if(this.w == p) return this.v; else throw new RuntimeException(); } public double weight() { return weight; } public int compareTo(Edge that) { if(weight < that.weight) return -1; if(weight > that.weight) return 1; return 0; } public String toString() { return String.format("%d-%d:%.2f", v, w, weight); } }
package com.atguigu.lgl; import java.util.Arrays; /* * 4. 对象数组题目: 定义类Student,包含三个属性:学号number(int),年级state(int),成绩score(int)。 创建20个学生对象,学号为1到20,年级和成绩都由随机数确定。 问题一:打印出3年级(state值为3)的学生信息。 问题二:使用冒泡排序按学生成绩排序,并遍历所有学生信息 int 提示: 1) 生成随机数:Math.random(),返回值类型double; 2) 四舍五入取整:Math.round(double d),返回值类型long。 */ public class StudentTest_Luo { public static void main(String[] args) { //创建学生信息 int[] info = new int[20]; for (int i = 0; i < 20; i++) { Student2 st = new Student2(); st.number = i+1; st.state = (int)(Math.random()*6+1); st.score = (int)(Math.round(Math.random()*100)); info[i] = st.score; if (st.state == 3) { System.out.print("学号: " + st.number + " "); System.out.print("班级: " + st.state + " "); System.out.print("分数: " + st.score + " "); System.out.println(); } } System.out.println(); //遍历原始成绩 System.out.println("原始的成绩: "); for (int i = 0; i < info.length; i++) { System.out.print(info[i] + " "); } System.out.println(); System.out.println("------------------"); //使用冒泡排序,遍历排序后的成绩 for (int i = 0; i < info.length -1; i++) { for (int j = 0; j < info.length- i -1; j++) { if (info[j] > info[j+1]) { int tmp = info[j]; info[j] = info[j+1]; info[j+1] = tmp; } } } System.out.println("排序后的成绩: "); for (int i = 0; i < info.length; i++) { System.out.print(info[i] + " "); } System.out.println(); //使用arrays工具类排序后遍历成绩 /*System.out.println("------------------"); for (int i = 0; i < info.length; i++) { System.out.print(info[i] + " "); } System.out.println();*/ } } class Student2{ public int number; public int state; public int score; }
package circle; import java.util.*; //import java.lang.*; public class Circle { public static void main(String[] args) { Scanner obj = new Scanner(System.in); System.out.println("Give Radius Value:"); int a = obj.nextInt(); With ob = new With(a); ob.Area(); // ob.finalize(); With obb = new With(); obb.Area(); } }
package com.document.feed.util; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class IndexUtils { public static final String TEMPLATE_NAME = "article-template"; public static final String INDEX_NAME = "article"; public static final String TEMPLATE_PATTERN = INDEX_NAME + "-*"; public static String timeToText(LocalDateTime time) { return time.truncatedTo(ChronoUnit.MILLIS).toString().replace(':', '-').replace('T', '.'); } public static LocalDateTime textToTime(String text) { return LocalDateTime.parse(text.replace('-', ':').replace('.', 'T')); } }
package com.javiermarsicano.algorithms.codility; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.assertEquals; /** Your monthly phone bill has just arrived, and is unexpectedly large. You decide to venrify the amount by recalculating the bill based on your phone cell logs and the phone company's charges. The logs are given as a string S consisting of N lines separated by end-of-line characters (ASCII code 10). Each line describes one phone call using the following format: " hh:mm:ss,nnn-nnn-nnn", where "hh:mm:ss" denotes the duration of the call and "nnn-nnn-nnn" denotes the 9-digit phone number of the recipient (with no leading zeros). Each call is billed separately. The billing rules are as follows: • If the call was shorter than 5 minutes, then you pay 3 cents for every started second of the cell (e.g. for duration "00:01:07" you pay 67*3 = 201 cents). • If the call was at least 5 minutes long, then you pay 150 cents for every started minute of the call (e.g. for duration "00:05:00' you pay 5*150 = 750 cents and for duration "00:05:01" you pay 6*150 = 900 cents). • All cells to the phone number that has the longest total duration of cells are free. In the case of a tie, if more than one phone number shares the longest total duration, the promotion is applied only to the phone number whose numerical value is the smallest among these phone numbers. Write a function: class Solution { public int solution(String S); } that given a string S describing phone call logs, returns the amount of money you have to pay in cents. For example, given string S with N = 3 lines: "00:01:07,400-234-090 00:05:01,701-080-080 00:05:00,400-234-090" the function should return 900 (the total duration for number 400-234-090 is 6 minutes 7 seconds, and the total duration for number 701-080-080 is 5 minutes 1 second; therefore, the free promotion applies to the former phone number). Assume that: • N is an integer within the range [1..100]; • every phone number follows the format "nnn-nnn-nnn" strictly, there are no leading zeros; • the duration of every call follows the format "hh:mm:ss strictly (00 <= hh <= 99, 00 <= mm, ss <= 99); • each line follows the format " hh:mm:ss,nnn-nnn-nnn" strictly, there are no empty lines and spaces. In your solution, focus on correctness. The performance of your solution will not be the focus. */ public class PhoneCallsBilling { @Test public void test_basic_case() { String logs = "00:01:07,400-234-090\n00:05:01,701-080-080\n00:05:00,400-234-090"; assertEquals(900, Solution.find(logs)); } @Test public void test_complex_case() { String logs = "00:00:01,400-234-090\n00:05:00,400-234-098"; assertEquals(3, Solution.find(logs)); } @Test public void test_complex_case2() { String logs = "00:00:00,400-234-090\n00:00:00,400-234-098"; assertEquals(0, Solution.find(logs)); } public static class Solution { static int find(String S) { String[] logs = S.split("\n"); ArrayList<CallLog> callLogs = new ArrayList<>(); for (String l :logs){ callLogs.add(new CallLog(l)); } callLogs.sort((callLog, t1) -> callLog.phoneNumber - t1.phoneNumber); callLogs.forEach(callLog -> callLog.billing = Rule.apply(callLog)); for (int i = 0; i< callLogs.size() -1 ;i++) { if (callLogs.get(i).phoneNumber == callLogs.get(i+1).phoneNumber) { callLogs.get(i).billing += callLogs.get(i+1).billing; callLogs.remove(i+1); } } callLogs.sort((callLog, t1) -> callLog.billing - t1.billing); //FALTO callLogs.remove(callLogs.size() - 1); //ESTABA ANTES DEL BUCLE int out = 0; for (CallLog callLog : callLogs) { out += callLog.billing; } return out; } static class CallLog { int hours; int minutes; int seconds; int phoneNumber; int billing; CallLog(String log) { String[] entry = log.split(","); String[] time = entry[0].split(":"); hours = Integer.parseInt(time[0]); minutes = Integer.parseInt(time[1]); seconds = Integer.parseInt(time[2]); phoneNumber = Integer.parseInt(entry[1].replace("-","")); } @Override public String toString() { return " "+hours+" "+minutes+" "+seconds+" "+phoneNumber+" "+billing; } } static class Rule { static final int MINUTES_IN_HOUR = 60; //returns the billing amount in cents static int apply(CallLog log) { if (log.minutes >= 5) { int startedMinute = log.seconds > 0 ? 1 : 0; return (log.hours * MINUTES_IN_HOUR + log.minutes + startedMinute) * 150; } else { return (log.minutes * MINUTES_IN_HOUR + log.seconds) * 3; } } } } }
package com.yasin.round.card; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.FrameLayout; import com.yasin.round.R; /** * Created by leo on 17/3/31. */ public class RoundView extends FrameLayout { /** * 阴影的起始颜色 */ private int mShadowStartColor; /** * 阴影的结束颜色 */ private int mShadowEndColor; /** * 圆角半径 */ private float mRadius; /** * 阴影的起始颜色 */ private float mElevation; /** * 控件背景颜色 */ private ColorStateList mBackgroundColor; private static IRoundView roundViewImp; static { if (Build.VERSION.SDK_INT >= 17) { roundViewImp = new RoundViewJellyBeanMr(); } else { roundViewImp = new RoundViewLowImp(); } roundViewImp.initStatic(); } public RoundView(Context context) { super(context); initialize(context, null, 0); } public RoundView(Context context, AttributeSet attrs) { super(context, attrs); initialize(context, attrs, 0); } public RoundView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initialize(context, attrs, defStyleAttr); } private void initialize(Context context, AttributeSet attrs, int defStyleAttr) { TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundView, defStyleAttr, 0); //判断是否有背景颜色 if (a.hasValue(R.styleable.RoundView_backgroundColor)) { mBackgroundColor = a.getColorStateList(R.styleable.RoundView_backgroundColor); } else { //获取系统的背景颜色 TypedArray aa = context.obtainStyledAttributes(new int[]{android.R.attr.colorBackground}); //获取系统的背景颜色 int themeBackgroundColor = aa.getColor(0, 0); //获取背景颜色的hvs值(h色彩、s饱和度、v颜色值) float[] hsv = new float[3]; Color.colorToHSV(themeBackgroundColor, hsv); //当饱和度>0.5的时候,我们获取自定义的cardview_dark_background颜色 if (hsv[2] > 0.5) { mBackgroundColor = ColorStateList.valueOf(getResources().getColor(R.color.cardview_dark_background)); } else { mBackgroundColor = ColorStateList.valueOf(getResources().getColor(R.color.cardview_dark_background)); } aa.recycle(); } mRadius = a.getDimensionPixelSize(R.styleable.RoundView_conerRadius, 0); mElevation = a.getDimensionPixelSize(R.styleable.RoundView_shadowSize, 0); mShadowStartColor = a.getColor(R.styleable.RoundView_shadowStartColor, getResources().getColor(R.color.cardview_shadow_start_color)); mShadowEndColor = a.getColor(R.styleable.RoundView_shadowEndColor, getResources().getColor(R.color.cardview_shadow_end_color)); a.recycle(); roundViewImp.initialize(mRoundViewDelegate); } public int getShadowStartColor() { return mShadowStartColor; } public void setShadowStartColor(int shadowStartColor) { this.mShadowStartColor = shadowStartColor; } public int getShadowEndColor() { return mShadowEndColor; } public void setShadowEndColor(int shadowEndColor) { this.mShadowEndColor = shadowEndColor; } public float getRadius() { return mRadius; } public void setRadius(float mRadius) { this.mRadius = mRadius; } public float getElevation() { return mElevation; } public void setElevation(float mElevation) { this.mElevation = mElevation; } public ColorStateList getBackgroundColor() { return mBackgroundColor; } public void setBackgroundColor(ColorStateList backgroundColor) { this.mBackgroundColor = backgroundColor; } private IRoundViewDelegate mRoundViewDelegate = new IRoundViewDelegate() { private Drawable bgDrawable; @Override public void setCardBackground(Drawable drawable) { this.bgDrawable = drawable; setBackgroundDrawable(drawable); } @Override public Drawable getCardBackground() { return bgDrawable; } @Override public View getCardView() { return RoundView.this; } @Override public int getShadowStartColor() { return RoundView.this.getShadowStartColor(); } @Override public int getShadowEndColor() { return RoundView.this.getShadowEndColor(); } @Override public ColorStateList getBackgroundColor() { return RoundView.this.getBackgroundColor(); } @Override public float getRadius() { return RoundView.this.getRadius(); } @Override public float getElevation() { return RoundView.this.getElevation(); } }; }
package command; import command.robot.*; /** * Инкапсулирует запрос в виде объекта, делая возможной параметризацию клиентских объектов с другими запросами, * организацию очереди, регистрации запросов, а так же поддержку отмены операции. Шаблок используется в многопоточности, * (Runnable) и при транзакциях (сложных операциях, при которыех выполняется последовательность определенных действий, * при невозможности выполнения любого из этапов транзакции, все операции выполненные до проблемной отменяются). * *Реализация: * 1.Вынести общий интерфейс комманд и определить в нем методы запуска и отмены комманды. * 2.Создать конкретные классы команд. В каждой комманде должно быть поле, которое хранит ссылку на 1 или несколько * получателей комманды. Так же можно создать поля, которые будут определять параметры комманды. Все эти параметры * команда должна получать из конструктора. * 3.Реализовать методы интерфейса комманды. * @author Vladimir Ryazanov (v.ryazanov13@gmail.com) */ public class Example { public static void main(String[] args) { Robot robot = new Robot(); //Создаем объект команды, передем в конструкторе сущность, которая будет выполнять команду Command forward = new ForwardCommand(robot); System.out.println("Двигем робота вперед через команду"); //Выполняем команду forward.execute(); System.out.println("Отменяем комманду"); //Отмена команды forward.undo(); //Создадим макро-команду, состоящую из нескольких MacroCommand macroCommand = new MacroCommand(); //Добавим в макро-команду несколько комманд, которые будут выполняться по порялку macroCommand.addCommand(new ForwardCommand(robot)); macroCommand.addCommand(new ForwardCommand(robot)); macroCommand.addCommand(new BackCommand(robot)); //Т.к. макрокоманда реализует интерфейс комманды, мы можем обращаться к ней как не-составной //Command command = macroCommand; System.out.println("Выполняем составную комманду"); //Выполняет все комманды, добавленные в очередь macroCommand.execute(); System.out.println("Отменяем составную комманду"); //Отменяет все выполненные команды macroCommand.undo(); } }
package com.zs.bus; import com.huaiye.sdk.sdkabi._params.SdkBaseParams; /** * author: admin * date: 2018/05/29 * version: 0 * mail: secret * desc: ChannelInvistor */ public class NetStatusChange { public SdkBaseParams.ConnectionStatus data; /** * 是否已经尝试过重新登陆 */ public boolean haveTryLogin; public NetStatusChange(SdkBaseParams.ConnectionStatus data) { this.data = data; this.haveTryLogin = false; } public NetStatusChange(SdkBaseParams.ConnectionStatus data, boolean haveTryLogin) { this.data = data; this.haveTryLogin = haveTryLogin; } // public NetStatusChange(SdkBaseParams.ConnectionStatus data, CQueryUserListRsp.UserInfo usrInfo) { // this.data = data; // this.usrInfo = usrInfo; // } }
package com.revature.daoimplementations; import com.revature.project1.dao.UserDao; import com.revature.project1.models.User; import com.revature.project1.jdbc.*; import java.sql.*; import java.util.*; public class UserDaoImpl implements UserDao { static PreparedStatement pstmt = null; static Statement stmt = null; static ResultSet rs = null; static String query = " "; public User myUser = new User(); public User login(String username, String password) { // System.out.println(userName + " "+ password); User user = new User(); user = null; try { DatabaseConnection conn = DatabaseConnection.getInstance(); Connection connection = conn.getConnection(); query = "select * from users where username =? and password=?"; pstmt = connection.prepareStatement(query); pstmt.setString(1, username); pstmt.setString(2, password); rs = pstmt.executeQuery(); if (rs.next()) { myUser.setUserId(rs.getInt("user_id")); myUser.setFirstName(rs.getString("first_name")); myUser.setLastName(rs.getString("last_name")); myUser.setUsername(rs.getString("username")); myUser.setEmail(rs.getString("email")); myUser.setRoleId(rs.getInt("role_id")); user = myUser; } else { System.err.println("User does not exist"); user = null; } } catch (SQLException e) { Dashboard.logger.trace("SQL Exception caught UserDaoImpl.java: 85"); } return user; } public User logout(User user) { user = myUser; myUser = null; return myUser; } public User viewUser(int id) { try { User user = new User(); DatabaseConnection conn = DatabaseConnection.getInstance(); Connection connection = conn.getConnection(); query = "select * from users where user_id =?"; pstmt = connection.prepareStatement(query); pstmt.setInt(1, id); rs = pstmt.executeQuery(); while (rs.next()) { System.out.println(rs.getString("first_name")); user.setUserId(rs.getInt("user_id")); user.setFirstName(rs.getString("first_name")); user.setLastName(rs.getString("last_name")); user.setEmail(rs.getString("email")); user.setUsername(rs.getString("username")); //user.setRoleId(rs.getInt("role_id")); } return user; } catch (SQLException e) { Dashboard.logger.trace("SQL Exception caught UserDaoImpl.java: 111"); return null; } } }
package com.wy.action.algorithm; import org.junit.Assert; import org.junit.Test; import java.lang.reflect.Array; import java.util.*; /** * @Author wangyong * @Date 2020-02-18 */ public class StringApp { /** * 判断是否为回文数 * @param x * @return */ public boolean isPalindrome(int x) { String one = x+""; StringBuilder two = new StringBuilder(one).reverse(); System.out.println(two.toString()); return one.equals(two.toString()); } @Test public void isPalindromeTest() { Assert.assertEquals(true, isPalindrome(121)); Assert.assertEquals(false, isPalindrome(-121)); Assert.assertEquals(false, isPalindrome(212221)); } /** * int转罗马数字,4是IV(5-1) 9是IX(10-1) * I 1 * V 5 * X 10 * L 50 * C 100 * D 500 * M 1000 * Input: 1994 * Output: "MCMXCIV" */ public String intToRoman(int num) { String result = ""; int m = num/1000; while (m-->0){ result+="M"; } m = (num %1000)/100; result = add(result,m,"D", "M", "C"); m = (num%100)/10; result = add(result,m,"L", "C", "X"); m = num%10; result = add(result,m,"V", "X", "I"); return result; } private String add(String result, int m,String five, String ten, String one) { if(m>0) { if(m==5) { result+= five; } else if(m<5){ if (m == 4) { result += one + five; }else { while (m-->0) { result += one; } } } else { if (m == 9) { result += one + ten; } else { result += five; m -= 5; while (m-->0) { result += one; } } } } return result; } @Test public void intToRomanTest() { Assert.assertEquals("MCMXCIV",intToRoman(1994)); Assert.assertEquals("III",intToRoman(3)); Assert.assertEquals("IV",intToRoman(4)); Assert.assertEquals("IX",intToRoman(9)); Assert.assertEquals("LVIII",intToRoman(58)); } /** * 判断是否为数独 * @param board * @return */ public boolean isValidSudoku(char[][] board) { Map<Integer, Set<Character>> rows = new HashMap<>(); Map<Integer, Set<Character>> cols = new HashMap<>(); Map<String, Set<Character>> subBoxes = new HashMap<>(); for (int row = 0; row < board.length; row++) { for (int col = 0; col < board[0].length; col++) { if (board[row][col] != '.') { Character c = board[row][col]; if (rows.get(row) != null && rows.get(row).contains(c)) return false; rows.putIfAbsent(row, new HashSet<>()); rows.get(row).add(c); if (cols.get(col) != null && cols.get(col).contains(c)) return false; cols.putIfAbsent(col, new HashSet<>()); cols.get(col).add(c); String keySubBox = String.valueOf(row / 3) + String.valueOf(col / 3); if (subBoxes.get(keySubBox) != null && subBoxes.get(keySubBox).contains(c)) return false; subBoxes.putIfAbsent(keySubBox, new HashSet<>()); subBoxes.get(keySubBox).add(c); } } } return true; } @Test public void isValidSudokuTest() { char[][] one = { {'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'} }; char[][] two = { {'8','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'} }; Assert.assertEquals(true, isValidSudoku(one)); Assert.assertEquals(false, isValidSudoku(two)); } /** * 对包含相同字符的字符串分组 * @param strs * @return */ public List<List<String>> groupAnagrams(String[] strs) { Map<String, List<String>> map = new HashMap<>(); for(int i=0;i<strs.length;i++) { int[] arr = new int[26]; for( int j=0;j<strs[i].length(); j++) { arr[strs[i].charAt(j)-'a'] ++; } String key = Arrays.toString(arr); List<String> one = map.get(key); if (one == null) { one = new ArrayList<>(); } one.add(strs[i]); map.put(key, one); } return new ArrayList<>(map.values()); } @Test public void test() { String[] arr = {"eat", "tea", "tan", "ate", "nat", "bat"}; System.out.println(groupAnagrams(arr)); } /** * 求最后一个单词的长度 *https://leetcode.com/problems/length-of-last-word/ */ public int lengthOfLastWord(String str) { int len = str.length(); for(int i=len-1; i>=0;i--) { if (str.charAt(i)==' ') { len--; } else { break; } } str = str.substring(0, len); int index = str.lastIndexOf(" "); return str.length()-index-1; } @Test public void lengthOfLastWordTest() { // Assert.assertEquals(5, lengthOfLastWord("hello world")); // Assert.assertEquals(1, lengthOfLastWord("a ")); // Assert.assertEquals(1, lengthOfLastWord("b a ")); Random random = new Random(); for(int i=0; i<100; i++) { System.out.println(random.nextFloat());; } } /** * 必要时请添加多余的空格'',以使每行都具有完全maxWidth个字符。 * https://leetcode.com/problems/text-justification/ * @param words * @param maxWidth * @return */ public List<String> fullJustify(String[] words, int maxWidth) { int start=0, end=0; int sum = 0; int blank, extra ,addB; List<String> result = new ArrayList<>(); for(int i=0; i< words.length;i++){ end = i; if (sum + words[i].length() + (end-start) > maxWidth) { //超过了长度, maxWidth-单词的长度,然后在均分空格 end--; if (end-start == 0) { blank = maxWidth - words[i].length(); extra = 0; } else { blank = (maxWidth - sum)/(end-start); extra = (maxWidth - sum)%(end-start); } StringBuilder sb = new StringBuilder(); for(int j=start; j<=end; j++) { sb.append(words[j]); if (j== end) { extra = 0; addB = maxWidth-sb.length(); } else { addB = blank; } if(extra>0) { addB++; extra--; } while (addB-- > 0 ){ sb.append(" "); } } result.add(sb.toString()); start = i; end = i; sum = words[i].length(); } else { sum += words[i].length(); } } if (end ==words.length-1) { StringBuilder sb = new StringBuilder(); for(int j=start; j<=end; j++) { sb.append(words[j]); if (j== end) continue; sb.append(" "); } while (maxWidth - sb.length()>0) { sb.append(" "); } result.add(sb.toString()); } return result; } @Test public void fullJustifyTest() { System.out.println(fullJustify(new String[]{ "This", "is", "an", "example", "of", "text", "justification."}, 16)); System.out.println(fullJustify(new String[]{ "What","must","be","acknowledgment","shall","be"}, 16)); System.out.println(fullJustify(new String[]{ "Science","is","what","we","understand","well","enough","to","explain", "to","a","computer.","Art","is","everything","else","we","do"}, 20)); } /** * 求包含字符串t的,s的最小子串 * https://leetcode.com/problems/minimum-window-substring/ * @param s * @param t * @retu */ public String minWindow(String s, String t) { Map<Character, Integer> map = new HashMap<>(t.length()); char c; for(int i=0; i<t.length(); i++){ c = t.charAt(i); if (map.containsKey(c)) { map.put(c, map.get(c)+1); }else { map.put(c, 1); } } int left=0, minLeft=0; int count=0, minLen = s.length()+1; for (int i=0; i<s.length(); i++) { c = s.charAt(i); if (map.containsKey(c)) { map.put(c, map.get(c)-1); if (map.get(c) >= 0 ) { count++; } while (count == t.length()) {// 窗口移动,比较最小值 if (i -left +1 < minLen) { minLeft = left; minLen = i - left+1; } if (map.containsKey(s.charAt(left))) {// 修改left的值 map.put(s.charAt(left), map.get(s.charAt(left))+1);//使移动抛弃的left+1>=0, 使count可以增加 if (map.get(s.charAt(left))>0) {// 去掉重复的值 count--; } } left++; } } } if (minLen > s.length()) { return ""; } return s.substring(minLeft, minLeft+minLen); } @Test public void minWindowTest() { Assert.assertEquals("BANC", minWindow("ADOBECODEBANC","ABC")); } /** * 检查单词在数组中是否存在(必须是连续的) * https://leetcode.com/problems/word-search/ * @param board * @param word * @return */ public boolean exist(char[][] board, String word) { for( int i=0; i< board.length; i++) { for (int j=0; j< board[0].length; j++) { if (dfs(board, i,j,word, 0)) { return true; } } } return false; } private boolean dfs(char[][] board, int i, int j, String word, int count) { if (count == word.length()) { return true; } if (i<0 || i>= board.length || j<0 || j>=board[0].length || board[i][j] != word.charAt(count)) { return false; } board[i][j] = '-';// boolean wordExist = dfs(board,i-1,j, word, count+1) || dfs(board, i+1, j, word, count+1) || dfs(board, i, j-1, word, count+1) || dfs(board, i, j+1, word, count+1); board[i][j] = word.charAt(count); return wordExist; } @Test public void existTest() { char[][] board = { {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }; Assert.assertEquals(true, exist(board,"ABCCED")); Assert.assertEquals(true, exist(board,"SEE")); Assert.assertEquals(false, exist(board,"ABCB")); } }
package com.mad.cityassignment; public class GameSchema { public static class GameTable{ public static final String NAME = "game_data"; public static class Cols { public static final String GAME = "game"; } } }
package com.kh.jd.comment; import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.ibatis.session.SqlSession; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class CommentDAO { @Autowired SqlSession sqlSession; @Autowired SqlSessionTemplate sqlSessionTemplate; // 공지사항 댓글 리스트 public List<Comment> getCommentList(int notice_no){ return sqlSession.selectList("Comment.noticeCommentList", notice_no); } // 공지사항 댓글 작성 public int writeNoticeComment(Comment comment) { int result = sqlSession.insert("Comment.noticeCommentInsert", comment); return result; } // 공지사항 댓글 카운트 public int countNoticeComment(int notice_no) { int result = sqlSession.selectOne("Comment.countNoticeComment", notice_no); return result; } // 공지사항 댓글 삭제 public int deleteNoticeComment(int comment_number) { int result = sqlSession.delete("Comment.noticeCommentDelete", comment_number); return result; } // 공지 사항 댓글 수정 public int updateNoticeComment(String comment_con,int comment_number) { HashMap<String, String> map = new HashMap<String, String>(); map.put("comment_con", comment_con); map.put("comment_number", Integer.toString(comment_number)); int result = sqlSession.update("Comment.noticeCommentUpdate", map); return result; } // 비디오 댓글 리스트 public List<Comment> getVideoCommentList(int video_no){ return sqlSession.selectList("Comment.videoCommentList", video_no); } // 비디오 댓글 작성 public int writeVideoComment(Comment comment) { int result = sqlSession.insert("Comment.videoCommentInsert", comment); return result; } // 비디오 댓글 카운트 public int countVideoComment(int video_no) { int result = sqlSession.selectOne("Comment.countVideoComment", video_no); return result; } // 비디오 댓글 삭제 public int deleteVideoComment(int comment_number) { int result = sqlSession.delete("Comment.videoCommentDelete", comment_number); return result; } // 비디오 댓글 수정 public int updateVideoComment(String comment_con,int comment_number) { HashMap<String, String> map = new HashMap<String, String>(); map.put("comment_con", comment_con); map.put("comment_number", Integer.toString(comment_number)); int result = sqlSession.update("Comment.videoCommentUpdate", map); return result; } }
package sk.stuba.uim.fei.oop; public class Auto { private static final double FUEL_PER_KM=0.2; private double kapacitaNadrze; public double stavNadrze; private boolean neojazdene;//primitivny datovy typ,nie su objekty, int, double char public Auto(double kapacitaNadrze){ this.neojazdene=true; this.kapacitaNadrze=kapacitaNadrze; } public Auto(){ this(100); } public double dotankova(){ double diff = kapacitaNadrze-stavNadrze; stavNadrze= kapacitaNadrze; return diff; } public void drive(double distance){ this.neojazdene=false; stavNadrze -= distance*FUEL_PER_KM; if(stavNadrze<0){ stavNadrze=0; } } public double getStavNadrze(){ return stavNadrze; } public void setStavNadrze(double stavNadrze){ this.stavNadrze = stavNadrze; } public String currentState(){ String result; if(this.neojazdene){ result="Auto je neojazdene\n"; } else { result="Auto je ozajdene"; } result +="\n"+ stavNadrze+"\\"+kapacitaNadrze; return result; } }
package com.gaoshin.cloud.web.xen.service; import java.util.Map; import java.util.Map.Entry; import com.gaoshin.cloud.web.xen.bean.HostNetwork; import com.gaoshin.cloud.web.xen.bean.HostNetworkList; import com.xensource.xenapi.Network; import com.xensource.xenapi.Network.Record; public class NetworkXenTask extends XenTask { private HostNetworkList networks = new HostNetworkList(); private Long hostId; public NetworkXenTask(String url, String user, String pwd, Long hostId) { super(url, user, pwd); this.hostId = hostId; } @Override protected void doTask() throws Exception { Map<Network, Record> allRecords = Network.getAllRecords(connection); for(Entry<Network, Record> entry : allRecords.entrySet()) { Record rec = entry.getValue(); Network s = entry.getKey(); HostNetwork hn = new HostNetwork(); hn.setUuid(rec.uuid); hn.setBridge(rec.bridge); hn.setNameLabel(rec.nameLabel); hn.setNameDescription(rec.nameDescription); networks.getItems().add(hn); } } public HostNetworkList getNetworks() { return networks; } public void setNetworks(HostNetworkList networks) { this.networks = networks; } }
package io.qtechdigital.onlineTutoring.service.authentication; import io.qtechdigital.onlineTutoring.dto.auth.AuthenticationRequestDto; import org.springframework.security.core.Authentication; public interface AuthenticationService { Authentication authenticate(AuthenticationRequestDto requestDto); }
package com.krish.iw; import java.util.ArrayList; import java.util.List; public class MergeSortedList { public static void main(String[] args) { List<Integer> lst1 = new ArrayList<Integer>(); List<Integer> lst2 = new ArrayList<Integer>(); lst1.add(1); lst1.add(3); lst1.add(5); lst1.add(7); lst1.add(9); lst1.add(11); lst1.add(13); lst2.add(1); lst2.add(2); lst2.add(4); lst2.add(6); lst2.add(8); lst2.add(10); merge(lst1, lst2); } private static void merge(List<Integer> lst1, List<Integer> lst2) { int i = 0; int j = 0; List<Integer> lst = new ArrayList<Integer>(); while (i < lst1.size() || j < lst2.size()) { if (i < lst1.size() && j < lst2.size()) { if (lst1.get(i) <= lst2.get(j)) { lst.add(lst1.get(i)); i++; } else { lst.add(lst2.get(j)); j++; } } else { if (lst1.size() > i) { lst.addAll(lst1.subList(i, lst1.size())); i = lst1.size(); } if (lst2.size() > j) { lst.addAll(lst2.subList(j, lst2.size())); j = lst2.size(); } } } System.out.println(lst); } }
package com.ractive.netty; import io.reactivex.netty.protocol.http.server.HttpServer; import rx.Observable; import java.math.BigDecimal; public class RxNettyRestServer { private static final BigDecimal RATE = new BigDecimal("1.06448"); public static void main(String[] args) { HttpServer.newServer(8080).start((req, resp) -> { String eur = req.getDecodedPath().substring(1); return resp.writeStringAndFlushOnEach( Observable .range(0, 1000) .onBackpressureBuffer(10) .map( a -> eurToUsd(eur)) ); }).awaitShutdown(); } private static String eurToUsd(String eur) { return eur + " EUR is " + new BigDecimal(eur).multiply(RATE) + " USD\n"; } }
package com.javarush.test.level08.lesson08.task04; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /* Удалить всех людей, родившихся летом Создать словарь (Map<String, Date>) и занести в него десять записей по принципу: «фамилия» - «дата рождения». Удалить из словаря всех людей, родившихся летом. */ public class Solution { public static HashMap<String, Date> createMap() { HashMap<String, Date> map = new HashMap<String, Date>(); map.put("Stallone1", new Date("JUNE 1 1989")); map.put("Stallon2", new Date("JUNE 1 1988")); map.put("Stallon3", new Date("JUNE 1 1987")); map.put("Stallon4", new Date("JUNE 1 1986")); map.put("Stallon5", new Date("JUNE 1 1985")); map.put("Stallon6", new Date("DECEMBER 1 1984")); map.put("Stallon7", new Date("JUNE 1 1983")); map.put("Stallon8", new Date("SEPTEMBER 1 1982")); map.put("Stallon9", new Date("JUNE 1 1981")); map.put("Stallone", new Date("MAY 1 1980")); //напишите тут ваш код return map; } public static void removeAllSummerPeople(HashMap<String, Date> map) { Iterator iterator= map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Date> pair = (Map.Entry<String, Date>)iterator.next(); Date date = pair.getValue(); if (date.getMonth()>4&&date.getMonth()<8) iterator.remove(); } for (String s : map.keySet()){ System.out.println(s); } } //напишите тут ваш код public static void main(String [] args){ removeAllSummerPeople(createMap()); } }
package dao; import model.Project; public interface ProjectDaoInterface { Project insert(Project project); boolean delete(int projectId); Project update(int projectId,String endDate,String status); }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.debug.ui.views; import org.eclipse.debug.internal.core.commands.Request; import org.eclipse.debug.internal.ui.viewers.model.provisional.IPresentationContext; import org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate; import org.eclipse.jface.viewers.TreePath; import org.eclipse.ui.IMemento; /** * @since 3.3 */ abstract class MementoUpdate extends Request implements IViewerUpdate { private IPresentationContext fContext; private Object fElement; private TreePath fElementPath; private IMemento fMemento; protected TreeModelContentProvider fProvider; protected Object fViewerInput; /** * Constructs a viewer state request. * * @param provider * the content provider to use for the update * @param viewerInput * the current input * @param elementPath * the path of the element to update * @param element * the element to update * @param memento * Memento to update * @param context * the presentation context * */ public MementoUpdate(TreeModelContentProvider provider, Object viewerInput, IPresentationContext context, Object element, TreePath elementPath, IMemento memento) { fContext = context; fElement = element; fElementPath = elementPath; fMemento = memento; fProvider = provider; fViewerInput = viewerInput; } /* * (non-Javadoc) * * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate#getPresentationContext() */ public IPresentationContext getPresentationContext() { return fContext; } /* * (non-Javadoc) * * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate#getElement() */ public Object getElement() { return fElement; } /* * (non-Javadoc) * * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate#getElementPath() */ public TreePath getElementPath() { return fElementPath; } public IMemento getMemento() { return fMemento; } public TreeModelContentProvider getContentProvider() { return fProvider; } public Object getElement(TreePath path) { return fProvider.getElement(path); } /* * (non-Javadoc) * * @see org.eclipse.debug.internal.ui.viewers.model.provisional.IViewerUpdate#getViewerInput() */ public Object getViewerInput() { return fViewerInput; } }
package com.springboot.racemanage.controller; import com.springboot.racemanage.po.*; import com.springboot.racemanage.service.*; import com.springboot.racemanage.util.UploadFile; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; @Controller @RequestMapping("/teacher") @Transactional public class TeacherController { private static final String MENU_SELECTED_1 = "menuSelected1"; private static final String RACE_INFO_LIST = "raceInfoList"; private static final String MENU_SELECTED_2 = "menuSelected2"; private static final String RACE_MANAGE = "raceManage"; @Autowired TermService termService; @Autowired StudentService studentService; @Autowired TeamerService teamerService; @Autowired InviteService inviteService; @Autowired MessageService messageService; @Autowired TeacherService teacherService; @Autowired RaceService raceService; @Autowired RaceinfoService raceinfoService; @Autowired ProjectService projectService; @Autowired TaskService taskService; @Autowired SolutionService solutionService; @Autowired LogService logService; @RequestMapping(value = "/login.do", method = RequestMethod.POST) public String login(Model model, HttpSession httpSession, @RequestParam("username") String tNumber, @RequestParam("password") String password) { Teacher teacher = teacherService.login(1, tNumber, password); if (teacher == null) { model.addAttribute("errorMsg", "工号或密码错误"); return "login"; } else { Term term = termService.findFirstByStatusOrderByTerm(1); httpSession.setAttribute("term", term); httpSession.setAttribute("teacher", teacher); return "forward:/teacher/index.do"; } } @RequestMapping("logout.do") public String logout(HttpSession httpSession) { httpSession.removeAttribute("teacher"); httpSession.removeAttribute("term"); return "login"; } @RequestMapping("/index.do") public String index(Model model, HttpSession httpSession) { Term term = (Term) httpSession.getAttribute("term"); List<Raceinfo> raceinfoList = raceinfoService.findByStatusAndTerm(1, term.getTerm()); model.addAttribute("raceinfoList", raceinfoList); return "teacher/index"; } @RequestMapping("/profile.do") public String profile(Model model, HttpSession httpSession) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); model.addAttribute("teacher", teacher); return "teacher/profile"; } @RequestMapping("/updateProfile.do") public String updateProfile(Model model, HttpSession httpSession, @RequestParam(value = "tEmail", required = false) String tEmail, @RequestParam("phone") String phone, @RequestParam("oldPasswd") String oldPasswd, @RequestParam("newPasswd") String newPasswd, //TODO 上传文件需要重新再搞下 @RequestParam(value = "photo",required = false) MultipartFile photo) throws IOException { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); if (oldPasswd.equals(teacher.gettPassword())) { teacher.settEmail(tEmail); teacher.settPhone(phone); teacher.settPassword(newPasswd); if (phone!=null) { teacher.settPhoto(UploadFile.uploadFile(photo,photo.getOriginalFilename(),"photo/").getPath()); } model.addAttribute("updateMsg", "更新成功"); return "forward:/teacher/profile.do"; } else if (oldPasswd.length() == 0) { teacher.settEmail(tEmail); teacher.settPhone(phone); model.addAttribute("updateMsg", "更新成功"); return "forward:/teacher/profile.do"; } else { model.addAttribute("updateMsg", "更新失败"); return "forward:/teacher/profile.do"; } } @RequestMapping("raceInfoList.do") public String raceInfoList(Model model, HttpSession httpSession) { model.addAttribute(MENU_SELECTED_1, RACE_MANAGE); model.addAttribute(MENU_SELECTED_2, RACE_INFO_LIST); Term term = (Term) httpSession.getAttribute("term"); List<Raceinfo> raceinfoList = raceinfoService.findByStatusAndTerm(1, term.getTerm()); model.addAttribute("raceinfoList", raceinfoList); return "teacher/raceInfoList"; } @RequestMapping("/raceInfoDetail.do") public String raceInfoDetail(Model model, HttpSession httpSession, @RequestParam("raceInfoUUID") String raceInfoUUID) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Term term = (Term) httpSession.getAttribute("term"); Raceinfo raceinfo = raceinfoService.findFirstByUuid(raceInfoUUID); List<Project> projectList = projectService.findCanRaceProject(teacher.gettUuid(), term.getTerm(), raceInfoUUID); model.addAttribute("raceInfo", raceinfo); model.addAttribute("projectList", projectList); return "teacher/raceInfoDetail"; } @RequestMapping("/addRace.do") public String addRace(Model model, HttpSession httpSession, @RequestParam("projectUUID") String projectUUID, @RequestParam("raceInfoUUID") String raceInfoUUID) { Project project = projectService.findFirstByUuid(projectUUID); Raceinfo raceinfo = raceinfoService.findFirstByUuid(raceInfoUUID); Term term = (Term) httpSession.getAttribute("term"); if (projectUUID == null || projectUUID.length() == 0) { System.out.println("项目不能为空"); return "forward:/teacher/raceInfoDetail.do?raceInfoUUID=" + raceInfoUUID; } Race race = new Race(); race.setDescription(raceinfo.getDescription()); race.setKind(raceinfo.getKind()); race.setProname(project.getName()); race.setProUuid(project.getUuid()); race.setRaceinfoUuid(raceInfoUUID); race.setRacename(raceinfo.getRacename()); race.setRaceteacher(project.getTname()); race.setStatus(1); race.setTerm(term.getTerm()); race.settUuid(project.gettUuid()); race.setUuid(UUID.randomUUID().toString()); raceService.insertSelective(race); return "forward:/teacher/teacInfoList.do"; } @RequestMapping("/myRaceList.do") public String raceList(Model model, HttpSession httpSession) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Term term = (Term) httpSession.getAttribute("term"); List<Race> raceList = raceService.findByStatusAndTermAndTUuid(1, term.getTerm(), teacher.gettUuid()); model.addAttribute("myRaceList", raceList); return "teacher/myRaceList"; } @RequestMapping("/raceDetail.do") public String raceDetail(Model model, HttpSession httpSession, @RequestParam("raceUUID") String raceUUID) { Race race = raceService.findByUuid(raceUUID); List<Teamer> teamerList = teamerService.findByStatusAndProUuid(1, race.getProUuid()); Raceinfo raceinfo = raceinfoService.findFirstByUuid(race.getRaceinfoUuid()); model.addAttribute("race", race); model.addAttribute("teamerList", teamerList); model.addAttribute("raceinfo", raceinfo); return "teacher/raceDetail"; } @RequestMapping("/updateRace.do") public String updateRace(Model model, HttpSession httpSession, @RequestParam("raceUUID") String raceUUID, @RequestParam(value = "file1", required = false) MultipartFile file1, @RequestParam(value = "file2", required = false) MultipartFile file2, @RequestParam(value = "file3", required = false) MultipartFile file3) throws IOException { Race race = raceService.findByUuid(raceUUID); if (file1 != null) { race.setFile1(UploadFile.uploadFile(file1,file1.getOriginalFilename(),"file/").getPath()); } if (file2 != null) { race.setFile1(UploadFile.uploadFile(file2,file2.getOriginalFilename(),"file/").getPath()); } if (file3 != null) { race.setFile1(UploadFile.uploadFile(file3,file3.getOriginalFilename(),"file/").getPath()); } raceService.update(race); return "forward:/teacher/myRaceList.do"; } @RequestMapping("/achievementList.do") public String achievementList(Model model, HttpSession httpSession) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); List<Race> achivList = raceService.findByStatusAndTUuidAndProgress(1, teacher.gettUuid(), 1); model.addAttribute("achivList", achivList); return "teacher/achievementList"; } @RequestMapping("/achievementToExcel.do") public String achievementToExcel(HttpServletResponse response, HttpSession httpSession) throws IOException, WriteException { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); List<Race> achivList = raceService.findByStatusAndTUuidAndProgress(1, teacher.gettUuid(), 1); response.setCharacterEncoding("utf-8"); response.setHeader("Content-disposition","attachment;filename=achievement.xls"); response.setContentType("application/msexcel;"); OutputStream os = response.getOutputStream(); WritableWorkbook workbook = Workbook.createWorkbook(os); WritableSheet sheet = workbook.createSheet("学科竞赛所获成果报表",0); Integer xnum = 1; sheet.addCell(new Label(0,0,"序号")); sheet.addCell(new Label(1,0,"赛事名称")); sheet.addCell(new Label(2,0,"赛事类型")); sheet.addCell(new Label(3,0,"赛事期数")); sheet.addCell(new Label(4,0,"参赛项目")); sheet.addCell(new Label(5,0,"指导教师")); sheet.addCell(new Label(6,0,"所获奖项")); for(Race race : achivList){ if (xnum < achivList.size()+1){ sheet.addCell(new Label(0,xnum,race.getId().toString())); sheet.addCell(new Label(1,xnum,race.getRacename())); sheet.addCell(new Label(2,xnum,race.getKind())); sheet.addCell(new Label(3,xnum,race.getTerm().toString())); sheet.addCell(new Label(4,xnum,race.getProname())); sheet.addCell(new Label(5,xnum,race.getRaceteacher())); if (race.getResult()==0){ sheet.addCell(new Label(6,xnum,"无奖项")); }else if (race.getResult()==1){ sheet.addCell(new Label(6,xnum,"一等奖")); }else if (race.getResult()==2){ sheet.addCell(new Label(6,xnum,"二等奖")); }else if (race.getResult()==3){ sheet.addCell(new Label(6,xnum,"三等奖")); }else{ sheet.addCell(new Label(6,xnum,"其他奖项")); } } xnum++; } workbook.write(); workbook.close(); os.close(); return null; } @RequestMapping("/achievementDetail.do") public String achievementDetail(Model model, @RequestParam("raceUUID") String raceUUID) { Race race = raceService.findByUuid(raceUUID); Raceinfo raceinfo = raceinfoService.findFirstByUuid(race.getRaceinfoUuid()); Project project = projectService.findFirstByUuid(race.getProUuid()); List<Teamer> teamerList = teamerService.findByStatusAndProUuid(1, project.getUuid()); Teacher raceTeacher = teacherService.findByTUuid(race.gettUuid()); model.addAttribute("race", race); model.addAttribute("raceinfo", raceinfo); model.addAttribute("teamerList", teamerList); model.addAttribute("raceTeacher", raceTeacher); return "teacher/achievementDetail"; } @RequestMapping("/toAddProject.do") public String toAddProject(Model model, HttpSession httpSession) { List<Student> stuList = studentService.findByStuStatus(1); model.addAttribute("stuList", stuList); return "teacher/addProject"; } @RequestMapping("/addProject.do") public String addProject(Model model, HttpSession httpSession, @RequestParam("proName") String proName, @RequestParam("proDescription") String proDescription, @RequestParam(value = "document", required = false) MultipartFile document, @RequestParam("stuUuid[]") List<String> stuUUIDList) throws IOException { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Project project = new Project(); project.setName(proName); project.setDescription(proDescription); project.setUuid(UUID.randomUUID().toString()); project.setDocument("");//后期处理文件上传一并解决 project.settUuid(teacher.gettUuid()); project.setTname(teacher.gettName()); project.setStatus(1); project.setDocument(UploadFile.uploadFile(document,document.getOriginalFilename(),"doc/").getPath()); projectService.insertSelective(project); Invite stuInvite = new Invite(); stuUUIDList.forEach(tostuuuid -> { stuInvite.setDuty("1"); stuInvite.setTeamerDescription(project.getDescription()); stuInvite.setFromUuid(teacher.gettUuid()); stuInvite.setUuid(UUID.randomUUID().toString()); stuInvite.setProname(project.getName()); stuInvite.setProUuid(project.getUuid()); stuInvite.setSendtime(new Date()); stuInvite.setToUuid(tostuuuid); stuInvite.setStatus(1); inviteService.insertSelective(stuInvite); }); return "redirect:/teacher/projectList.do"; } @RequestMapping("/projectList.do") public String projectList(Model model, HttpSession httpSession) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); List<Project> projectList = projectService.findByStatusAndTUuid(1, teacher.gettUuid()); model.addAttribute("projectList", projectList); return "teacher/projectList"; } @RequestMapping("/projectDetail.do") public String projectDetail(Model model, HttpSession httpSession, @RequestParam("proUUID") String proUUID) { Project project = projectService.findByUuid(proUUID).get(0); List<Task> allTaskList = taskService.findByProUuidAndStatusNot(proUUID,0); List<Teamer> proTeamerList = teamerService.findByStatusAndProUuid(1, proUUID); model.addAttribute("project", project); model.addAttribute("allTaskList", allTaskList); model.addAttribute("proTeamerList", proTeamerList); return "teacher/projectDetail"; } @RequestMapping("/projectTimeLine.do") public String projectTimeLine(Model model, HttpSession httpSession, @RequestParam("projectUUID") String projectUUID) { Project project = projectService.findFirstByUuid(projectUUID); //名字太不优雅 回来想到更好的就改下 List<Map> logandteamernameList = logService.getLogAndTeamerNameByProUuid(projectUUID); model.addAttribute("logandteamernameList", logandteamernameList); model.addAttribute("project", project); return "teacher/projectTimeLine"; } @RequestMapping("/toPublishTask.do") public String toPublishTask(Model model ,HttpSession httpSession, @RequestParam("proUUID")String proUUID, @RequestParam("teamerUUID")String teamerUUID) { Project project = projectService.findFirstByUuid(proUUID); List<Teamer> teamerList = teamerService.findByStatusAndProUuid(1,proUUID); Teamer teamer = teamerService.findFirstByUuid(teamerUUID); model.addAttribute("project", project); model.addAttribute("teamerList", teamerList); model.addAttribute("teamer", teamer); return "teacher/publishTask"; } //给多人分配同一个任务不可行 没意义 // @RequestMapping("/publishTask.do") // public String publishTask(Model model,HttpSession httpSession, // @RequestParam("title")String title, // @RequestParam("description")String description, // @RequestParam("teamerUuid[]")List<String> teamerUUIDList) { // Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); // // } @RequestMapping("/publishTask.do") public String publishTask(HttpSession httpSession, @RequestParam("title")String title, @RequestParam(value = "description",required = false)String description, @RequestParam("teamerUUID")String teamerUUID, @RequestParam(value = "file1",required = false)MultipartFile file1) throws IOException { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Teamer teamer = teamerService.findFirstByUuid(teamerUUID); Task task = new Task(); task.setDescription(description); if (file1!=null) { task.setFile1(UploadFile.uploadFile(file1,file1.getOriginalFilename(),"file/").getPath()); } task.setFromUuid(teacher.gettUuid()); task.setProUuid(teamer.getProUuid()); task.setStatus(2); task.setTitle(title); task.setToUuid(teamerUUID); task.setUuid(UUID.randomUUID().toString()); taskService.insertSelective(task); return "forward:/teacher/projectDetail.do?proUUID=" + teamer.getProUuid(); } @RequestMapping("/toReviewTask.do") public String toReviewTask(Model model , HttpSession httpSession, @RequestParam("taskUUID")String taskUUID) { Task task = taskService.findFirstByUuid(taskUUID); Solution solution = solutionService.findByResultAndStatusAndTaskUuid(3, 1, taskUUID); Teamer teamer = teamerService.findFirstByUuid(task.getToUuid()); model.addAttribute("solution", solution); model.addAttribute("task", task); model.addAttribute("teamer", teamer); return "teacher/reviewTask"; } @RequestMapping("/passTask.do") public String passTask(HttpSession httpSession, @RequestParam("solutionUUID")String solutionUUID) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Solution solution = solutionService.findByUuid(solutionUUID); Task task = taskService.findFirstByUuid(solution.getTaskUuid()); Teamer teamer = teamerService.findFirstByUuid(task.getToUuid()); Project project = projectService.findFirstByUuid(task.getProUuid()); Log log = new Log(); //以系统身份任务完成消息 Message message = new Message(); message.setUuid(UUID.randomUUID().toString()); message.setFromUuid("000"); String msg = teacher.gettName() + "通过了您 " + solution.getTitle() + " 的解决方案。"; message.setContent(msg); message.setSendtime(new Date()); message.setTitle("系统提示"); message.setToUuid(teamer.getStuUuid()); message.setStatus(1); //改变任务状态和解决方案状态 solution.setResult(1); task.setProgress(1); //新建log log.setAction("完成项目任务"); log.setDescription("完成 "+task.getTitle()); log.setProUuid(project.getUuid()); log.setTasktitle(task.getTitle()); log.setTaskUuid(task.getUuid()); log.setTeamerUuid(teamer.getUuid()); log.setTheTime(new Date()); log.setUuid(UUID.randomUUID().toString()); messageService.insertSelective(message); solutionService.update(solution); taskService.update(task); logService.insertSelective(log); return "forward:/teacher/projectDetail.do?proUUID=" + project.getUuid(); } @RequestMapping("/rejectTask.do") public String rejectTask(HttpSession httpSession, @RequestParam("solutionUUID")String solutionUUID) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Solution solution = solutionService.findByUuid(solutionUUID); Task task = taskService.findFirstByUuid(solution.getTaskUuid()); Teamer teamer = teamerService.findFirstByUuid(task.getToUuid()); Project project = projectService.findFirstByUuid(task.getProUuid()); //以系统身份发送任务不通过消息 Message message = new Message(); message.setUuid(UUID.randomUUID().toString()); message.setFromUuid("000"); String msg = teacher.gettName() + "没有通过您 " + solution.getTitle() + " 的解决方案。"; message.setContent(msg); message.setSendtime(new Date()); message.setTitle("系统提示"); message.setToUuid(teamer.getStuUuid()); message.setStatus(1); //改变任务状态和解决方案状态 solution.setResult(2); task.setProgress(2); messageService.insertSelective(message); solutionService.update(solution); taskService.update(task); return "forward:/teacher/projectDetail.do?proUUID=" + project.getUuid(); } @RequestMapping("/inviteList.do") public String inviteList(Model model, HttpSession httpSession) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); List<Invite> inviteList = inviteService.findByToUuidAndStatus(teacher.gettUuid(), 1); System.out.println(inviteList); model.addAttribute("inviteList", inviteList); return "teacher/inviteList"; } @RequestMapping("/acceptInvite.do") public String acceptInvite(Model model, HttpSession httpSession, @RequestParam("inviteUUID")String inviteUUID) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Invite invite = inviteService.findByUuid(inviteUUID); Project project = projectService.findFirstByUuid(invite.getProUuid()); //以系统身份发送邀请接受消息 Message message = new Message(); message.setUuid(UUID.randomUUID().toString()); message.setFromUuid("000"); String rfusMsg ="教师"+ teacher.gettName() + "接受了您 " + project.getName() + " 的项目邀请。"; message.setContent(rfusMsg); message.setSendtime(new Date()); message.setTitle("系统提示"); message.setToUuid(invite.getFromUuid()); message.setStatus(1); //修改邀请信息状态 invite.setStatus(2); //修改项目指导教师 project.settUuid(teacher.gettUuid()); project.setTname(teacher.gettName()); inviteService.update(invite); messageService.insertSelective(message); projectService.update(project); return "forward:/teacher/inviteList.do"; } @RequestMapping("/refuseInvite.do") public String refuseInvite(Model model, HttpSession httpSession, @RequestParam("inviteUUID") String inviteUUID) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); Invite invite = inviteService.findByUuid(inviteUUID); Project project = projectService.findFirstByUuid(invite.getProUuid()); //以系统身份发送邀请被拒绝消息 Message message = new Message(); message.setUuid(UUID.randomUUID().toString()); message.setFromUuid("000"); String rfusMsg = "教师"+ teacher.gettName() + "拒绝了您 " + project.getName() + " 的项目邀请。"; message.setContent(rfusMsg); message.setSendtime(new Date()); message.setTitle("系统提示"); message.setToUuid(invite.getFromUuid()); message.setStatus(1); System.out.println("+++++++" + message); //修改邀请信息状态 invite.setStatus(3); System.out.println("~~~~~~" + invite); inviteService.update(invite); messageService.insertSelective(message); return "forward:/teacher/inviteList.do"; } @RequestMapping("/ignoreInvite.do") public String ignoreInvite(Model model, HttpSession httpSession, @RequestParam("inviteUUID") String inviteUUID) { Invite invite = inviteService.findByUuid(inviteUUID); invite.setStatus(4); inviteService.update(invite); return "forward:/teacher/inviteList.do"; } @RequestMapping("/msgCenter.do") public String msgCenter(Model model , HttpSession httpSession) { Teacher teacher = (Teacher) httpSession.getAttribute("teacher"); List<Message> messageList = messageService.findByToUuidAndStatus(teacher.gettUuid(), 1); List<Map<String, String>> mapList = messageService.getMsgWithStuName(teacher.gettUuid()); System.out.println("_____" + mapList.size()); model.addAttribute("msgList", messageList); model.addAttribute("mapList", mapList); return "teacher/messageCenter"; } }
package escolasis.ws.jaxws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import escolasis.modelo.xml.ListaPessoaInsert; @XmlRootElement(name = "CadastrarListaPessoasResponse", namespace = "http://ws.escolasis/") @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CadastrarListaPessoasResponse", namespace = "http://ws.escolasis/") public class SalvarResponse { @XmlElement(name = "pessoas", namespace = "") private ListaPessoaInsert pessoas; /** * * @return * returns ListaPessoaInsert */ public ListaPessoaInsert getPessoas() { return this.pessoas; } /** * * @param pessoas * the value for the pessoas property */ public void setPessoas(ListaPessoaInsert pessoas) { this.pessoas = pessoas; } }
package net.lvcy.card.entity.gate.mid; import net.lvcy.card.core.AbstarctCard; import net.lvcy.card.entity.gate.MidCard; import net.lvcy.card.eumn.CardType; public class ThreeThree extends AbstarctCard implements MidCard { public ThreeThree() { this.type = CardType.THREE_THREE; } }
package org.vanilladb.comm.protocols.tcpfd; import net.sf.appia.core.AppiaEventException; import net.sf.appia.core.Channel; import net.sf.appia.core.Direction; import net.sf.appia.core.Event; import net.sf.appia.core.Session; public class ProcessConnected extends Event { private int connectedProcessId; public ProcessConnected(Channel channel, Session src, int connectedProcessId) throws AppiaEventException { super(channel, Direction.UP, src); this.connectedProcessId = connectedProcessId; } public int getConnectedProcessId() { return connectedProcessId; } }
package com.test.demo.Entities; import java.util.Set; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "investors") @AttributeOverrides({ @AttributeOverride(name="id", column=@Column(name="investor_id")), //@AttributeOverride(name="name", column=@Column(name="name")) }) public class Investors extends Node { @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "Investors_Funds", joinColumns = { @JoinColumn(referencedColumnName = "investor_id") }, inverseJoinColumns = { @JoinColumn(referencedColumnName = "fund_id") }) private Set<Funds> funds; public Set<Funds> getFunds() { return funds; } public void setFunds(Set<Funds> funds) { this.funds = funds; } }
package com.zd.christopher.action; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.google.gson.reflect.TypeToken; import com.zd.christopher.bean.Administrator; import com.zd.christopher.bean.Faculty; import com.zd.christopher.json.JsonForm; import com.zd.christopher.transaction.AdministratorTransaction; @Controller @Scope("prototype") public class AdministratorAction extends BaseAction<Administrator> { private static final long serialVersionUID = 1L; @Resource private AdministratorTransaction administratorTransaction; public AdministratorAction() { this.entityClass = Administrator.class; } public Boolean getModel() { super.getModel(); jsonForm = gson.fromJson(form, new TypeToken<JsonForm<Administrator>>(){}.getType()); return true; } }
/* * Copyright (c) 2013-2014, Neuro4j.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.neuro4j.studio.core.diagram.navigator; import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.IMemento; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.ICommonLabelProvider; import org.neuro4j.studio.core.diagram.part.Neuro4jDiagramEditorPlugin; /** * @generated */ public class Neuro4jDomainNavigatorLabelProvider implements ICommonLabelProvider { /** * @generated */ private AdapterFactoryLabelProvider myAdapterFactoryLabelProvider = new AdapterFactoryLabelProvider( Neuro4jDiagramEditorPlugin.getInstance() .getItemProvidersAdapterFactory()); /** * @generated */ public void init(ICommonContentExtensionSite aConfig) { } /** * @generated */ public Image getImage(Object element) { if (element instanceof Neuro4jDomainNavigatorItem) { return myAdapterFactoryLabelProvider .getImage(((Neuro4jDomainNavigatorItem) element) .getEObject()); } return null; } /** * @generated */ public String getText(Object element) { if (element instanceof Neuro4jDomainNavigatorItem) { return myAdapterFactoryLabelProvider .getText(((Neuro4jDomainNavigatorItem) element) .getEObject()); } return null; } /** * @generated */ public void addListener(ILabelProviderListener listener) { myAdapterFactoryLabelProvider.addListener(listener); } /** * @generated */ public void dispose() { myAdapterFactoryLabelProvider.dispose(); } /** * @generated */ public boolean isLabelProperty(Object element, String property) { return myAdapterFactoryLabelProvider.isLabelProperty(element, property); } /** * @generated */ public void removeListener(ILabelProviderListener listener) { myAdapterFactoryLabelProvider.removeListener(listener); } /** * @generated */ public void restoreState(IMemento aMemento) { } /** * @generated */ public void saveState(IMemento aMemento) { } /** * @generated */ public String getDescription(Object anElement) { return null; } }
package com.proyectogrado.alternativahorario.alternativahorario.web; import com.proyectogrado.alternativahorario.alternativahorario.negocio.FachadaNegocioLocal; import com.proyectogrado.alternativahorario.entidades.Facultad; import com.proyectogrado.alternativahorario.entidades.Sede; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.view.ViewScoped; import javax.inject.Named; import lombok.Setter; import lombok.Getter; import org.omnifaces.util.Messages; /** * * @author Steven */ @Named(value = "modificacionFacultad") @ViewScoped public class ModificacionFacultadMB implements Serializable { private static final long serialVersionUID = 1L; @EJB private FachadaNegocioLocal fachadaNegocio; @Getter @Setter private List<String> sedes; @Getter @Setter private Facultad facultadSeleccionada; @Getter @Setter private String nombre; @Getter @Setter private String sede; @PostConstruct public void init() { sedes = llenarListaSedes(); } public void cargarDatos() { facultadSeleccionada = fachadaNegocio.getFacultadPorNombre(nombre); sede = facultadSeleccionada.getSede().getNombre(); } public List<String> llenarListaSedes() { List<Sede> sedes = fachadaNegocio.getSedes(); List<String> sedesLabel = new ArrayList(); for (Sede sede : sedes) { sedesLabel.add(sede.getNombre()); } return sedesLabel; } public Sede buscarSede(String nombreSede) { return fachadaNegocio.getSedePorNombre(nombreSede); } public void modificarfacultad() { facultadSeleccionada.setNombre(this.nombre); facultadSeleccionada.setSede(buscarSede(this.sede)); boolean modificarFacultad = fachadaNegocio.modificarFacultad(facultadSeleccionada); if (modificarFacultad) { notificarModificacionExitosa(); } else { notificarModificacionFallida(); } } public void notificarModificacionExitosa() { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO", "Se modifica la facultad Exitosamente"); Messages.addFlashGlobal(msg); } public void notificarModificacionFallida() { FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "Hubo un error al modificar la Facultad"); Messages.addFlashGlobal(msg); } }
package cluster.shop.items; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import cluster.shop.Shop; public class ItemManager { private File file; private FileConfiguration stream; private List<ShopItem> items = new ArrayList<>(); public ItemManager(Shop plugin) { this.file = new File(plugin.getDataFolder(), "items.yml"); if(!file.exists()) { try { file.createNewFile(); } catch(IOException e) { throw new RuntimeException(e); } } stream = YamlConfiguration.loadConfiguration(file); Set<String> keys = stream.getKeys(false); if(keys == null || keys.isEmpty()) return; for (String name : keys) { try { Map<String, Integer> enchantments = new HashMap<>(); ConfigurationSection sec = stream.getConfigurationSection(name + ".enchantments"); if(sec != null) { Set<String> ekeys = sec.getKeys(false); if(ekeys != null) for (String ek : ekeys) enchantments.put(ek, stream.getInt(name + ".enchantments." + ek)); } ShopItem item = ShopItem.deserialize(name, stream.getString(name + ".id"), stream.getString(name + ".name"), stream.getStringList(name + ".lore"), enchantments); items.add(item); } catch (Exception e) { Shop.err("Malformed item '" + name + "' in items.yml", e); } } } public ShopItem getItem(String key) { for (ShopItem i : items) { if(i.getKey().equalsIgnoreCase(key)) return i; } return null; } }
package com.rqhua.demo.lib_annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by Administrator on 2018/6/25. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.SOURCE) public @interface FieldAnnotation { int value(); }
package com.thoughtworks.maomao.noam; import com.thoughtworks.maomao.noam.annotation.Column; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; public class ModelInfo { private String tableName; private List<String> columns = new ArrayList(); private Class modelClass; public ModelInfo(Class modelClass) { this.modelClass = modelClass; this.tableName = FieldValueUtil.toUpperUnderscore(modelClass.getSimpleName()); initColumns(modelClass); } private void initColumns(Class modelClass) { Field[] fields = modelClass.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.isAnnotationPresent(Column.class)) { this.columns.add(field.getName()); } } } public String getTableName() { return tableName; } public List<String> getColumns() { return columns; } public Class getModelClass() { return modelClass; } }
package codejam1; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; class gomo{ public static void main(String[] args) { System.out.println("give input to file instream for file "); Scanner sc = null; try { sc = new Scanner(new File("C:/Users/Aloy Aditya Sen/workspace/Thought/src/input/inStream")); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File fi=new File("E:/newfile.txt"); System.out.println("hitchka"); try { if (!fi.exists()) { fi.createNewFile(); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try (FileOutputStream o =new FileOutputStream(fi)){ System.out.println("hitchka"); do { String a =sc.next(); a+=" "; byte[] content =a.getBytes(); o.write(content); fi.setReadOnly(); } while (sc.hasNext()); o.close(); System.out.println("file cerated"); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
package com.god.gl.vaccination.base; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.god.gl.vaccination.R; import com.god.gl.vaccination.widget.TitleView; import com.jaeger.library.StatusBarUtil; import com.lzy.okgo.OkGo; import butterknife.ButterKnife; import pub.devrel.easypermissions.EasyPermissions; /** * @author gl * @date 2018/12/4 * @desc */ public abstract class BaseActivity extends AppCompatActivity { protected TitleView mTitleView; protected Context mContext; private String tag = ""; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getActivityViewById()); ButterKnife.bind(this); setStatusBar(); mContext = this; initView(savedInstanceState); findTitleViewId(); handleData(); setback(); } protected abstract int getActivityViewById(); protected abstract void initView(Bundle savedInstanceState); /** * 数据处理 */ protected abstract void handleData(); /** * 获取头部标题栏 */ protected void findTitleViewId() { if (null != findViewById(R.id.titleView)) { mTitleView = findViewById(R.id.titleView); } } protected void setStatusBar() { StatusBarUtil.setColor(this, getResources().getColor(R.color.blue), 80); } /** * 头部返回键处理 */ private void setback() { if (null != mTitleView) { mTitleView.setBackListener(new TitleView.BackListener() { @Override public void backClick() { finish(); } }); } } public String getTAG() { try { if ("".equals(tag)) { tag = getClass().getSimpleName(); } } catch (Exception e) { e.printStackTrace(); } return tag; } @Override protected void onDestroy() { super.onDestroy(); OkGo.getInstance().cancelTag(getTAG()); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } }
package itchihuahua.mitec.com.mitec; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CalifListAdapter extends ArrayAdapter<String> { Activity context; String[] itemasig; int[] itemcalif; public CalifListAdapter(Activity context, String[] itemasig, int[] itemcalif) { super(context, R.layout.calif_modelo, itemasig); // TODO Auto-generated constructor stub this.context=context; this.itemasig=itemasig; this.itemcalif=itemcalif; } public View getView(int posicion, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView = inflater.inflate(R.layout.calif_modelo, null, true); TextView txtV_a1=(TextView)rowView.findViewById(R.id.txtV_a1); TextView txtV_a2=(TextView)rowView.findViewById(R.id.txtV_a2); TextView txtV_asignatura = (TextView) rowView.findViewById(R.id.txtV_materia); TextView txtV_calif = (TextView) rowView.findViewById(R.id.txtV_calif); txtV_a1.setText("Asignatura"); txtV_a2.setText("Calificación"); txtV_asignatura.setText(itemasig[posicion]); txtV_calif.setText(String.valueOf(itemcalif[posicion])); return rowView; } }
package com.esum.web.ebms.ebmsroutingpath.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import com.esum.appetizer.dao.AbstractDao; import com.esum.appetizer.util.PageUtil; import com.esum.web.ebms.ebmsroutingpath.vo.EbmsRoutingPath; public class EbmsRoutingPathDao extends AbstractDao { public List<EbmsRoutingPath> selectList(String routingPathId, PageUtil pageUtil) { Map<String, Object> param = new HashMap<String, Object>(); param.put("routingPathId", escape(routingPathId, PercentAdd.BOTH)); // escape for LIKE param.put("startRow", pageUtil.getStartRow()); param.put("endRow", pageUtil.getEndRow()); return getSqlSession().selectList("ebmsRoutingPath.selectPageList", param); } public int countList(String routingPathId) { Map<String, Object> param = new HashMap<String, Object>(); param.put("routingPathId", escape(routingPathId, PercentAdd.BOTH)); // escape for LIKE return (Integer)getSqlSession().selectOne("ebmsRoutingPath.countList", param); } public EbmsRoutingPath select(String routingPathId) { Map<String, Object> param = new HashMap<String, Object>(); param.put("routingPathId", routingPathId); return getSqlSession().selectOne("ebmsRoutingPath.select", param); } public int insert(EbmsRoutingPath vo) { return getSqlSession().insert("ebmsRoutingPath.insert", vo); } public int update(EbmsRoutingPath vo) { return getSqlSession().update("ebmsRoutingPath.update", vo); } public int delete(String routingPathId) { return getSqlSession().delete("ebmsRoutingPath.delete", routingPathId); } }
package com.bestseller.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class BackPageController { @RequestMapping("/back/{page}") public String showBackPage(@PathVariable("page") String page){ return page; } @RequestMapping("/back/frame/{page}") public String showBackPage2(@PathVariable("page") String page){ return "frame/"+page; } }
package com.github.fly_spring.demo06.prepost; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * 配置类 * initMethod和destroyMethod指定BeanWayService类的init和destroy方法在构造之后、bean销毁之前执行 * @author william * */ @Configuration @ComponentScan("com.github.fly_spring.demo06.prepost") public class PrePostConfig { @Bean(initMethod = "init", destroyMethod = "destroy") BeanWayService beanWayService() { return new BeanWayService(); } @Bean JSR250WayService jsr250WayService() { return new JSR250WayService(); } }
import com.github.theholywaffle.lolchatapi.*; import com.github.theholywaffle.lolchatapi.listeners.ChatListener; import com.github.theholywaffle.lolchatapi.listeners.FriendListener; import com.github.theholywaffle.lolchatapi.listeners.FriendRequestListener; import com.github.theholywaffle.lolchatapi.riotapi.RateLimit; import com.github.theholywaffle.lolchatapi.riotapi.RiotApiKey; import com.github.theholywaffle.lolchatapi.wrapper.Friend; import java.io.Console; import java.util.*; import java.text.SimpleDateFormat; import java.util.logging.LogManager; public class Listeners { private static String lastSentTo = ""; private static String lastGotReplyFrom = ""; public static void main(String[] args) { //Disable presence warnings LogManager.getLogManager().reset(); //Disable xmlproperty warnings System.err.close(); String pwd; Scanner input = new Scanner(System.in); System.out.print("Username: "); String usr = input.next(); try{ Console console = System.console(); pwd = String.valueOf(console.readPassword("Password: ")); }catch(Exception ex){ System.out.print("Password: "); pwd = input.next(); } System.out.print("\033[H\033[2J"); System.out.flush(); final LolChat api = new LolChat(ChatServer.NA2, FriendRequestPolicy.ACCEPT_ALL, new RiotApiKey("RIOT-API-KEY", RateLimit.DEFAULT)); boolean autoReplyFlag = false; new Listeners(api); Queue<String> msgQ = new ArrayDeque<>(); ChatListener noAutoReplyChatListener = new ChatListener() { public void onMessage(Friend friend, String message) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + friend.getName() + " -> [MSG]: " + message); lastGotReplyFrom = friend.getName(); } }; ChatListener autoReplyChatListener = new ChatListener() { public void onMessage(Friend friend, String message) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + friend.getName() + " -> [MSG]: " + message); String reMsg = "Hello " + friend.getName() + ", I am currently away and will get back to you shortly."; System.out.println("[" + timeStamp + "] " + "[MSG] -> " + friend.getName() + ": " + reMsg); friend.sendMessage(reMsg); lastGotReplyFrom = friend.getName(); lastSentTo = friend.getName(); msgQ.add("[" + timeStamp + "] " + friend.getName() + " -> [MSG]: " + message); } }; api.addChatListener(noAutoReplyChatListener); int option = -1; if (api.login(usr, pwd)) { System.out.println("Initialized Successfully..."); pwd = ""; } else { System.out.println("Failed to initialize..."); option = 0; } while (option != 0) { System.out.println("----------------------------"); System.out.println("Sychan LoL Utilities [AR: " + autoReplyFlag + "]\n"); System.out.print("Options:\n(1)getOnlineFriends\n(2)sendMessage\n(3)reply\n(4)sendToLastSent\n(5)autoReply\n(6)queryUser\n(7)getState\n(8)setStatus\n(9)setStatusOptions\n(0)quit\n"); System.out.print("----------------------------\n> "); option = input.nextInt(); switch (option) { case 1: getFriendsList(api); break; case 2: System.out.print("Recipient: "); String recipient = input.next(); System.out.print("Message: "); String message = input.next(); System.out.print("Number of times: "); Integer no = input.nextInt(); sendMessage(api, recipient, message, no); break; case 3: String lastGotReplyFromTemp = lastGotReplyFrom; if(lastGotReplyFromTemp.equals("")){ System.out.println("N/A"); break; } System.out.print("Recipient: " + lastGotReplyFromTemp); System.out.print("\nMessage: "); String message1 = input.next(); sendToLastGotReplyFrom(api, lastGotReplyFromTemp, message1); break; case 4: String lastGotSentToTemp = lastSentTo; if(lastGotSentToTemp.equals("")){ System.out.println("N/A"); break; } System.out.print("Recipient: " + lastGotSentToTemp); System.out.print("\nMessage: "); String message2 = input.next(); sendToLastSentTo(api, lastGotSentToTemp, message2); break; case 5: autoReplyFlag = !autoReplyFlag; if (autoReplyFlag) { api.addChatListener(autoReplyChatListener); api.removeChatListener(noAutoReplyChatListener); api.disconnect(); api.login(usr, pwd); } else { if(msgQ.size()>0){ System.out.println("Retrieving auto replied to messages..."); while(msgQ.poll()!=null){ System.out.println(msgQ.poll()); } }else{ System.out.println("No messages auto replied to"); } api.removeChatListener(autoReplyChatListener); api.addChatListener(noAutoReplyChatListener); api.disconnect(); api.login(usr, pwd); } break; case 6: System.out.print("User: "); String userToQuery = input.next(); queryUser(api, userToQuery); break; case 7: getState(api); break; case 8: System.out.print("offline/online/away: "); String status = input.next(); setStatus(api, status); break; case 9: setStatusOptions(api); break; case 0: System.exit(0); } } } private static void queryUser(LolChat api, String user) { Friend userf = api.getFriendByName(user); LolStatus status = userf.getStatus(); System.out.println("\n------------------------------------"); System.out.println("'" + user + "' LOG REPORT\n"); System.out.println("Timestamp: " + status.getTimestamp()); System.out.println("Level: " + status.getLevel()); System.out.println("Current Tier: " + status.getRankedLeagueTier()); System.out.println("Current Division: " + status.getRankedLeagueDivision()); System.out.println("Status Message: " + status.getStatusMessage()); System.out.println("Current GameStatus: " + status.getGameStatus()); System.out.println("Normal Wins: " + status.getNormalWins()); System.out.println("Normal Leaves: " + status.getNormalLeaves()); System.out.println("Ranked Wins: " + status.getRankedWins()); System.out.println("Ranked League Name: " + status.getRankedLeagueName()); System.out.println("Ranked League Queue: " + status.getRankedLeagueQueue()); System.out.println("Ranked Solo Restricted: " + status.getRankedSoloRestricted()); System.out.println("Game Queue Type: " + status.getGameQueueType()); System.out.println("Spectating: " + status.getSpectatedGameId()); System.out.println("Spectate Game ID: " + status.getSpectatedGameId()); System.out.println("Tier: " + status.getTier()); System.out.println("Profile Icon ID: " + status.getProfileIconId()); System.out.println("Dominion Wins: " + status.getDominionWins()); System.out.println("Dominion Leaves: " + status.getDominionLeaves()); System.out.println("Featured Game Data: " + status.getFeaturedGameData()); System.out.println("Mobile: " + status.getMobile()); System.out.println("Skin: " + status.getSkin()); System.out.println("------------------------------------\n"); } private static void getFriendsList(LolChat api) { for (final Friend f : api.getOnlineFriends()) { System.out.println("[" + f.getGroup() + "]: " + f.getName()); } } private static void getState(LolChat api){ System.out.println("Loaded: " + api.isLoaded()); System.out.println("Connected: " + api.isConnected()); System.out.println("Online: " + api.isOnline()); } private static void setStatus(LolChat api, String status) { switch (status) { case "offline": api.setOffline(); break; case "online": api.setOnline(); case "away": api.setChatMode(ChatMode.AWAY); } } private static void setStatusOptions(LolChat api) { LolStatus newStatus = new LolStatus(); newStatus.setLevel(1); newStatus.setRankedLeagueQueue(LolStatus.Queue.RANKED_SOLO_5x5); newStatus.setRankedLeagueTier(LolStatus.Tier.CHALLENGER); newStatus.setRankedLeagueName("Sone"); newStatus.setGameQueueType(LolStatus.Queue.RANKED_TEAM_5x5); api.setStatus(newStatus); } private static void sendMessage(LolChat api, String username, String message, int num) { Friend f; f = api.getFriendByName(username); if (f != null && f.isOnline()) { for (int i = 0; i < num; i++) { f.sendMessage(message); } String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "[MSG] -> " + username + "(" + num + "): " + message); lastSentTo = username; } } private static void sendToLastGotReplyFrom(LolChat api, String lastGotReplyFromTemp, String message) { Friend f; f = api.getFriendByName(lastGotReplyFromTemp); if (f != null && f.isOnline()) { f.sendMessage(message); String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "[MSG] -> " + lastGotReplyFromTemp + ": " + message); lastSentTo = lastGotReplyFromTemp; } } private static void sendToLastSentTo(LolChat api, String lastSentToTemp, String message) { Friend f; f = api.getFriendByName(lastSentToTemp); if (f != null && f.isOnline()) { f.sendMessage(message); String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "[MSG] -> " + lastSentToTemp + ": " + message); lastSentTo = lastSentToTemp; } } private Listeners(LolChat api) { /** First add or set all listeners BEFORE logging in! */ api.addFriendListener(new FriendListener() { public void onFriendAvailable(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "STATUS>AVAILABLE: " + friend.getName()); } public void onFriendAway(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "STATUS>AWAY: " + friend.getName()); } public void onFriendBusy(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "STATUS>BUSY: " + friend.getName()); } public void onFriendJoin(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "[LOG-I] " + friend.getName()); } public void onFriendLeave(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "[LOG-O] " + friend.getName()); } public void onFriendStatusChange(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + friend.getName() + "STATUS \u0394]: " + friend.getStatus().getGameStatus()); } public void onNewFriend(Friend friend) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "New friend: " + friend.getUserId()); } public void onRemoveFriend(String userId, String name) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + "Friend removed: " + userId + " " + name); } }); api.setFriendRequestListener(new FriendRequestListener() { public boolean onFriendRequest(String userId, String name) { String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime()); System.out.println("[" + timeStamp + "] " + userId + " wants to add me. Yes or no?"); return true; } }); } }
package com.example.landrouter.controller; import com.example.landrouter.model.LandRouteResponse; import com.example.landrouter.service.LandRouteService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController @RequiredArgsConstructor public class LandRouteController { private final LandRouteService landRouteService; @GetMapping("/routing/{origin}/{destination}") public LandRouteResponse getRouteBetweenLands(@PathVariable("origin") String origin, @PathVariable("destination") String destination) { return new LandRouteResponse(landRouteService.shortestPath(origin, destination)); } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.com) * * 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 com.forgerock.sapi.gateway.ob.uk.common.datamodel.account; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.stream.Stream; public enum FRBalanceType { CLOSINGAVAILABLE("ClosingAvailable"), CLOSINGBOOKED("ClosingBooked"), CLOSINGCLEARED("ClosingCleared"), EXPECTED("Expected"), FORWARDAVAILABLE("ForwardAvailable"), INFORMATION("Information"), INTERIMAVAILABLE("InterimAvailable"), INTERIMBOOKED("InterimBooked"), INTERIMCLEARED("InterimCleared"), OPENINGAVAILABLE("OpeningAvailable"), OPENINGBOOKED("OpeningBooked"), OPENINGCLEARED("OpeningCleared"), PREVIOUSLYCLOSEDBOOKED("PreviouslyClosedBooked"); private String value; FRBalanceType(String value) { this.value = value; } public String getValue() { return value; } @JsonValue public String toString() { return value; } @JsonCreator public static FRBalanceType fromValue(String value) { return Stream.of(values()) .filter(type -> type.getValue().equals(value)) .findFirst() .orElse(null); } }
package com.edasaki.rpg.mobs; import org.bukkit.inventory.ItemStack; import com.edasaki.rpg.items.RPGItem; public final class MobDrop { public final RPGItem item; public final int minAmount; public final int maxAmount; public final double chance; public ItemStack generate() { return item.generate(); } public boolean roll() { return Math.random() < chance; } public MobDrop(RPGItem item, int minAmount, int maxAmount, double chance) { this.item = item; this.minAmount = minAmount; this.maxAmount = maxAmount; this.chance = chance; } }
/* * Classe per guardar cada element * de la web amb la informació del COVID */ package at.project.covid; import java.sql.Timestamp; public class CovidInfo { private String nom; private String codi; private Timestamp data_ini; private Timestamp data_fi; private String residencia; private float iepg_confirmat; private float r0_confirmat_m; private float taxa_casos_confirmat; private int casos_confirmat; private float taxa_pcr; private int pcr; private float perc_pcr_positives; private int ingressos_total; private int ingressos_critic; private int exitus; public CovidInfo() { super(); } public CovidInfo(String nom, String codi, Timestamp data_ini, Timestamp data_fi, String residencia, float iepg_confirmat, float r0_confirmat_m, float taxa_casos_confirmat, int casos_confirmat, float taxa_pcr, int pcr, float perc_pcr_positives, int ingressos_total, int ingressos_critic, int exitus) { super(); this.nom = nom; this.codi = codi; this.data_ini = data_ini; this.data_fi = data_fi; this.residencia = residencia; this.iepg_confirmat = iepg_confirmat; this.r0_confirmat_m = r0_confirmat_m; this.taxa_casos_confirmat = taxa_casos_confirmat; this.casos_confirmat = casos_confirmat; this.taxa_pcr = taxa_pcr; this.pcr = pcr; this.perc_pcr_positives = perc_pcr_positives; this.ingressos_total = ingressos_total; this.ingressos_critic = ingressos_critic; this.exitus = exitus; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getCodi() { return codi; } public void setCodi(String codi) { this.codi = codi; } public Timestamp getData_ini() { return data_ini; } public void setData_ini(Timestamp data_ini) { this.data_ini = data_ini; } public Timestamp getData_fi() { return data_fi; } public void setData_fi(Timestamp data_fi) { this.data_fi = data_fi; } public String getResidencia() { return residencia; } public void setResidencia(String residencia) { this.residencia = residencia; } public float getIepg_confirmat() { return iepg_confirmat; } public void setIepg_confirmat(float iepg_confirmat) { this.iepg_confirmat = iepg_confirmat; } public float getR0_confirmat_m() { return r0_confirmat_m; } public void setR0_confirmat_m(float r0_confirmat_m) { this.r0_confirmat_m = r0_confirmat_m; } public float getTaxa_casos_confirmat() { return taxa_casos_confirmat; } public void setTaxa_casos_confirmat(float taxa_casos_confirmat) { this.taxa_casos_confirmat = taxa_casos_confirmat; } public int getCasos_confirmat() { return casos_confirmat; } public void setCasos_confirmat(int casos_confirmat) { this.casos_confirmat = casos_confirmat; } public float getTaxa_pcr() { return taxa_pcr; } public void setTaxa_pcr(float taxa_pcr) { this.taxa_pcr = taxa_pcr; } public int getPcr() { return pcr; } public void setPcr(int pcr) { this.pcr = pcr; } public float getPerc_pcr_positives() { return perc_pcr_positives; } public void setPerc_pcr_positives(float perc_pcr_positives) { this.perc_pcr_positives = perc_pcr_positives; } public int getIngressos_total() { return ingressos_total; } public void setIngressos_total(int ingressos_total) { this.ingressos_total = ingressos_total; } public int getIngressos_critic() { return ingressos_critic; } public void setIngressos_critic(int ingressos_critic) { this.ingressos_critic = ingressos_critic; } public int getExitus() { return exitus; } public void setExitus(int exitus) { this.exitus = exitus; } /* * Mètode toString modificat per adaptar el format del text a la pàgina web */ @Override public String toString() { return "&emsp;<b>Comarca: " + nom + "</b><br>&emsp;&emsp;data inici: " + data_ini + ",&emsp; data final: " + data_fi + "<br>&emsp;&emsp;Residencia: " + residencia + ", &emsp;Risc de rebrot: " + iepg_confirmat + ", &emsp;r0 confirmat: " + r0_confirmat_m + ", &emsp;taxa casos confirmats: " + taxa_casos_confirmat + ", &emsp;casos confirmats: " + casos_confirmat + "<br>&emsp;&emsp;taxa PCR: " + taxa_pcr + ", &emsp;número PCR realitzades: " + pcr + ", &emsp;Percentatge PCR positives: " + perc_pcr_positives + "<br>&emsp;&emsp;Ingressos totals = " + ingressos_total + ", &emsp;Ingressos crítics: " + ingressos_critic + ", &emsp;Defuncions=" + exitus + "<br><br>"; } /* * Mètode toString modificat per adaptar el format del text al * format d'un missatge de Telegram */ public String telegramInfo() { return "CovidInfo\n[nom=" + nom + ",\n data_ini=" + data_ini + ",\n data_fi=" + data_fi + ",\n residencia=" + residencia + ",\n iepg_confirmat=" + iepg_confirmat + ",\n r0_confirmat_m=" + r0_confirmat_m + ",\n taxa_casos_confirmat=" + taxa_casos_confirmat + ",\n casos_confirmat=" + casos_confirmat + ",\n taxa_pcr=" + taxa_pcr + ",\n pcr=" + pcr + ",\n perc_pcr_positives=" + perc_pcr_positives + ",\n ingressos_total=" + ingressos_total + ",\n ingressos_critic=" + ingressos_critic + ",\n defuncions=" + exitus + "]"; } }
package com.zhicai.byteera.activity.traincamp.module; import com.zhicai.byteera.activity.traincamp.presenter.DayTaskPresenter; import dagger.internal.Factory; import javax.annotation.Generated; @Generated("dagger.internal.codegen.ComponentProcessor") public final class DayTaskModule_ProvideTaskPresenterFactory implements Factory<DayTaskPresenter> { private final DayTaskModule module; public DayTaskModule_ProvideTaskPresenterFactory(DayTaskModule module) { assert module != null; this.module = module; } @Override public DayTaskPresenter get() { DayTaskPresenter provided = module.provideTaskPresenter(); if (provided == null) { throw new NullPointerException("Cannot return null from a non-@Nullable @Provides method"); } return provided; } public static Factory<DayTaskPresenter> create(DayTaskModule module) { return new DayTaskModule_ProvideTaskPresenterFactory(module); } }
package se.ade.autoproxywrapper.gui.controller; import static javafx.stage.StageStyle.DECORATED; import java.io.IOException; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import se.ade.autoproxywrapper.Main; import se.ade.autoproxywrapper.events.EventBus; import se.ade.autoproxywrapper.events.ShutDownEvent; public class MenuController { private Main main; private AboutController aboutController; @FXML public void initialize() { aboutController = new AboutController(); } @FXML public void menuProperties() throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getClassLoader().getResource("view/properties.fxml")); BorderPane pane = loader.load(); Stage stage = new Stage(DECORATED); stage.initOwner(main.getPrimaryStage()); stage.setResizable(false); stage.setTitle("Properties"); Scene scene = new Scene(pane, 500, 300); stage.setScene(scene); stage.show(); loader.<PropertiesController>getController().setWindow(stage); } @FXML public void menuProxies() throws IOException { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getClassLoader().getResource("view/proxies.fxml")); VBox pane = loader.load(); Stage stage = new Stage(DECORATED); stage.initOwner(main.getPrimaryStage()); stage.setResizable(false); stage.setTitle("Proxies"); Scene scene = new Scene(pane, 500, 300); stage.setScene(scene); stage.show(); loader.<ProxiesController>getController().setWindow(stage); } catch (IOException e) { e.printStackTrace(); } } @FXML public void menuBlockedHosts() throws IOException { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getClassLoader().getResource("view/hostlist.fxml")); VBox pane = loader.load(); Stage stage = new Stage(DECORATED); stage.initOwner(main.getPrimaryStage()); stage.setResizable(false); stage.setTitle("Blocked hosts"); Scene scene = new Scene(pane, 500, 300); stage.setScene(scene); stage.show(); loader.<HostListController>getController().setWindow(stage).editBlockedHosts(); } catch (IOException e) { e.printStackTrace(); } } @FXML public void menuDirectModeHosts() throws IOException { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getClassLoader().getResource("view/hostlist.fxml")); VBox pane = loader.load(); Stage stage = new Stage(DECORATED); stage.initOwner(main.getPrimaryStage()); stage.setResizable(false); stage.setTitle("Direct mode hosts"); Scene scene = new Scene(pane, 500, 300); stage.setScene(scene); stage.show(); loader.<HostListController>getController().setWindow(stage).editDirectModeHosts(); } catch (IOException e) { e.printStackTrace(); } } @FXML public void menuLoopbacks() throws IOException { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getClassLoader().getResource("view/loopbacks.fxml")); VBox pane = loader.load(); Stage stage = new Stage(DECORATED); stage.initOwner(main.getPrimaryStage()); stage.setResizable(false); stage.setTitle("Loopback configurations"); Scene scene = new Scene(pane, 500, 300); stage.setScene(scene); stage.show(); loader.<LoopbackController>getController().setWindow(stage); } catch (IOException e) { e.printStackTrace(); } } @FXML public void menuClose() { EventBus.get().post(new ShutDownEvent()); } @FXML public void menuAbout() throws Exception { aboutController.show(); } public void setMain(Main main) { this.main = main; } }
package download.util; import java.io.InputStream; import java.io.RandomAccessFile; import java.io.Serializable; import java.net.HttpURLConnection; import java.net.URL; import org.apache.log4j.Logger; public class DownLoadTask implements Runnable, Serializable { private static final long serialVersionUID = 4762342796221839508L; private static final Logger LOG = Logger.getLogger(DownLoadTask.class); private int threadId;// 线程编号 private long beginLocation;// 开始的字节数的位置 private long endLocation;// 结束的字节位置 @SuppressWarnings("unused") private long downloadContentLength;// 当前线程下载的长度 private String downFilePath;// 文件下载保存路径 private URL url; public DownLoadTask(int threadId, long beginLocation, long endLocation, String downFilePath, URL url) { this.threadId = threadId; this.beginLocation = beginLocation; this.endLocation = endLocation; this.downFilePath = downFilePath; this.url = url; } /** * 启动线程 */ @Override public void run() { LOG.info(" --------------------> 启动了" + threadId + "个线程"); RandomAccessFile raf = null; try { raf = new RandomAccessFile(downFilePath, "rwd"); raf.seek(beginLocation); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Range", "bytes=" + beginLocation + "-" + endLocation); // 获取下载数据流 InputStream in = con.getInputStream(); byte[] by = new byte[1024 * 1024]; int len; while ((len = in.read(by)) != -1) { downloadContentLength += len; raf.write(by, 0, len); } raf.close(); LOG.info(" --------------------> 第" + threadId + "个线程下载完成..,下载从" + beginLocation + "到" + endLocation); } catch (Exception e) { LOG.info(e.getStackTrace()); } finally { if (null != raf) { try { raf.close(); } catch (Exception e) { LOG.info(e.getStackTrace()); } } } } }
package com.auro.scholr.teacher.presentation.viewmodel; import android.content.Context; import android.view.View; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.auro.scholr.R; import com.auro.scholr.core.common.AppConstant; import com.auro.scholr.core.common.CommonCallBackListner; import com.auro.scholr.core.common.Status; import com.auro.scholr.databinding.ClassItemLayoutBinding; import com.auro.scholr.teacher.data.model.request.SelectClassesSubject; import com.auro.scholr.util.AppUtil; public class SubjectViewHolder extends RecyclerView.ViewHolder { ClassItemLayoutBinding binding; public SubjectViewHolder(@NonNull ClassItemLayoutBinding binding) { super(binding.getRoot()); this.binding = binding; } public void bindUser(SelectClassesSubject model, int position, Context mcontext, CommonCallBackListner commonCallBackListner, int adapter) { binding.txtClass.setText(model.getText()); binding.buttonClick.setBackground(model.isSelected() ? ContextCompat.getDrawable(mcontext, R.drawable.class_bule_border_background) : ContextCompat.getDrawable(mcontext, R.drawable.class_borader_background)); binding.txtClass.setTextColor(model.isSelected() ? ContextCompat.getColor(mcontext, R.color.white) : ContextCompat.getColor(mcontext, R.color.grey_color)); binding.buttonClick.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (model.isSelected()) { model.setSelected(false); } else { model.setSelected(true); } binding.buttonClick.setBackground(model.isSelected() ? ContextCompat.getDrawable(mcontext, R.drawable.class_bule_border_background) : ContextCompat.getDrawable(mcontext, R.drawable.class_borader_background)); binding.txtClass.setTextColor(model.isSelected() ? ContextCompat.getColor(mcontext, R.color.white) : ContextCompat.getColor(mcontext, R.color.grey_color)); setClickListnerForSubject(commonCallBackListner, model, adapter); } }); } private void setClickListnerForSubject(CommonCallBackListner commonCallBackListner, SelectClassesSubject model, int subjectadapter) { if (commonCallBackListner != null) { if (subjectadapter == AppConstant.FriendsLeaderBoard.SUBJECTADAPTER) { commonCallBackListner.commonEventListner(AppUtil.getCommonClickModel(AppConstant.FriendsLeaderBoard.SUBJECTADAPTER, Status.SUBJECT_CLICK, model)); } else { commonCallBackListner.commonEventListner(AppUtil.getCommonClickModel(AppConstant.FriendsLeaderBoard.CLASSESADAPTER, Status.CLASS_CLICK, model)); } } } }
package com.model; import java.io.Serializable; public class CashPayBillItem implements Serializable{ private String id; private String cashPayBillNo; private String item; private double money; private String desc; public CashPayBillItem(String id, String cashPayBillNo, String item, double money, String desc) { super(); this.id = id; this.cashPayBillNo = cashPayBillNo; this.item = item; this.money = money; this.desc = desc; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCashPayBillNo() { return cashPayBillNo; } public void setCashPayBillNo(String cashPayBillNo) { this.cashPayBillNo = cashPayBillNo; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
/* * 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 Facade; import entity.Person; import java.io.Closeable; import java.io.IOException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author RolfMoikjær */ public class Logic implements Closeable { private final EntityManager entityManager; public Logic(EntityManagerFactory factory) { this.entityManager = factory.createEntityManager(); this.entityManager.getTransaction().begin(); } public <T extends Person> T add(T person) { this.entityManager.persist(person); return person; } public <T extends Person> T find(Class<T> type, int id) { return this.entityManager.find(type, new Long(id)); } @Override public void close() { this.entityManager.getTransaction().commit(); this.entityManager.close(); } }
package com.company; public class Main { public static void main(String[] args) { } //problem 1 public boolean sleepIn(boolean weekday, boolean vacation) { if (!weekday || vacation){ return true; } else{ return false; } } //problem 2 public int sumDouble(int a, int b) { int sum = a + b; if(a == b){ return (sum * 2); } else{ return sum; } } //problem 3 public int close10(int a, int b) { int aAbs = Math.abs(a - 10); int bAbs = Math.abs(b - 10); if(aAbs > bAbs){ return b; } else if(bAbs > aAbs){ return a; } else{ return 0; } } //bonus 1 public String frontBack(String str) { if (str.length() > 0) { char[] charArray = str.toCharArray(); char firstChar = charArray[0]; charArray[0] = charArray[charArray.length - 1]; charArray[charArray.length - 1] = firstChar; String newString = new String(charArray); return newString; } else { String emptyString = ""; return emptyString; } } //bonus 2 public String notString(String str) { String notStr = "not " + str; if (str.startsWith("not")) { return str; } else { return notStr; } } }
package io.magicthegathering.javasdk.filter; import io.magicthegathering.javasdk.filter.domain.Color; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.*; /** * Tests the ColorFilter * * @author Timon Link - timon.link@gmail.com */ @RunWith(JUnit4.class) public class ColorFilterTest { @Test public void testBlue() { assertEquals("colors=blue", filterAndGetExpression(Color.BLUE)); } @Test public void testRed() { assertEquals("colors=red", filterAndGetExpression(Color.RED)); } @Test public void testBlack() { assertEquals("colors=black", filterAndGetExpression(Color.BLACK)); } @Test public void testWhite() { assertEquals("colors=white", filterAndGetExpression(Color.WHITE)); } @Test public void testGreen() { assertEquals("colors=green", filterAndGetExpression(Color.GREEN)); } private String filterAndGetExpression(Color color) { return new ColorFilter(new Filter(), color).expression; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.implDao; import com.dao.IDao; import com.entity.Cliente; import com.entity.Notificacion; import com.entity.Tienda; /** * * @author DAC-PC */ public interface INotificacion extends IDao<Notificacion, Long>{ long ObtenerUltimo(Tienda c); long Obtenerultimoclien(Cliente c); }
import static org.junit.Assert.*; import org.junit.Test; public class EventBarrierTest { @Test public void testArrive() throws InterruptedException { EventBarrier e = new EventBarrier(); MyThread t1 = new MyThread(e, false); MyThread t3 = new MyThread(e, true); t1.start(); Thread.sleep(100); assertTrue(e.waiters() == 2); t3.start(); } }
package ru.gurps.generator.desktop.models.characters; import ru.gurps.generator.desktop.config.Model; public class CharactersCultura extends Model { public Integer id; public Integer characterId; public Integer culturaId; public Integer cost = 0; public CharactersCultura() { } public CharactersCultura(Integer characterId, Integer culturaId, Integer cost) { this.characterId = characterId; this.culturaId = culturaId; this.cost = cost; } }
package com.springboot.racemanage.service.serviceImpl; import com.springboot.racemanage.service.LogService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; import java.util.Map; import com.springboot.racemanage.po.Log; import com.springboot.racemanage.dao.LogDao; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class LogServiceImpl implements LogService{ @Resource private LogDao logDao; public int insert(Log pojo){ return logDao.insert(pojo); } public int insertSelective(Log pojo){ return logDao.insertSelective(pojo); } public int insertList(List<Log> pojos){ return logDao.insertList(pojos); } public int update(Log pojo){ return logDao.update(pojo); } @Override public List<Log> findByStatusAndProUuid(Integer status, String proUuid) { return logDao.findByStatusAndProUuid(status,proUuid); } @Override public List<Map> getLogAndTeamerNameByProUuid(String proUuid) { return logDao.getLogAndTeamerNameByProUuid(proUuid); } }
package com.example.hyunyoungpark.addressbookdemo; import android.content.Context; import android.net.Uri; import android.support.v4.app.Fragment; import android.database.Cursor; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.hyunyoungpark.addressbookdemo.Data.DatabaseDescription; public class ContactsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { //from here you should goto MainActivity and load //detailFragment with selected ID // @Override // public void onClick(Uri uri) { // contactFragmentInterface.onContactSelected(uri); // } //interface .: have only methods no implementation //Class implementing interface will have code public interface ContactFragmentInterface { void onAddContact(); void onContactSelected(Uri uri); } private ContactAdapter contactAdapter; private int contact_loader =0; //declaration not intialization public ContactFragmentInterface contactFragmentInterface; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view =inflater.inflate( R.layout.fragment_contacts, container, false ); RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); //set layoutManger recyclerView.setLayoutManager( new LinearLayoutManager( getActivity().getBaseContext() )); //set Adapter contactAdapter = new ContactAdapter(new ContactAdapter.ContactAdapterInterface() { @Override public void onClick(Uri uri) { contactFragmentInterface.onContactSelected(uri); } }); recyclerView.setAdapter(contactAdapter); recyclerView.addItemDecoration(new ItemDivider(getContext())); //Improving the performance recyclerView.setHasFixedSize(true); FloatingActionButton addButton = (FloatingActionButton) view.findViewById(R.id.addButton); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { contactFragmentInterface.onAddContact(); } }); return view; } @Override public void onAttach(Context context) { super.onAttach(context); contactFragmentInterface = (ContactFragmentInterface) context; } @Override public void onDetach() { super.onDetach(); contactFragmentInterface = null; } //Intialize the loader whenever the fragment // activity is created @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getLoaderManager().initLoader(contact_loader, null,this); } //create a loader object and start loading // the data into cursor @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader c = new CursorLoader( getActivity(), DatabaseDescription.Contact.CONTENT_URI, null, null, null, null ); return c; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { contactAdapter.notifyChange(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { contactAdapter.notifyChange(null); } }
/** * Subclass Salesman * * @author Mark Orimoloye */ public class Salesman extends Employee { private double annualSales; //contructor public Salesman(String name, double mthlySalary, double annualSales) { super(name, mthlySalary); this.annualSales = annualSales; } @Override public double annualSalary() { if (annualSales > 1000000) { annualSales = 1000000; } double smanSalary = (annualSales * 0.02) + super.annualSalary(); return smanSalary; } @Override public String toString () { String strg = super.toString() + " This Salesman also made " + annualSales +" in annual sales."; return strg; } }
package cap5exercices.example1; import java.io.IOException; public class RandomNumberGame { public static void main(String[] args) throws IOException { boolean sair = false; //variavel de controlo quebrar: do { // ciclo principal com label quebrar boolean guess = false; char c; int tentativas = 0; //gerar um numero aleatorio e armazenar em num double d = Math.random(); int num = (int) (100 * d); while (guess == false) { //ciclo interno String s = ""; System.out.println("Qual é o número?(0-100, -1 para desistir)"); while ((c = (char) System.in.read()) != 10) { s += c; s = s.substring(0, s.length() - 1); // eliminacao de lixo no final da string int n = Integer.valueOf(s).intValue(); tentativas ++; //incrementar o contador de tentativas if (n == -1) { System.out.println("Voce desistiu!"); break quebrar; } if (n == num) { guess = true; }else if (n > num) System.out.println(n + "? Não, o número é mais baixo!"); else System.out.println(n + "? Não, o número é mais alto!"); } } System.out.println("Voce adivinhou o numero em " + tentativas + "tentativas"); boolean repetir; do { System.out.println("Quer jogar de novo? [S/N]"); c = (char) System.in.read(); switch (c) { case 's': case 'S': System.out.println("Vamos jogar outra vez"); repetir = false; break; case 'n': case 'N': System.out.println("Ate a proxima..."); repetir = false; sair = true; break; default: System.out.println("A sua resposta nao e valida"); repetir = true; break; } } while (repetir == true); System.in.read(); } while (sair); } }
package net.aimeizi.service.order; import net.aimeizi.order.Order; import net.aimeizi.order.OrderService; import org.apache.thrift.TException; import org.springframework.stereotype.Service; @Service("orderService") public class OrderServiceImpl implements OrderService.Iface { @Override public String ping() throws TException { return "pong"; } @Override public Order getOrder(int orderId) throws TException { return new Order(orderId).setOrderTitle("dubbo"); } }
package com.god.gl.vaccination.main.home.activity; import android.os.Bundle; import com.god.gl.vaccination.R; import com.god.gl.vaccination.base.BaseActivity; /** * @author gl * @date 2018/12/8 * @desc */ public class ProductsDetailActivity extends BaseActivity { @Override protected int getActivityViewById() { return R.layout.activity_products_detail; } @Override protected void initView(Bundle savedInstanceState) { } @Override protected void handleData() { } }
package br.com.salon.carine.lima.repositoriessdp; import java.util.List; import java.util.Optional; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import br.com.salon.carine.lima.models.Cliente; @Repository public interface ClienteRepositorySJPA extends JpaRepository<Cliente, Integer> { @EntityGraph(value = "Cliente.endereco") Page<Cliente> findAll(Pageable pageable); @EntityGraph(value = "Cliente.endereco") Optional<Cliente> findById(Integer id); @Query("SELECT MIN(c.id) FROM Cliente c WHERE c.id > :idClienteAtual") Integer idClienteProximo (@Param("idClienteAtual") Integer idClienteAtual); @Query("SELECT MAX(c.id) FROM Cliente c WHERE c.id < :idClienteAtual") Integer idClienteAnterior (@Param("idClienteAtual") Integer idClienteAtual); @Query("SELECT MAX(c.id) FROM Cliente c") Integer idlastCliente (); @Query("SELECT MIN(c.id) FROM Cliente c") Integer idFirstCliente(); @EntityGraph(value = "Cliente.endereco") @Query("FROM Cliente c WHERE c.nome LIKE :nome%") List<Cliente> searchNomeFilter(@Param("nome") String nome); List<Cliente> findByOrderByNomeAsc(); }
import java.util.Vector; public class A4Vectortest { public static void main(String[] args) { Vector v = new Vector();//그 크기만큼 키움/add/증가 Vector v2= new Vector(3); Vector v3= new Vector(3,4); for (int i = 0; i <=10 ; i++) { v.add(i+""); v2.add(i+""); v3.add(i+""); } System.out.println(v.capacity()+","+v.size()); System.out.println(v2.capacity()+","+v2.size()); System.out.println(v3.capacity()+","+v3.size()); } }
package kompressor.huffman; import kompressor.huffman.bytearray.ByteArrayReader; import kompressor.huffman.structures.HuffmanNode; import kompressor.huffman.structures.HuffmanQueue; import kompressor.huffman.structures.HuffmanTree; public class TreeBuilder { private TreeBuilder() { } public static HuffmanTree createTreeFromUnencodedBytes(byte[] bytes) { int[] freqs = new int[256]; //talletetaan merkkien esiintymismäärät for (byte b : bytes) { freqs[Byte.toUnsignedInt(b)]++; } HuffmanQueue q = new HuffmanQueue(); HuffmanNode[] leafs = new HuffmanNode[256]; //laitetaan jonoon ja lehtitaulukkoon kaikki esiintyneet solmut for (int i = 0; i < freqs.length; i++) { if (freqs[i] > 0) { HuffmanNode n = new HuffmanNode((char) i, freqs[i]); q.add(n); leafs[i] = n; } } HuffmanTree t = null; while (q.size() > 0) { //jonosta poistetaan solmut (lehdet), joiden kirjaimia esiintyy vähiten HuffmanNode n0 = q.poll(); HuffmanNode n1 = q.poll(); if (n1 != null) { //kun löytyy kaksi solmua, ne yhdistetään uudeksi HuffmanNode nu = new HuffmanNode(null, n0.getFrequency() + n1.getFrequency()); nu.setRight(n0); n0.setParent(nu); nu.setLeft(n1); n1.setParent(nu); q.add(nu); } else { //viimeinen solmu loydetään, asetetaan puun juureksi t = new HuffmanTree(n0, leafs); } } return t; } //Rakentaa pakatun datan alussa olevasta headerista puun public static TreeBuilderReturnObject createTreeFromHeader(byte[] bytes) { ByteArrayReader br = new ByteArrayReader(bytes); HuffmanTree t = null; //kun puussa on vain yksi solmu if (br.readBit() == 1) { t = new HuffmanTree(new HuffmanNode(br.readCharacter())); return new TreeBuilderReturnObject(t, br.getLeftoverBytes()); } HuffmanNode root = buildNode(new HuffmanNode(null), br); t = new HuffmanTree(root); return new TreeBuilderReturnObject(t, br.getLeftoverBytes()); } private static HuffmanNode buildNode(HuffmanNode n, ByteArrayReader br) { //vasen lapsi if (br.readBit() == 1) n.setLeft(new HuffmanNode(br.readCharacter())); else n.setLeft(buildNode(new HuffmanNode(null), br)); //oikea lapsi if (br.readBit() == 1) n.setRight(new HuffmanNode(br.readCharacter())); else n.setRight(buildNode(new HuffmanNode(null), br)); return n; } }
package com.metoo.module.app.pojo; public class Ddu { private String status; private String time; private String location; private String details; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Ddu() { super(); // TODO Auto-generated constructor stub } public Ddu(String location, String details, String time, String status) { super(); this.location = location; this.details = details; this.time = time; this.status = status; } @Override public String toString() { return "Ddu [location=" + location + ", details=" + details + ", time=" + time + ", status=" + status + "]"; } }
package library.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import library.model.Faculties; import library.model.Students; import library.utils.HibernateUtil; public class StudentsDaoImpl implements StudentsDao{ public static SessionFactory factory = HibernateUtil.getSessionFactory(); public void addStudent(Students student) { Session session = factory.openSession(); session.save(student); session.beginTransaction().commit(); session.close(); } public List<Students> listAllStudents() { Session session = factory.openSession(); Query query = (Query)session.createQuery("from Students"); List<Students> students = query.list(); session.close(); return students; } public void deleteStudent(int studentId) { Session session = factory.openSession(); Students student = session.load(Students.class, studentId); session.delete(student); session.beginTransaction().commit(); session.close(); } public Students updateStudent(Students student) { Session session = factory.openSession(); session.update(student); session.beginTransaction().commit(); session.close(); return student; } public Students getStudent(int studentId) { Session session = factory.openSession(); Students student = session.get(Students.class, studentId); session.close(); return student; } }
package com.nfet.icare.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.nfet.icare.pojo.Staff; import com.nfet.icare.service.StaffServiceImpl; import com.nfet.icare.util.GlobalConstants; /** * 员工后台登录 * 1、员工登录 * */ @Controller @RequestMapping("/mgr") public class Mgr_LoginController { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private StaffServiceImpl staffServiceImpl; //员工登录 @RequestMapping("/login") @ResponseBody public Map<String, Object> login(@RequestParam(value="staffNo",required=true) String staffNo, @RequestParam(value="password",required=true) String password, HttpServletRequest request){ Map<String, Object> loginMap = new HashMap<>(); HttpSession session = request.getSession(); Staff staff = staffServiceImpl.queryStaff(staffNo); logger.info("query staff of " + staffNo); if (staff == null) { //员工不存在 logger.info("the staff is not exist"); loginMap.put("errorCode", GlobalConstants.ERROR_CODE_FAIL); loginMap.put("desc", "工号未入库!"); } else if (staff.getPassword().equals(password)) { //密码一致 logger.info("the password is correct"); session.setAttribute("staff", staff); loginMap.put("errorCode", GlobalConstants.ERROR_CODE_SUCCESS); loginMap.put("roleId", staff.getRole().getRoleId()); } else { //密码不一致 logger.info("the password is uncorrect"); loginMap.put("errorCode", GlobalConstants.ERROR_CODE_FAIL); loginMap.put("desc", "密码不正确!"); } return loginMap; } }
/* $Id$ Copyright (C) 2002-2005 Sebastien Vauclair This file is part of Extensible Java Profiler. Extensible Java Profiler is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Extensible Java Profiler is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Extensible Java Profiler; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.ejp.tools.formatonsave.core.cleaner; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; class PreserveActiveEditors extends AbstractCleanerWrapper { private List l; protected void doPreClean() { l = getActiveEditors(); } protected void doPostClean() { for (Iterator iter = l.iterator(); iter.hasNext();) { PreserveActiveEditors.PageState editorState = (PreserveActiveEditors.PageState) iter .next(); logDebug("activating " + editorState.editor + " in " + editorState.page); editorState.page.activate(editorState.editor); } } /** * @return a {@link java.util.List list} of {@link PageState} elements */ private List getActiveEditors() { List list = new ArrayList(); IWorkbenchWindow[] windows = PlatformUI.getWorkbench() .getWorkbenchWindows(); for (int i = 0; i < windows.length; i++) { IWorkbenchWindow window = windows[i]; IWorkbenchPage[] pages = window.getPages(); for (int j = 0; j < pages.length; j++) { IWorkbenchPage page = pages[j]; IEditorPart activeEditor = page.getActiveEditor(); list.add(new PageState(page, activeEditor)); } } return list; } private static class PageState { public final IWorkbenchPage page; public final IEditorPart editor; public PageState(IWorkbenchPage _page, IEditorPart _editor) { page = _page; editor = _editor; } } }
/* * 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 crawlers.publishers.telaNon; import crawlers.FlexNewsCrawler; import crawlers.Logos; import crawlers.publishers.exceptions.ArticlesNotFoundException; import db.news.NewsSource; import db.news.Tag; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; /** * * @author zua */ public class TelaNonCrawler extends FlexNewsCrawler { public TelaNonCrawler() { } @Override public void crawl() { try { crawlWebsite(getMySource().getUrl(), getMySource()); } catch (Exception e) { getLogger().error(String.format("Exception thrown %s", e.getMessage())); } } @Override public NewsSource getMySource() { NewsSource source = new NewsSource(); source.setCategory(new Tag("geral")); source.setCountry("ST"); source.setDescription(""); source.setLanguage("pt"); source.setSourceId("tela-non"); source.setLogoUrl(Logos.getLogo(source.getSourceId())); source.setName("Téla Nón"); source.setUrl("https://www.telanon.info/"); source.setLogoUrl(Logos.getLogo("tela-non")); return source; } @Override public Elements getArticles(Document document) throws crawlers.publishers.exceptions.ArticlesNotFoundException { if (document == null) { throw new IllegalArgumentException("Document cannot be null."); } Elements articles = document.select("body div.blog-item-holder div.blog-content-wrapper"); if (!articles.isEmpty()) { return articles; } throw new ArticlesNotFoundException(); } @Override protected String getUrlValue(Element article) { if (article == null) { throw new IllegalArgumentException("Article cannot be null"); } Elements urls = article.select("div > a"); if (!urls.isEmpty() && !urls.attr("href").isEmpty()) { return urls.attr("href"); } return null; } @Override protected String getTitleValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null."); } Elements titles = document.select("body h1 a"); if (!titles.isEmpty() && titles.first() != null && !titles.first().text().isEmpty()) { String title = titles.first().text(); return title; } return null; } @Override protected String getImageUrlValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null."); } Elements images = document.select("body div.gdl-blog-full > div.blog-content > div.blog-media-wrapper.gdl-image > a > img"); if (!images.isEmpty() && !images.attr("src").isEmpty()) { String image = images.attr("src"); return image; } return null; } @Override protected String getContentValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null."); } Elements contents = document.select("body div.gdl-blog-full > div.blog-content > p"); if (!contents.isEmpty() && contents.first() != null && !contents.first().text().isEmpty()) { String content = contents.first().text(); return content; } return null; } @Override protected String getAuthorsValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null."); } return getMySource().getName(); } @Override protected String getTimeValue(Document document) { if (document == null) { throw new IllegalArgumentException("Document cannot be null."); } Elements paragraphs = document.select("body div.blog-date > a"); if (!paragraphs.isEmpty() && paragraphs.first() != null && !paragraphs.first().text().isEmpty()) { String time = paragraphs.first().text(); return time; } return null; } }
package com.xp.springboot.dto; import java.util.ArrayList; import java.util.List; import com.xp.springboot.entities.Address; public class EmployeeDTO { private int empId; private String empName; private int empSalary; private int age; List<Address> addList=new ArrayList<>(); public EmployeeDTO() { super(); } public EmployeeDTO(int empId, String empName, int empSalary, int age, List<Address> addList) { super(); this.empId = empId; this.empName = empName; this.empSalary = empSalary; this.age = age; this.addList = addList; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public int getEmpSalary() { return empSalary; } public void setEmpSalary(int empSalary) { this.empSalary = empSalary; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List<Address> getAddList() { return addList; } public void setAddList(List<Address> addList) { this.addList = addList; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } @Override public String toString() { return "EmployeeDTO [empName=" + empName + ", empSalary=" + empSalary + ", age=" + age + ", addList=" + addList + "]"; } }
package com.javarush.test.level05.lesson05.task04; /* Create three objects of Cat type Create three objects of type Cat in the method main and fill them with data. Use the class Cat of the first task. Do not create the class Cat. */ public class Solution { public static void main(String[] args) { Cat cat1 = new Cat("CatA", 10, 14, 9); Cat cat2 = new Cat("CatB", 10, 14, 9); Cat cat3 = new Cat("CatC", 10, 14, 9); } public static class Cat { public static int count = 0; private String name; private int age; private int weight; private int strength; public Cat(String name, int age, int weight, int strength) { count++; this.name = name; this.age = age; this.weight = weight; this.strength = strength; } } }
package com.metoo.view.web.tools; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.nutz.json.Json; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsCase; import com.metoo.foundation.service.IGoodsCaseService; import com.metoo.foundation.service.IGoodsService; /** * * <p> * Title: GoodsCaseViewTools.java * </p> * * <p> * Description: 橱窗工具类 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author lixiaoyang * * @date 2014-11-24 * * @version koala_b2b2c 2.0 */ @Component public class GoodsCaseViewTools { @Autowired private IGoodsCaseService goodscaseService; @Autowired private IGoodsService goodsService; public List queryGoodsCase(String case_id) { Map params = new HashMap(); params.put("case_id", case_id); params.put("display", 1); List<GoodsCase> list = this.goodscaseService .query("select obj from GoodsCase obj where obj.case_id=:case_id and obj.display=:display order by obj.sequence", params, 0, 6); List<String> ca = new ArrayList<String>(); return list; } public List queryCaseGoods(String case_content) { if (case_content != null && !case_content.equals("")) { List list = (List) Json.fromJson(case_content); List<Goods> goods_list = new ArrayList<Goods>(); if (list.size() > 6) { for (Object id : list.subList(0, 6)) { Map params = new HashMap(); params.put("id", CommUtil.null2Long(id)); List<Goods> objs = this.goodsService .query("select new Goods(id,goods_name,goods_current_price,goods_price,goods_main_photo) from Goods obj where obj.id=:id", params, 0, 1); if (objs.size() > 0) { goods_list.add(objs.get(0)); } } } else { for (Object id : list) { Map params = new HashMap(); params.put("id", CommUtil.null2Long(id)); List<Goods> objs = this.goodsService .query("select new Goods(id,goods_name,goods_current_price,goods_price,goods_main_photo) from Goods obj where obj.id=:id", params, 0, 1); if (objs.size() > 0) { goods_list.add(objs.get(0)); } } } return goods_list; } return null; } }
package main; public class InterfacesMain { public static void main(String[] args) { // static methods in interfaces can be called like in any class OtherInterface.staticMethod(); // we create an object of type [MyClass] and store it in a variable of [AnInterface] AnInterface myObject = new MyClass(); myObject.interfaceMethod(); myObject.a(); // now we replace the object in the variable [myObject] with an object of the type [MyOtherClass] myObject = new MyOtherClass(); myObject.a(); } }
package ch.florianluescher.salary; import java.util.NoSuchElementException; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; public interface Nullable<T> { boolean isPresent(); T get(); T getOrElse(T fallback); <U> Nullable<U> map(Function<T,U> f); <U> Nullable<U> flatMap(Function<T, Nullable<U>> f); Nullable<T> filter(Predicate<T> predicate); Nullable<T> ifPresent(Consumer<T> consumer); static <T> Nullable<T> of(T reference) { if(reference == null) return new Null(); return new Some(reference); } class Some<T> implements Nullable<T> { private final T value; private Some(T value) { if(value == null) throw new RuntimeException("Tried to initialize Some instance with null"); this.value = value; } @Override public boolean isPresent() { return true; } @Override public T get() { return value; } @Override public T getOrElse(T fallback) { return this.value; } @Override public <U> Nullable<U> map(Function<T, U> f) { return new Some(f.apply(this.value)); } @Override public <U> Nullable<U> flatMap(Function<T, Nullable<U>> f) { return Nullable.of(f.apply(this.value).getOrElse(null)); } @Override public Nullable<T> filter(Predicate<T> predicate) { if(predicate.test(this.value)) { return this; } else { return new Null<T>(); } } @Override public Nullable<T> ifPresent(Consumer<T> consumer) { consumer.accept(this.value); return this; } } class Null<T> implements Nullable<T> { private Null() {} @Override public boolean isPresent() { return false; } @Override public T get() { throw new NoSuchElementException(); } @Override public T getOrElse(T fallback) { return fallback; } @Override public <U> Nullable<U> map(Function<T, U> f) { return new Null<U>(); } @Override public <U> Nullable<U> flatMap(Function<T, Nullable<U>> f) { return new Null<U>(); } @Override public Nullable<T> filter(Predicate<T> predicate) { return this; } @Override public Nullable<T> ifPresent(Consumer<T> consumer) { return this; } } }
package net.imglib2.view; public class IjMetaGenerics { public interface ViewFactory< S > { S createView( S source ); } public interface Space< S extends Space< S, T >, T > { T type(); Space< S, T > access(); ViewFactory< S > viewFactory(); } static abstract class SpaceView< S extends Space< S, T >, T > implements Space< S, T > { private final S source; public SpaceView( final S source ) { this.source = source; } @Override public T type() { return source.type(); } @Override public Space< S, T > access() { return new Access(); } class Access implements Space< S, T > { @Override public T type() { return SpaceView.this.type(); } @Override public Space< S, T > access() { return SpaceView.this.access(); } @Override public ViewFactory< S > viewFactory() { return SpaceView.this.viewFactory(); } } } static abstract class SpaceContainer< S extends Space< S, T >, T > implements Space< S, T > { private final T type; public SpaceContainer( final T type ) { this.type = type; } @Override public T type() { return type; } @Override public Space< S, T > access() { return this; } } static interface IjSpace extends Space< IjSpace, String > {} static class IjSpaceViewFactory implements ViewFactory< IjSpace > { static IjSpaceViewFactory instance = new IjSpaceViewFactory(); private IjSpaceViewFactory() {} @Override public IjSpace createView( final IjSpace source ) { return new IjSpaceView( source ); } } static class IjSpaceView extends SpaceView< IjSpace, String > implements IjSpace { public IjSpaceView( final IjSpace source ) { super( source ); } @Override public ViewFactory< IjSpace > viewFactory() { return IjSpaceViewFactory.instance; } } static class IjSpaceContainer extends SpaceContainer< IjSpace, String > implements IjSpace { public IjSpaceContainer( final String type ) { super( type ); } @Override public ViewFactory< IjSpace > viewFactory() { return IjSpaceViewFactory.instance; } } public static < S extends Space< S, T >, T > S view( final S source ) { return source.viewFactory().createView( source ); } public static void main( final String[] args ) { final IjSpace c = new IjSpaceContainer( "blah " ); final IjSpace v = view( c ); final IjSpace vv = view( v ); System.out.print( c.type() ); System.out.print( v.type() ); System.out.print( vv.type() ); System.out.println(); System.out.print( c.access().type() ); System.out.print( v.access().type() ); System.out.print( vv.access().type() ); System.out.println(); } }
package ua.game.pro.dto; import ua.game.pro.entity.GroupOfUsers; public class ProfesorDTO { private int id; private String name; private GroupOfUsers groupOfUsers; public ProfesorDTO() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public GroupOfUsers getGroupOfUsers() { return groupOfUsers; } public void setGroupOfUsers(GroupOfUsers groupOfUsers) { this.groupOfUsers = groupOfUsers; } }
package com.example.practica3; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class Fragment_Eliminar extends Fragment { Button eliminar; private SQLlite sqlite; EditText id; public Fragment_Eliminar() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_fragment__eliminar, container, false); eliminar = (Button) view.findViewById(R.id.bEliminar); id = (EditText) view.findViewById(R.id.txtId); eliminar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sqlite=new SQLlite(getContext()); sqlite.abrir(); System.out.print("Entraste"); if(id.getText().toString()!=null){ sqlite.Eliminar(id.getText()); Toast.makeText(getContext(), "Registro Eliminado", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getContext(), "Llene el campo", Toast.LENGTH_SHORT).show(); } } }); return view; } }
/* NMS-DRIVERS -- Free NMS packages. * Copyright (C) 2009 Andrew A. Porohin * * NMS-DRIVERS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 2.1 of the License. * * NMS-DRIVERS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with NMS-DRIVERS. If not, see <http://www.gnu.org/licenses/>. */ package org.aap.nms.driver.client.pingobject; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import javax.swing.ImageIcon; import org.aap.nms.driver.client.abstraction.AbstractDriverUI; import org.doomdark.uuid.UUID; import org.valabs.odisp.common.Message; import com.novel.nms.client.components.DeviceInfo; import com.novel.nms.client.devices.DeviceType; import com.novel.nms.client.devices.GenericDevice; import com.novel.nms.client.tcpclient.NetManager; import com.novel.nms.messages.MapAddObjectMessage; import com.novel.nms.messages.MapAddObjectNotifyMessage; import com.novel.nms.messages.client.DeviceAddObjectMessage; import com.novel.nms.messages.client.DeviceAddObjectReplyMessage; import com.novel.nms.messages.client.RegisterTypeMessage; /** * Just a ping object. * * If you make a choice by trusting your feelings instead of your logic, * and you succeed, then, logically, your logic was illogical. * * @author <a href="andrew.porokhin@gmail.com">Andrew A. Porokhin</a> * @version 1.0 */ public class PingGUI extends AbstractDriverUI { /** Device handler */ public static final String HANDLER = "ping"; /** Device name. */ public static final String NAME = HANDLER + "-gui"; /** Module version. */ public static final String VERSION = "1.0.0.1"; /** Module description. */ public static final String FULLNAME = "ping.name"; /** All right reserved. */ public static final String COPYRIGHT = "ping.copyright"; /** Short description of the module. */ public static final String SHORTNAME = "ping.shortName"; /** Field to store request id. */ public static final String MSG_ID_FIELD = "requestMsgId"; /** Field to store coordinate of creator. */ public static final String MSG_ORIG_FIELD = "requestMsgOrig"; /** Processes for that handler. */ private List processes = new LinkedList(); /** Icon for ping object. */ public static ImageIcon deviceIcon = null; /** * Конструктор. */ public PingGUI() { super(NAME, FULLNAME, VERSION, COPYRIGHT); deviceIcon = new ImageIcon(getClass().getResource("/resources/client/default_ping.gif")); } /* * (non-Javadoc) * @see org.valabs.odisp.common.StandartODObject#handleMessage(org.valabs.odisp.common.Message) */ public void handleMessage(Message msg) { if (DeviceAddObjectMessage.equals(msg)) { // Add device to the map. DeviceInfo newInfo = (DeviceInfo) DeviceAddObjectMessage.getDevice(msg); newInfo.setProperty(MSG_ID_FIELD, msg.getId()); newInfo.setProperty(MSG_ORIG_FIELD, msg.getOrigin()); Message addmsg = dispatcher.getNewMessage(); MapAddObjectMessage.setup(addmsg, NetManager.makeDestination(newInfo .getHandler(), NetManager .makeOrigin(newInfo.getConnectionIndex())), getObjectName(), UUID .getNullUUID()); MapAddObjectMessage.setName(addmsg, newInfo.getName()); MapAddObjectMessage.setHandler(addmsg, newInfo.getHandler()); MapAddObjectMessage.setURN(addmsg, newInfo.getURN()); MapAddObjectMessage.setCity(addmsg, (String) newInfo.getProperty(DeviceInfo.CITY)); MapAddObjectMessage.setSuffix(addmsg, (String) newInfo.getProperty(DeviceInfo.SUFFIX)); MapAddObjectMessage.setOwner(addmsg, (String) newInfo.getProperty(DeviceInfo.OWNER)); MapAddObjectMessage.setCustomer(addmsg, (String) newInfo.getProperty(DeviceInfo.CUSTOMER)); MapAddObjectMessage.setPlacement(addmsg, (String) newInfo.getProperty(DeviceInfo.PLACEMENT)); MapAddObjectMessage.setComment(addmsg, (String) newInfo.getProperty(DeviceInfo.COMMENTS)); if (!addmsg.isCorrect()) { logger.severe("Message AddObject is incorrect"); } // copy additional fields. Iterator it = msg.getEnvelope().iterator(); while (it.hasNext()) { addmsg.addToEnvelope((Message) it.next()); } synchronized (processes) { processes.add(newInfo); } dispatcher.send(addmsg); } else if (MapAddObjectNotifyMessage.equals(msg)) { // This message received from map and inform us that // add object process complited. boolean found = false; synchronized (processes) { DeviceInfo devInfo = null; for (Iterator it = processes.iterator(); it.hasNext(); ) { devInfo = (DeviceInfo) it.next(); if (devInfo.getName().equals(MapAddObjectNotifyMessage.getName(msg)) && devInfo.getHandler().equals( MapAddObjectNotifyMessage.getHandler(msg)) && devInfo.getConnectionIndex() == NetManager .getIndexFromOrigin(msg.getOrigin())) { found = true; break; } } if (found) { processes.remove(devInfo); Message reply = dispatcher.getNewMessage(); DeviceAddObjectReplyMessage.setup( reply, (String) devInfo.getProperty(MSG_ORIG_FIELD), getObjectName(), (UUID) devInfo.getProperty(MSG_ID_FIELD)); DeviceAddObjectReplyMessage.setDevice(reply, devInfo); // Remove temporarily fields devInfo.setProperty(MSG_ID_FIELD, null); devInfo.setProperty(MSG_ORIG_FIELD, null); // Send result to originator dispatcher.send(reply); /* * I think that code is deprecated. * Message enumObj = dispatcher.getNewMessage(); MapEnumerateObjectsReplyMessage.setup(enumObj, "map-gui", NetManager.makeDestination("map", msg.getOrigin()), UUID.getNullUUID()); List newObj = new ArrayList(); newObj.add(MapAddObjectNotifyMessage.getName(msg)); newObj.add(MapAddObjectNotifyMessage.getURN(msg)); newObj.add(MapAddObjectNotifyMessage.getHandler(msg)); newObj.add(new Integer(0)); enumObj.addField("0", newObj); dispatcher.send(enumObj);*/ } else if (MapAddObjectNotifyMessage.getHandler(msg).equals(HANDLER)) { logger.info("Object not found, may be it is not my object"); } } // synchronized (processes) } else { if (!handleCommonMessage(msg) && logger.isLoggable(Level.FINEST)) { logger.finest("Message unprocessed by driver: " + msg.toString()); } } } protected void registerDeviceTypes() { // Register new device type: simple ping object. DeviceType devicePing = new DeviceType(); devicePing.setHandler(HANDLER); devicePing.setHasChild(false); devicePing.setIcon(deviceIcon); devicePing.setRealName(translate(SHORTNAME, "PING")); // Send register message. Message registerMessage = dispatcher.getNewMessage(); RegisterTypeMessage.setup(registerMessage, GenericDevice.DEVICE_SERVICE, getObjectName(), UUID.getNullUUID()); RegisterTypeMessage.setHandler(registerMessage, HANDLER); RegisterTypeMessage.setDeviceType(registerMessage, devicePing); dispatcher.send(registerMessage); } /* * (non-Javadoc) * @see org.valabs.odisp.common.ODObject#getDepends() */ public String[] getDepends() { String depends[] = { "dispatcher", com.novel.nms.client.components.info.InfoGUI.NAME, com.novel.nms.client.components.map.MapGUI.NAME }; return depends; } /* * (non-Javadoc) * @see org.valabs.odisp.common.ODObject#getProviding() */ public String[] getProviding() { String providing[] = { NAME }; return providing; } }
package com.aliam3.polyvilleactive.model; import com.aliam3.polyvilleactive.db.MockAPI; import com.aliam3.polyvilleactive.model.incidents.transportation.Delay; import com.aliam3.polyvilleactive.model.transport.Journey; import com.aliam3.polyvilleactive.model.transport.ModeTransport; import com.aliam3.polyvilleactive.service.JourneyService; import org.junit.Test; import java.time.Duration; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class JourneyTest { @Test public void isAffectedByTest(){ MockAPI mockAPI = new MockAPI(); JourneyService journeyService = new JourneyService(); List<Journey> journeys = journeyService.jsonJourneyToObject(mockAPI.loadResource("mock/test2.json")); Delay delay1= new Delay(Duration.ofSeconds(2000), "Pontoise / Versailles R. Gauche / St-Quentin en Y. - Versailles Ch. / Dourdan la F. / St-Martin d'E", ModeTransport.TRAIN); assertTrue(journeys.get(0).isAffectedBy(delay1)); Delay delay2= new Delay(Duration.ofSeconds(2000), "Pontoise / Versailles R. Gauche / St-Quentin en Y. - Versailles Ch. / Dourdan la F. / St-Martin d'E", ModeTransport.METRO); assertFalse(journeys.get(0).isAffectedBy(delay2)); } @Test public void getCurrentStep() { MockAPI mockAPI = new MockAPI(); JourneyService journeyService = new JourneyService(); List<Journey> journeys = journeyService.jsonJourneyToObject(mockAPI.loadResource("mock/test2.json")); assertEquals(journeys.get(0).getSections().get(0), journeys.get(0).getCurrentStep()); journeys.get(0).getSections().get(0).setReached(true); journeys.get(0).getSections().get(2).setReached(true); journeys.get(0).getSections().get(3).setReached(true); assertEquals(journeys.get(0).getSections().get(1), journeys.get(0).getCurrentStep()); journeys.get(0).getSections().get(1).setReached(true); assertEquals(journeys.get(0).getSections().get(4), journeys.get(0).getCurrentStep()); } }
package com.ama.springdemojavaconfiguration; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class JavaConfigDemoApp { public static void main(String[] args) { // load the spring configuration file ==> create spring Container from java configuration class AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SportConfig.class); // Retrieve bean from Spring Container //BaseBallCoach baseBallBean = context.getBean("baseBallCoach", BaseBallCoach.class); Coach swimBean = context.getBean("swimCoach", SwimCoach.class); // use the bean //System.out.println(baseBallBean.getDailyWorkout()); //System.out.println(baseBallBean.getDailyFortune()); System.out.println(swimBean.getDailyFortune()); System.out.println("My email is : " + ((SwimCoach)swimBean).getEmail()); System.out.println("My team is : " + ((SwimCoach)swimBean).getTeam()); //close context context.close(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inbio.ara.persistence.gathering; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Embeddable; /** * * @author esmata */ @Embeddable public class CollectorObserverPK implements Serializable { @Basic(optional = false) @Column(name = "gathering_observation_id") private Long gatheringObservationId; @Basic(optional = false) @Column(name = "collector_person_id") private Long collectorPersonId; public CollectorObserverPK() { } public CollectorObserverPK(Long gatheringObservationId, Long collectorPersonId) { this.gatheringObservationId = gatheringObservationId; this.collectorPersonId = collectorPersonId; } public Long getGatheringObservationId() { return gatheringObservationId; } public void setGatheringObservationId(Long gatheringObservationId) { this.gatheringObservationId = gatheringObservationId; } public Long getCollectorPersonId() { return collectorPersonId; } public void setCollectorPersonId(Long collectorPersonId) { this.collectorPersonId = collectorPersonId; } @Override public int hashCode() { int hash = 0; hash += (gatheringObservationId != null ? gatheringObservationId.hashCode() : 0); hash += (collectorPersonId != null ? collectorPersonId.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof CollectorObserverPK)) { return false; } CollectorObserverPK other = (CollectorObserverPK) object; if ((this.gatheringObservationId == null && other.gatheringObservationId != null) || (this.gatheringObservationId != null && !this.gatheringObservationId.equals(other.gatheringObservationId))) { return false; } if ((this.collectorPersonId == null && other.collectorPersonId != null) || (this.collectorPersonId != null && !this.collectorPersonId.equals(other.collectorPersonId))) { return false; } return true; } @Override public String toString() { return "org.inbio.ara.inventory.CollectorObserverPK[gatheringObservationId=" + gatheringObservationId + ", collectorPersonId=" + collectorPersonId + "]"; } }
package stepDefinitions; import java.io.IOException; import io.cucumber.java.Before; public class Hooks { @Before("@deletePlaceAPI") public void precondition() throws IOException { if(StepDefinitions.placeId == null) { StepDefinitions sd = new StepDefinitions(); sd.place_payload("100", "daniel", "(+91) 9876543287", "120, machiel layout, cohen 23"); sd.user_calls_with_http_request("addPlaceAPI", "post"); sd.verify_that_maps_to_by_calling_with_http_request("daniel", "getPlaceAPI", "get"); } } }
package org.jacpfx.kube.repository; import org.jacpfx.kube.entity.Person; import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.repository.reactive.ReactiveCrudRepository; import org.springframework.stereotype.Repository; /** * Created by amo on 04.04.17. */ public interface ReactiveUserRepository extends ReactiveCrudRepository<Person, String> { }
package scalagoon; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ SimplePins.class, ShortSpares.class, ShortStrikes.class, Textual.class, NormalPlay.class, FinalFrameTest.class }) /** * Contenitore per tutti i test * * @author mim * */ public class AllTests { }
package com.next.infra.odata4; import java.util.List; import java.util.Map.Entry; import javax.persistence.EntityManager; import org.apache.olingo.commons.api.http.HttpMethod; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath; import com.sap.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType; import com.sap.olingo.jpa.processor.core.api.JPAAbstractCUDRequestHandler; import com.sap.olingo.jpa.processor.core.exception.ODataJPAInvocationTargetException; import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessException; import com.sap.olingo.jpa.processor.core.exception.ODataJPAProcessorException; import com.sap.olingo.jpa.processor.core.modify.JPAUpdateResult; import com.sap.olingo.jpa.processor.core.processor.JPARequestEntity; import com.sap.olingo.jpa.processor.core.processor.JPARequestLink; public class ODataRequestHandler extends JPAAbstractCUDRequestHandler { @Override public Object createEntity(final JPARequestEntity requestEntity, final EntityManager em) throws ODataJPAProcessException { final JPAEntityType et = requestEntity.getEntityType(); /*if (et.getExternalName().equals("AdministrativeDivision")) { final Map<String, Object> jpaAttributes = requestEntity.getData(); AdministrativeDivision result = new AdministrativeDivision(); result.setCodeID((String) jpaAttributes.get("codeID")); result.setCodePublisher((String) jpaAttributes.get("codePublisher")); result.setDivisionCode((String) jpaAttributes.get("divisionCode")); result.setCountryCode((String) jpaAttributes.get("countryCode")); result.setParentCodeID((String) jpaAttributes.get("parentCodeID")); result.setParentDivisionCode((String) jpaAttributes.get("parentDivisionCode")); result.setAlternativeCode((String) jpaAttributes.get("alternativeCode")); result.setArea((Integer) jpaAttributes.get("area")); result.setPopulation((Long) jpaAttributes.get("population")); em.persist(result); return result; }*/ return super.createEntity(requestEntity, em); } @Override public void deleteEntity(JPARequestEntity requestEntity, EntityManager em) throws ODataJPAProcessException { final Object instance = em.find(requestEntity.getEntityType().getTypeClass(), requestEntity.getModifyUtil().createPrimaryKey(requestEntity.getEntityType(), requestEntity.getKeys(), requestEntity.getEntityType())); if (instance != null) em.remove(instance); } @Override public JPAUpdateResult updateEntity(final JPARequestEntity requestEntity, final EntityManager em, final HttpMethod method) throws ODataJPAProcessException { if (method == HttpMethod.PATCH || method == HttpMethod.DELETE) { final Object instance = em.find(requestEntity.getEntityType().getTypeClass(), requestEntity.getModifyUtil() .createPrimaryKey(requestEntity.getEntityType(), requestEntity.getKeys(), requestEntity.getEntityType())); requestEntity.getModifyUtil().setAttributesDeep(requestEntity.getData(), instance, requestEntity.getEntityType()); updateLinks(requestEntity, em, instance); return new JPAUpdateResult(false, instance); } return super.updateEntity(requestEntity, em, method); } private void updateLinks(final JPARequestEntity requestEntity, final EntityManager em, final Object instance) throws ODataJPAProcessorException, ODataJPAInvocationTargetException { if (requestEntity.getRelationLinks() != null) { for (Entry<JPAAssociationPath, List<JPARequestLink>> links : requestEntity.getRelationLinks().entrySet()) { for (JPARequestLink link : links.getValue()) { final Object related = em.find(link.getEntityType().getTypeClass(), requestEntity.getModifyUtil() .createPrimaryKey(link.getEntityType(), link.getRelatedKeys(), link.getEntityType())); requestEntity.getModifyUtil().linkEntities(instance, related, links.getKey()); } } } } }
package com.xh.proxy; import com.xh.base.BaseProxyActivity; /** * @version 创建时间:2017-12-29 上午9:59:09 * 项目:repair * 包名:com.xh.proxy * 文件名:XhProxyActivity.java * 作者:lhl * 说明:代理类,在清单文件中需要注册 */ public class XhProxyActivity extends BaseProxyActivity { }
package com.Service; import java.util.List; import com.al.model.Quotation; import com.al.model.Vendor; public class TestingMain { public static void main(String[] args) { // QuotationService quotationService = new QuotationService(); // List<Quotation> allQuotationList = quotationService.getAllQuotation(); // // List<Quotation> lowestQuotedCostFisrtList = quotationService.lowestQuotedCostFisrt(allQuotationList); // List<Quotation> earliestDeliveryList = quotationService.earliestDelivery(allQuotationList); // for(Quotation q : earliestDeliveryList) // { // System.out.println(q); // } VendorService vendorService = new VendorService(); List<Vendor> allVendorsList = vendorService.getAllVendors(); List<Vendor> bestVendorFirst = vendorService.bestVendorFirst(allVendorsList); for(Vendor v : bestVendorFirst) { System.out.println(v); } } }
package maksplo.study.myLinkedList; public class MyLinkedList<E> { private Element<E> last; private Element<E> first; private int count; public MyLinkedList() { last = new Element<E>(first, null, null); first = new Element<E>(null, null, last); } public void add(E e) { Element<E> result = last; result.setElement(e); last = new Element<E>(result, null, null); result.setNextElement(last); count++; } public int size() { return count; } public E get(int index) { if (index < 0 || index >= count) { throw new IndexOutOfBoundsException(); } Element<E> result = first; for (int i = 0 - 1; i < index; i++) { result = result.getNextElement(); } return result.getElement(); } public void remove(int index) { if (index < 0 || index >= count) { throw new IndexOutOfBoundsException(); } if (index == 0) { first = first.getNextElement(); count--; } else if (index == count - 1) { last = last.getPrevElement(); count--; } else { Element<E> currentElement = first; for (int i = 0 - 1; i < index; i++) { currentElement = currentElement.getNextElement(); } Element<E> nextElement = currentElement.getNextElement(); Element<E> prevElement = currentElement.getPrevElement(); prevElement.setNextElement(nextElement); count--; } } }
package com.example.hackathonapp; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class GetHelpActivity extends AppCompatActivity { TextView Food, Medical, Financial, Other, Confirm; boolean sel1 = false, sel2 = false, sel3 = false, sel4 = false; long maxid = 0; EditText food, medical, financial, others, add1, locality, city, state, nop; DatabaseReference myRef; HelpDetails helpDetails; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_get_help); Food = (TextView)findViewById(R.id.tvghafood); Medical = (TextView)findViewById(R.id.tvghamedical); Financial = (TextView)findViewById(R.id.tvghafinancial); Other = (TextView)findViewById(R.id.tvghaother); Confirm = (TextView)findViewById(R.id.tvghaconfirm); food = (EditText)findViewById(R.id.etfood); medical = (EditText)findViewById(R.id.etmedical); financial = (EditText)findViewById(R.id.etfinancial); others = (EditText)findViewById(R.id.etothers); add1 = (EditText)findViewById(R.id.etadd1); locality = (EditText)findViewById(R.id.etlocality); city = (EditText)findViewById(R.id.etcity); state = (EditText)findViewById(R.id.etstate); nop = (EditText)findViewById(R.id.etnop); myRef = FirebaseDatabase.getInstance().getReference().child("Help"); Food.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (sel1){ deselect(Food); sel1 = false; } else{ select(Food); sel1 = true; } } }); Medical.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (sel2){ deselect(Medical); sel2 = false; } else{ select(Medical); sel2 = true; } } }); Financial.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (sel3){ deselect(Financial); sel3 = false; } else{ select(Financial); sel3 = true; } } }); Other.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (sel4){ deselect(Other); sel4 = false; } else{ select(Other); sel4 = true; } } }); myRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { maxid = (dataSnapshot.getChildrenCount()); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getApplicationContext(), "There was an error!", Toast.LENGTH_SHORT).show(); } }); Confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { helpDetails = new HelpDetails(); helpDetails.setFood(food.getText().toString().trim()); helpDetails.setMedical(medical.getText().toString().trim()); helpDetails.setFinancial(financial.getText().toString().trim()); helpDetails.setOther(others.getText().toString().trim()); helpDetails.setAddress(add1.getText().toString().trim()+", "+locality.getText().toString().trim()+", "+city.getText().toString().trim()+", "+state.getText().toString().trim()); helpDetails.setNOP(nop.getText().toString().trim()); myRef.child(String.valueOf(maxid + 1)).setValue(helpDetails); Toast.makeText(GetHelpActivity.this, "Successfully Posted!", Toast.LENGTH_SHORT).show(); finish(); } }); } void select(TextView view){ view.setBackgroundResource(R.drawable.card_corners_highlighted); view.setTextColor(Color.parseColor("#ffffff")); } void deselect(TextView view){ view.setBackgroundResource(R.drawable.card_corners); view.setTextColor(Color.parseColor("#000000")); } }
package prf.cloneUtil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; public class CloneUtil {//深拷贝 @SuppressWarnings("unchecked") public static <T extends Serializable> T clone(T obj) { T clonedObj = null; try { //序列化 ByteArrayOutputStream output = new ByteArrayOutputStream(); ObjectOutputStream objOutput = new ObjectOutputStream(output); objOutput.writeObject(obj); objOutput.close(); //反序列化 ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray()); ObjectInputStream objInput = new ObjectInputStream(input); clonedObj = (T) objInput.readObject(); objInput.close(); } catch (IOException | ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return clonedObj; } }
package com.hellofresh.challenge.utils; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class PropertyReader { private static Properties prop = new Properties(); private static String fileName = "src/test/resources/config.properties"; public static String getProperty(String arg) { try { // load a properties file for reading prop.load(new FileInputStream(fileName)); } catch (IOException ex) { ex.printStackTrace(); } return prop.getProperty(arg); } }
package Jugador; import BaseDeDatos.Executes; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; /** * Created by pauit on 25/12/2016. */ public class DataLoad implements Listener { @EventHandler (priority = EventPriority.HIGHEST) public void eventoEntrar(PlayerJoinEvent e) { e.setJoinMessage(null); if (!Executes.jugadorExiste(e.getPlayer())) { Executes.registrarUsuario(e.getPlayer()); } else { return; } } @EventHandler public void eventoSalir(PlayerQuitEvent e) { e.setQuitMessage(null); } }
package com.github.nik9000.nnfa.heap; import static com.github.nik9000.nnfa.heap.AcceptsMatcher.accepts; import static org.apache.lucene.util.TestUtil.randomRealisticUnicodeString; import static org.hamcrest.Matchers.not; import java.nio.charset.Charset; import java.util.Random; import org.apache.lucene.util.LuceneTestCase; import org.junit.Test; import com.github.nik9000.nnfa.builder.NfaBuilder; /** * Test for AbstractCodePointOperations. */ public class CodePointOperationsTest extends LuceneTestCase { @Test public void codePointAcceptsThatCodePoint() { String c = randomRealisticUnicodeString(random(), 1, 1); Nfa nfa = new NfaBuilder().codePoint(c.codePointAt(0)).build(); assertThat(nfa, accepts(c)); assertThat(nfa, not(accepts(c + randomRealisticUnicodeString(random(), 1, 20)))); assertThat(nfa, accepts(c + randomRealisticUnicodeString(random(), 1, 20)).endUnanchored()); assertThat(nfa, accepts(randomRealisticUnicodeString(random(), 1, 20) + c) .startUnanchored()); } @Test public void codePointWithFromAndTo() { String cp = randomRealisticUnicodeString(random(), 1, 1); Nfa nfa = new NfaBuilder().codePoint("a").codePoint("b").accepts().from(0).to(1).codePoint(cp).buildNoAccept(); assertThat(nfa, accepts("ab")); assertThat(nfa, accepts(cp + "b")); assertThat(nfa, not(accepts("ab" + cp))); assertThat(nfa, not(accepts(cp + "ab"))); } @Test public void anyCodePointAcceptsAnySingleChar() { assertThat(new NfaBuilder().anyCodePoint().build(), accepts(randomRealisticUnicodeString(random(), 1, 1)).randomAnchoring(random())); } @Test public void anyCodePointDoesNotAcceptEmptyString() { assertThat(new NfaBuilder().anyCodePoint().build(), not(accepts("").randomAnchoring(random()))); } @Test public void anyCodePointDoesNotAcceptInvalidUtf8() { assertThat(new NfaBuilder().anyCodePoint().build(), not(accepts(randomInvalidUtf8Sequence(random())))); } @Test public void anyCodePointAcceptsAnyStringUnanchored() { Nfa nfa = new NfaBuilder().anyCodePoint().build(); assertThat(nfa, accepts(randomRealisticUnicodeString(random(), 1, 20)).startUnanchored()); assertThat(nfa, accepts(randomRealisticUnicodeString(random(), 1, 20)).endUnanchored()); assertThat(nfa, not(accepts(randomRealisticUnicodeString(random(), 2, 20)))); } @Test public void anyCodePointWithFromAndTo() { Nfa nfa = new NfaBuilder().codePoint("a").codePoint("b").accepts().from(0).to(1).anyCodePoint().buildNoAccept(); assertThat(nfa, accepts("ab")); assertThat(nfa, accepts(randomRealisticUnicodeString(random(), 1, 1) + "b")); assertThat(nfa, not(accepts("ab" + randomRealisticUnicodeString(random(), 1, 1)))); assertThat(nfa, not(accepts(randomRealisticUnicodeString(random(), 1, 1) + "ab"))); } private byte[] randomInvalidUtf8Sequence(Random random) { // 0 characters are no fun - they can't be broken. byte[] bytes = randomRealisticUnicodeString(random, 1, 20).getBytes( Charset.forName("utf-8")); // TODO add more ways to break utf-8 switch (random.nextInt(3)) { case 0: // The only valid prefix for continuation is 0b10xxxxxx so if we // find one an ruin it we'll break the encoding for (int i = 1; i < bytes.length; i++) { if ((bytes[i] & 0xc0) == 0x80) { // The high two bits are 0b10 bytes[i] &= 0xc0; // Now they are 0b11 break; } } // Couldn't find a byte to break - move on to the next method case 1: // The number of bytes in a multibyte sequence is specified by the // first byte so if we find the next byte _after_ the end of a // sequence and make it another continuation byte that'd be wrong for (int i = 2; i < bytes.length; i++) { if ((bytes[i - 1] & 0xc0) == 0x80 && (bytes[i] & 0xc0) != 0x80) { // The high two bits aren't 0b10 bytes[i] = (byte) 0x80; // Now they are 0b10 break; } } // Couldn't find a multibyte character to break - move on to the // next method case 2: // 0xff, 0x is invalid in utf-8 bytes[random.nextInt(bytes.length)] = (byte) 0xff; break; case 3: // TODO overlong encodings // Overlong encodings are when you encode a sequence with more than // the minimum number of bytes required. This is not allowed by the // utf-8 spec. default: throw new RuntimeException("Fix case statement!"); } return bytes; } }
package com.citibank.ods.modules.client.mrdocprvt.form; /** * Interface implementada nos forms MrDocPrvtHistListForm e MrDocPrvtHistDetailForm. * * @author michele.monteiro,24/04/2007 * */ public interface MrDocPrvtHistDetailable { /** * @return SelectedMrDocPrvt. Retorna o código do documento MR. */ public String getSelectedMrDocCode(); /** * @param mrDocPrvt_. Seta o código do documento MR. */ public void setSelectedMrDocCode( String mrDocCode_ ); /** * @return SelectedMrDocPrvt. Retorna o número da conta produto. */ public String getSelectedProdAcctCode(); /** * @param prodAcctCode_. Seta o número da conta produto. */ public void setSelectedProdAcctCode( String prodAcctCode_ ); /** * @return SelectedMrDocPrvt. Retorna o número da sub conta produto. */ public String getSelectedProdUnderAcctCode(); /** * @param prodUnderAcctCode_. Seta o número da sub conta produto. */ public void setSelectedProdUnderAcctCode( String prodUnderAcctCode_ ); /** * @return Retorna a data de referência do históric. */ public String getSelectedMrDocRefDate(); /** * @param mrDocRefDate_. Seta a data de referência do histórico. */ public void setSelectedMrDocRefDate( String mrDocRefDate_ ); }
/* ~~ The Main is part of BusinessProfit. ~~ * * The BusinessProfit's classes and any part of the code * cannot be copied/distributed without * the permission of Sotiris Doudis * * Github - RiflemanSD - https://github.com/RiflemanSD * * Copyright © 2016 Sotiris Doudis | All rights reserved * * License for BusinessProfit project - in GREEK language * * Οποιοσδήποτε μπορεί να χρησιμοποιήσει το πρόγραμμα για προσωπική του χρήση. * Αλλά απαγoρεύεται η πώληση ή διακίνηση του προγράμματος σε τρίτους. * * Aπαγορεύεται η αντιγραφή ή διακίνηση οποιοδήποτε μέρος του κώδικα χωρίς * την άδεια του δημιουργού. * Σε περίπτωση που θέλετε να χρεισημοποιήσετε κάποια κλάση ή μέρος του κώδικα. * Πρέπει να συμπεριλάβεται στο header της κλάσης τον δημιουργό και link στην * αυθεντική κλάση (στο github). * * ~~ Information about BusinessProfit project - in GREEK language ~~ * * Το BusinessProfit είναι ένα project για την αποθήκευση και επεξεργασία * των εσόδων/εξόδων μίας επιχείρησης με σκοπό να μπορεί ο επιχειρηματίας να καθορήσει * το καθαρό κέρδος της επιχείρησης. Καθώς και να κρατάει κάποια σημαντικά * στατιστικά στοιχεία για τον όγκο της εργασίας κτλ.. * * Το project δημιουργήθηκε από τον Σωτήρη Δούδη. Φοιτητή πληροφορικής του Α.Π.Θ * για προσωπική χρήση. Αλλά και για όποιον άλλον πιθανόν το χρειαστεί. * * Το project προγραμματίστηκε σε Java (https://www.java.com/en/download/). * Με χρήση του NetBeans IDE (https://netbeans.org/) * Για να το τρέξετε πρέπει να έχετε εγκαταστήσει την java. * * Ο καθένας μπορεί δωρεάν να χρησιμοποιήσει το project αυτό. Αλλά δεν επιτρέπεται * η αντιγραφή/διακήνηση του κώδικα, χωρίς την άδεια του Δημιουργού (Δείτε την License). * * Github - https://github.com/RiflemanSD/BusinessProfit * * * Copyright © 2016 Sotiris Doudis | All rights reserved */ package org.riflemansd.businessprofit; import org.riflemansd.businessprofit2.Category; import org.riflemansd.businessprofit2.IncomeCost; import org.riflemansd.businessprofit2.PackagesIncome; import org.riflemansd.businessprofit2.db.InOutDB; /** <h1>Main</h1> * * <p></p> * * <p>Last Update: 01/02/2016</p> * <p>Author: <a href=https://github.com/RiflemanSD>RiflemanSD</a></p> * * <p>Copyright © 2016 Sotiris Doudis | All rights reserved</p> * * @version 1.0.7 * @author RiflemanSD */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { Category cat1 = new Category(0, "demata"); Category cat2 = new Category(1, "papoutsia"); Category cat3 = new Category(2, "logiariasmoi"); Category cat4 = new Category(3, "kleidia"); Category cat5 = new Category(4, "alla"); IncomeCost cost20 = new IncomeCost(0, cat2, "Μπογιά", 20); IncomeCost cost21 = new IncomeCost(1, cat2, "Τακούνια", 32); IncomeCost cost5 = new IncomeCost(2, cat5, "Δεή", 350); IncomeCost cost4 = new IncomeCost(3, cat4, "Αγορά Κλειδιών", 45); IncomeCost cost01 = new IncomeCost(4, cat1, "Βενζίνη", 10); IncomeCost cost02 = new IncomeCost(5, cat1, "Βενζίνη", 10); IncomeCost cost03 = new IncomeCost(6, cat1, "Βενζίνη", 20); IncomeCost cost04 = new IncomeCost(7, cat1, "Βενζίνη", 10); IncomeCost income11 = new IncomeCost(0, cat2, "Παπούτσια", 22); IncomeCost income12 = new IncomeCost(0, cat2, "Παπούτσια", 13.5); IncomeCost income31 = new IncomeCost(0, cat4, "Κλειδιά", 4.5); IncomeCost income32 = new IncomeCost(0, cat4, "Κλειδαριές", 23.5); PackagesIncome pack = new PackagesIncome(0, cat1, "", 100, 20); System.out.println(pack.getValue()); InOutDB db = new InOutDB(); /*db.saveCategory(cat1); db.saveCategory(cat2); db.saveCategory(cat3); db.saveCategory(cat4); db.saveCategory(cat5); db.saveOut(cost20); db.saveOut(cost21); db.saveOut(cost4); db.saveOut(cost5); db.saveOut(cost01); db.saveOut(cost02); db.saveOut(cost03); db.saveOut(cost04); db.saveIn(income11); db.saveIn(income12); db.saveIn(income31); db.saveIn(income32);*/ //db.savePackIn(pack); System.out.println("Categorys"); System.out.println(db.getCategorys()); System.out.println("In"); System.out.println(db.getIn()); System.out.println("Out"); System.out.println(db.getOut()); System.out.println("Pack"); System.out.println(db.getPackIn()); } }
class Triangulo extends Masdisparejos{ public double Perimetrotriangulo(){ perimetro=lado1+lado2+lado3; return perimetro; } public double Areatriangulo(){ area=(lado1*altura)/2; return area; } }
package controller.payment; import boundary.CreditCardSociety; import model.User; import model.language.payment.PaymentLanguage; import model.payment.*; import view.PaymentForm; import javax.swing.*; import java.awt.*; /** * Created by davidemagnanimi on 06/09/16 at 12:57. */ public class PaymentController { private Transaction transaction; private PaymentObserver observer; public PaymentController(Double amount, User recipient) throws TransactionNotValid { this.transaction = new Transaction(amount, null, recipient.getIban(), Status.Processing); createView(String.format("%.2f", amount)); } private void createView(String amount) { JFrame frame = new JFrame(PaymentLanguage.payment_payment); frame.setContentPane(new PaymentForm(frame, this, amount).getPanelMain()); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public void confirmForm(String cardNumber, String ownerFirstName, String ownerLastName, String expirationDate) { try { CreditCard creditCard = new CreditCard(cardNumber, ownerFirstName, ownerLastName, expirationDate); transaction.setCreditCard(creditCard); if (new CreditCardSociety(transaction).forwardPayment()) setTransactionStatus(Status.Approved); else setTransactionStatus(Status.Failed); } catch (CreditCardCredentialNotValid creditCardCredentialNotValid) { JOptionPane.showMessageDialog(new Frame(), creditCardCredentialNotValid.getMessage()); creditCardCredentialNotValid.printStackTrace(); } } public void attachObserver(PaymentObserver observer) { this.observer = observer; } /* public void detachObserver(){ this.observer = null; } */ public void setTransactionStatus(Status status) { try { this.observer.update(status); this.transaction.setStatus(status); } catch (NullPointerException e) { e.printStackTrace(); } } public Transaction getTransaction() { return transaction; } }
package android.support.v4.util; import android.support.annotation.RestrictTo; import android.support.annotation.RestrictTo.Scope; import java.io.PrintWriter; @RestrictTo({Scope.LIBRARY_GROUP}) public final class TimeUtils { @RestrictTo({Scope.LIBRARY_GROUP}) public static final int HUNDRED_DAY_FIELD_LEN = 19; private static final int SECONDS_PER_DAY = 86400; private static final int SECONDS_PER_HOUR = 3600; private static final int SECONDS_PER_MINUTE = 60; private static char[] sFormatStr = new char[24]; private static final Object sFormatSync = new Object(); private static int accumField(int i, int i2, boolean z, int i3) { int i4 = 3; if (i > 99 || (z && i3 >= i4)) { return i4 + i2; } int i5 = 2; return (i > 9 || (z && i3 >= i5)) ? i5 + i2 : (z || i > 0) ? 1 + i2 : 0; } private static int printField(char[] cArr, int i, char c, int i2, boolean z, int i3) { if (!z && i <= 0) { return i2; } int i4; if ((!z || i3 < 3) && i <= 99) { i4 = i2; } else { int i5 = i / 100; cArr[i2] = (char) (i5 + 48); i4 = i2 + 1; i -= i5 * 100; } if ((z && i3 >= 2) || i > 9 || i2 != i4) { i2 = i / 10; cArr[i4] = (char) (i2 + 48); i4++; i -= i2 * 10; } cArr[i4] = (char) (i + 48); i4++; cArr[i4] = c; return i4 + 1; } private static int formatDurationLocked(long j, int i) { long j2 = j; int i2 = i; if (sFormatStr.length < i2) { sFormatStr = new char[i2]; } char[] cArr = sFormatStr; long j3 = 0; char c = ' '; boolean z = true; boolean z2 = false; int i3; if (j2 == j3) { i3 = i2 - 1; while (i3 > 0) { cArr[z2] = c; } cArr[z2] = '0'; return z; } char c2; int i4; int i5; int i6; int i7; if (j2 > j3) { c2 = '+'; } else { c2 = '-'; j2 = -j2; } long j4 = 1000; int i8 = (int) (j2 % j4); i3 = (int) Math.floor((double) (j2 / j4)); int i9 = 86400; if (i3 > i9) { i4 = i3 / i9; i3 -= i9 * i4; } else { i4 = z2; } if (i3 > 3600) { i9 = i3 / 3600; i3 -= i9 * 3600; } else { i9 = z2; } if (i3 > 60) { i5 = i3 / 60; i6 = i3 - (i5 * 60); i3 = i5; } else { i6 = i3; i3 = z2; } int i10 = 3; int i11 = 2; if (i2 != 0) { i5 = accumField(i4, z, z2, z2); i5 += accumField(i9, z, i5 > 0 ? z : z2, i11); i5 += accumField(i3, z, i5 > 0 ? z : z2, i11); i5 += accumField(i6, z, i5 > 0 ? z : z2, i11); i7 = z2; for (i5 += accumField(i8, i11, z, i5 > 0 ? i10 : z2) + z; i5 < i2; i5++) { cArr[i7] = c; i7++; } } else { i7 = z2; } cArr[i7] = c2; int i12 = i7 + 1; boolean z3 = i2 != 0 ? z : z2; int i13 = i12; int printField = printField(cArr, i4, 'd', i12, false, 0); printField = printField(cArr, i9, 'h', printField, printField != i13 ? z : false, z3 ? i11 : 0); printField = printField(cArr, i3, 'm', printField, printField != i13 ? z : false, z3 ? i11 : 0); printField = printField(cArr, i6, 's', printField, printField != i13 ? z : false, z3 ? i11 : 0); char c3 = 'm'; boolean z4 = true; i12 = (!z3 || printField == i13) ? 0 : i10; i3 = printField(cArr, i8, c3, printField, z4, i12); cArr[i3] = 's'; return i3 + z; } @RestrictTo({Scope.LIBRARY_GROUP}) public static void formatDuration(long j, StringBuilder stringBuilder) { synchronized (sFormatSync) { int i = 0; stringBuilder.append(sFormatStr, i, formatDurationLocked(j, i)); } } @RestrictTo({Scope.LIBRARY_GROUP}) public static void formatDuration(long j, PrintWriter printWriter, int i) { synchronized (sFormatSync) { printWriter.print(new String(sFormatStr, 0, formatDurationLocked(j, i))); } } @RestrictTo({Scope.LIBRARY_GROUP}) public static void formatDuration(long j, PrintWriter printWriter) { formatDuration(j, printWriter, 0); } @RestrictTo({Scope.LIBRARY_GROUP}) public static void formatDuration(long j, long j2, PrintWriter printWriter) { if (j == 0) { printWriter.print("--"); } else { formatDuration(j - j2, printWriter, 0); } } private TimeUtils() { } }