text
stringlengths 10
2.72M
|
|---|
package kxg.searchaf.url.gymboree;
import java.util.ArrayList;
public class GymboreeUtil {
public ArrayList<GymboreeProduct> checkuser(
ArrayList<GymboreeProduct> matchprolist,
GymboreeMailList amail, String ttype) {
ArrayList<GymboreeProduct> usermatch = new ArrayList<GymboreeProduct>();
//babyboy
if ("men".equalsIgnoreCase(ttype) && amail.warningMen) {
for (int i = 0; i < matchprolist.size(); i++) {
GymboreeProduct afProduct = matchprolist.get(i);
if (afProduct.realdiscount <= amail.mencheckingSaleDiscount) {
usermatch.add(afProduct);
}
}
}
//baby girl
if ("women".equalsIgnoreCase(ttype) && amail.warningWomen) {
for (int i = 0; i < matchprolist.size(); i++) {
GymboreeProduct afProduct = matchprolist.get(i);
if (afProduct.realdiscount <= amail.womencheckingSaleDiscount) {
usermatch.add(afProduct);
}
}
}
if ("boy".equalsIgnoreCase(ttype) && amail.warningBoy) {
for (int i = 0; i < matchprolist.size(); i++) {
GymboreeProduct afProduct = matchprolist.get(i);
if (afProduct.realdiscount <= amail.boycheckingSaleDiscount) {
usermatch.add(afProduct);
}
}
}
if ("girl".equalsIgnoreCase(ttype) && amail.warningGirl) {
for (int i = 0; i < matchprolist.size(); i++) {
GymboreeProduct afProduct = matchprolist.get(i);
if (afProduct.realdiscount <= amail.girlcheckingSaleDiscount) {
usermatch.add(afProduct);
}
}
}
return usermatch;
}
}
|
package com.example.threadapp;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class ThirdActivity extends AppCompatActivity {
TextView textView;
Handler handler;
Button thirdButton;
private final int STATUS_NONE = 0;
private final int STATUS_CONNECTING = 1;
private final int STATUS_CONNECTED = 2;
private final int STATUS_DOWNLOAD_START = 3;
private final int STATUS_DOWNLOAD_FILE = 4;
private final int STATUS_DOWNLOAD_STOP = 5;
private final int STATUS_DOWNLOAD_END = 6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
textView = findViewById(R.id.textView2);
thirdButton = findViewById(R.id.button3);
handler = new Handler(){
@Override
public void handleMessage(Message msg){
switch(msg.what){
case STATUS_NONE:
{
thirdButton.setEnabled(true);
textView.setText("Not connected");
break;
}
case STATUS_CONNECTING:
{
thirdButton.setEnabled(false);
textView.setText("Connecting");
break;
}
case STATUS_CONNECTED:
{
thirdButton.setEnabled(true);
textView.setText("Connected");
break;
}
case STATUS_DOWNLOAD_START:
{
thirdButton.setEnabled(true);
textView.setText("Download started " + msg.arg1 + " files");
break;
}
case STATUS_DOWNLOAD_FILE:
{
thirdButton.setEnabled(true);
textView.setText("Downloading " + msg.arg1 + " files. " + "Currently dowloading: " + msg.arg2);
try{
saveFile(msg.obj);
}
catch (Exception e){
e.fillInStackTrace();
}
break;
}
case STATUS_DOWNLOAD_STOP:
{
break;
}
case STATUS_DOWNLOAD_END:
{
break;
}
default:
{
break;
}
}
}
};
}
public void ClickThirdButton(View view)
{
new Thread(new Runnable() {
@Override
public void run() {
try{
byte[] file;
Message msg;
//TODO 1.Connecting and let the thread to sleep for 1 sec
handler.sendEmptyMessage(STATUS_CONNECTING);
TimeUnit.SECONDS.sleep(1);
//TODO 2.Change status to "connected"
handler.sendEmptyMessage(STATUS_CONNECTED);
TimeUnit.SECONDS.sleep(1);
//TODO 3. Determine the amount of files to download
Random random = new Random();
int countFiles = random.nextInt(6);
//TODO 4. If amount of files = 0, send status "none" to handler
if(countFiles == 0){
handler.sendEmptyMessage(STATUS_NONE);
TimeUnit.SECONDS.sleep(1);
return;
}
msg = handler.obtainMessage(STATUS_DOWNLOAD_START, countFiles,0);
handler.sendMessage(msg);
for(int i = 0; i < countFiles; i++){
file = downloadFile();
msg = handler.obtainMessage(STATUS_DOWNLOAD_FILE, countFiles, (i+1), file);
handler.sendMessage(msg);
}
}
catch (Exception e){
}
}
}).start();
}
private byte[] downloadFile() throws Exception{
TimeUnit.SECONDS.sleep(2);
return new byte[2000];
}
private void saveFile(Object file) throws Exception{
TimeUnit.SECONDS.sleep(1);
}
}
|
package com.esum.wp.ims.clientstatlog.dao.impl;
import java.util.List;
import com.esum.appframework.dao.impl.SqlMapDAO;
import com.esum.wp.ims.clientstatlog.dao.IClientStatLogDAO;
public class ClientStatLogDAO extends SqlMapDAO implements IClientStatLogDAO {
protected String selectDailyClientStatLogID = "";
public String getSelectDailyClientStatLogID() {
return selectDailyClientStatLogID;
}
public void setSelectDailyClientStatLogID(String selectDailyClientStatLogID) {
this.selectDailyClientStatLogID = selectDailyClientStatLogID;
}
@Override
public List selectDailyClientStatLog(Object object) {
return getSqlMapClientTemplate().queryForList(selectDailyClientStatLogID, object);
}
}
|
package Models;
/**
* Created by BurakMac on 13/05/15.
*/
public class Requirement {
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//WComponent.java
//Defines an abstract base class for WebTOP components.
//Yong Tze Chi (revised and enhanced by Davis Herring)
//Updated February 3 2002
//Version 2.0
package org.webtop.component;
import java.awt.*;
import javax.swing.*;
public abstract class WComponent extends JPanel {
protected Dimension minSize;
protected Dimension prefSize;
protected Dimension maxSize;
public void setMinimumSize(Dimension size) {
minSize = size==null ? null : new Dimension(size);}
public void setPreferredSize(Dimension size) {
prefSize = size==null ? null : new Dimension(size);}
public void setMaximumSize(Dimension size) {
maxSize = size==null ? null : new Dimension(size);}
public Dimension getMinimumSize() {
return minSize==null ? super.getMinimumSize() : minSize;
}
public Dimension getPreferredSize() {
return prefSize==null ? super.getPreferredSize() : prefSize;
}
public Dimension getMaximumSize() {
return maxSize==null ? super.getMaximumSize() : maxSize;
}
}
|
package com.thecupboardapp.cupboard;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SignInActivity extends AppCompatActivity {
private final String TAG = "SignInActivity";
private FirebaseAuth mAuth;
private String mEmail;
private String mPassword;
private EditText mEmailEditText;
private EditText mPasswordEditText;
private Button mSignInButton;
private Button mCreateAccountButton;
static final int SIGN_IN_RESULT_CODE = 1;
static final int NEW_ACCOUNT_RESULT_CODE = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
mEmail = "";
mPassword = "";
mEmailEditText = (EditText) findViewById(R.id.sign_in_email);
mPasswordEditText = (EditText) findViewById(R.id.sign_in_password);
mSignInButton = (Button) findViewById(R.id.button_sign_in);
mCreateAccountButton = (Button) findViewById(R.id.button_create_account);
mEmailEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mEmail = s.toString();
}
@Override
public void afterTextChanged(Editable s) {}
});
mPasswordEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mPassword = s.toString();
}
@Override
public void afterTextChanged(Editable s) {}
});
mSignInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createAccount();
}
});
}
// Create an intent for this
public static Intent newIntent(Context packageContext) {
Intent intent = new Intent(packageContext, SignInActivity.class);
return intent;
}
// Unit test?
public static boolean verifyEmail(String email){
if (email.contains(Character.toString('@'))
&& email.contains(Character.toString('.'))) return true;
else return false;
}
// If the fields are good, they wil
private boolean verifyFields() {
// Check if email field or password is filled out
if (TextUtils.isEmpty(mEmail) || TextUtils.isEmpty(mPassword)) {
Toast.makeText(this, "Please enter all fields!", Toast.LENGTH_SHORT).show();
return false;
} else if (!Patterns.EMAIL_ADDRESS.matcher(mEmail).matches()) {
Toast.makeText(this, "Invalid email address", Toast.LENGTH_SHORT).show();
return false;
} else if (mPassword.length() < 8) {
Toast.makeText(this, "Password must be 8 characters long",
Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void signIn() {
// check the fields
if (!verifyFields()) {
return;
}
mAuth.signInWithEmailAndPassword(mEmail, mPassword)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
UserData.get(SignInActivity.this).updateFromFirebase();
setResult(SIGN_IN_RESULT_CODE);
finish();
} else {
Toast.makeText(SignInActivity.this, task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
private void createAccount(){
// check the fields
if (!verifyFields()) {
return;
}
mAuth.createUserWithEmailAndPassword(mEmail, mPassword).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
setResult(NEW_ACCOUNT_RESULT_CODE);
finish();
} else {
Toast.makeText(SignInActivity.this, task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
}
|
package com.rengu.operationsoanagementsuite.Service;
import com.rengu.operationsoanagementsuite.Entity.DeviceEntity;
import com.rengu.operationsoanagementsuite.Utils.Utils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.*;
import java.util.Arrays;
@Service
public class UDPService {
public void sandMessage(InetAddress inetAddress, int port, String message) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
DatagramPacket datagramPacket = new DatagramPacket(message.getBytes(), message.length(), socketAddress);
datagramSocket.send(datagramPacket);
datagramSocket.close();
}
public void sandMessage(String hostName, int port, String message) throws IOException {
InetAddress inetAddress = InetAddress.getByName(hostName);
sandMessage(inetAddress, port, message);
}
public void sendHeartbeatBroadcastMessage(InetAddress inetAddress, int port, InterfaceAddress interfaceAddress) throws IOException {
String message = ("S101" + interfaceAddress.getAddress().toString()).replace("/", "");
sandMessage(inetAddress, port, message);
}
public void sendScanDeviceOrderMessage(String id, String ip, int port, String deviceId, String componentId, String path) throws IOException {
String codeType = Utils.getString("S102", 4);
id = Utils.getString(id, 37);
deviceId = Utils.getString(deviceId, 37);
componentId = Utils.getString(componentId, 37);
path = Utils.getString(path, 256);
sandMessage(ip, port, codeType + id + deviceId + componentId + path);
}
public void sendScanDeviceOrderMessage(String id, String ip, int port, String deviceId, String componentId, String path, String[] extensions) throws IOException {
String codeType = Utils.getString("S103", 4);
id = Utils.getString(id, 37);
deviceId = Utils.getString(deviceId, 37);
componentId = Utils.getString(componentId, 37);
String extension = Utils.getString(Arrays.toString(extensions).replace("[", "").replace("]", "").replaceAll("\\s*", ""), 128);
path = Utils.getString(path, 256);
sandMessage(ip, port, codeType + id + deviceId + componentId + extension + path);
}
public void sendGetDeviceTasksMessage(String id, DeviceEntity deviceEntity) throws IOException {
String codeType = Utils.getFixedLengthString("S105", 4);
String type = Utils.getFixedLengthString("1", 1);
id = Utils.getFixedLengthString(id, 37);
sandMessage(deviceEntity.getIp(), deviceEntity.getUDPPort(), codeType + type + id);
}
public void sendGetDeviceDisksMessage(String id, DeviceEntity deviceEntity) throws IOException {
String codeType = Utils.getFixedLengthString("S105", 4);
String type = Utils.getFixedLengthString("2", 1);
id = Utils.getFixedLengthString(id, 37);
sandMessage(deviceEntity.getIp(), deviceEntity.getUDPPort(), codeType + type + id);
}
}
|
package example;
public class UsbDiskWriter implements IDeviceWriter {
public String saveToDevice() {
return "save-to-usb";
}
}
|
package com.freddygenicho.mpesa.stkpush.interfaces;
import com.freddygenicho.mpesa.stkpush.model.Token;
public interface TokenListener {
void onTokenSuccess(Token token);
void OnTokenError(Throwable throwable);
}
|
/*
package tm.controller;
import org.apache.tiles.preparer.ViewPreparer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.view.tiles3.SpringBeanPreparerFactory;
import tm.pojo.PageParams;
import javax.servlet.ServletContext;
@Controller
@RequestMapping("/pageNum")
public class PageNumController extends SpringBeanPreparerFactory{
private PageParams pageParams;
private int begin;
private int end;
@Autowired
public void setPageParams(PageParams pageParams) {
this.pageParams = pageParams;
}
public ViewPreparer getViewPreparer(ServletContext sc){
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
return getPreparer("pageParams",context);
}
@RequestMapping(value = "/{num}",method = RequestMethod.GET)
public String pageNum(Model model ,@PathVariable("num") int num){
pageParams.setPage(num);
int totalPage = pageParams.getTotalPage();
begin = 1;
end = totalPage;
if(num > 4){
begin = num - 4;
}
if (num <= totalPage - 5) {
end = num + 5;
}
model.addAttribute("begin",begin);
model.addAttribute("end",end);
model.addAttribute("now",num);
return "pageNum";
}
}
*/
|
package com.example.demo.models.service.estadosolicitud;
import com.example.demo.models.dao.DIEstadoSolicitud;
import com.example.demo.models.entity.EstadoSolicitud;
import com.example.demo.models.entity.EstadoSolicitudPK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class SEstadoSolicitudImpl implements SIEstadoSolicitud {
@Autowired
private DIEstadoSolicitud estadoSolicitudDao;
@Override
public void save(EstadoSolicitud estadoSolicitud) {
estadoSolicitudDao.save(estadoSolicitud);
}
@Override
public List<EstadoSolicitud> findAll() {
return (List<EstadoSolicitud>) estadoSolicitudDao.findAll();
}
@Override
public EstadoSolicitud findOne(EstadoSolicitudPK id) {
return estadoSolicitudDao.findById(id).orElse(null);
}
@Override
public List<EstadoSolicitud> findAllByIdEstadoSolicitudBySolicitud(Long id) {
return estadoSolicitudDao.findAllByIdEstadoSolicitudBySolicitud(id);
}
}
|
package com.jd.jarvisdemonim.ui.testfragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.TextView;
import com.jd.jarvisdemonim.R;
import com.jd.jdkit.elementkit.fragment.DBaseFragment;
import com.jd.jdkit.reminder.ReminderManager;
/**
* Auther: Jarvis Dong
* Time: on 2017/1/6 0006
* Name:
* OverView:
* Usage:
*/
public class TabCarFragment extends DBaseFragment implements CalendarView.OnDateChangeListener {
private static String KEY = "key";
private CalendarView carlendar;
private TextView txtOne;
public static TabCarFragment newInstance(String key) {
TabCarFragment fragment = new TabCarFragment();
Bundle bun = new Bundle();
bun.putString(KEY, key);
fragment.setArguments(bun);
return fragment;
}
@Override
protected View initXml(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return mInflater.inflate(R.layout.fragment__text_carlendar, container, false);
}
@Override
protected void initView(View view, @Nullable Bundle savedInstanceState) {
txtOne = (TextView) view.findViewById(R.id.text_one);
carlendar = (CalendarView) view.findViewById(R.id.carlendar);
txtOne.setText(String.valueOf(System.currentTimeMillis()));
((Button) view.findViewById(R.id.button_one)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ReminderManager.getInstance().upDateUnReadNum(998, true, 1);
}
});
}
@Override
protected void processLogic(Bundle savedInstanceState) {
}
@Override
protected void initListener() {
carlendar.setOnDateChangeListener(this);
}
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
txtOne.setText(String.valueOf(year + month - 1 + dayOfMonth));
}
}
|
package ca.usask.cs.srlab.simclipse.ui.view.clone;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IViewPart;
import ca.usask.cs.srlab.simclipse.SimClipsePlugin;
public class CloneViewContentProvider implements ITreeContentProvider, CloneViewManagerListener {
private TreeViewer viewer;
private CloneViewManager manager;
private final Object[] EMPTY_ARRAY= new Object[0];
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
this.viewer = (TreeViewer) viewer;
if (manager != null)
manager.removeCloneViewManagerListener(this);
manager = (CloneViewManager) newInput;
if (manager != null)
manager.addCloneViewManagerListener(this);
}
@Override
public Object[] getElements(Object parent) {
IViewPart cloneView = SimClipsePlugin.getViewIfExists(CloneView.ID);
if (cloneView == null || parent.equals(cloneView.getViewSite())
|| (parent instanceof CloneViewManager) ) {
return manager.getCloneViewItems();
}
return getChildren(parent);
}
@Override
public Object[] getChildren(Object parentElement) {
if(parentElement instanceof ICloneViewItem
&& hasChildren(parentElement) ) {
return ((ICloneViewItem) parentElement).getChildren().toArray();
}
return EMPTY_ARRAY;
}
@Override
public Object getParent(Object child) {
if(child instanceof ICloneViewItem) {
return ((ICloneViewItem)child).getParent();
}
return null;
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof ICloneViewItem)
return ((ICloneViewItem) element).getChildren() != null
&& ((ICloneViewItem) element).getChildren().size() > 0;
return false;
}
@Override
public void executeEvent(CloneViewEvent event) {
viewer.getTree().setRedraw(false);
try {
viewer.getTree().clearAll(true);
viewer.setInput(event.getSource());
viewer.expandAll();
//viewer.refresh(event.getItemsToDisplay(), false);
} finally {
viewer.getTree().setRedraw(true);
}
}
}
|
package com.dokyme.alg4.sorting.application;
import com.dokyme.alg4.sorting.Sorting;
import com.dokyme.alg4.sorting.priorityqueue.MaxHeap;
import static com.dokyme.alg4.sorting.basic.Example.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Created by intellij IDEA.But customed by hand of Dokyme.
*
* @author dokym
* @date 2018/5/31-21:03
* Description:
*/
public class StableMaxHeap<T extends Comparable<T>> implements Sorting {
private int sid = 0;
private class Element implements Comparable<Element> {
private int index;
private T val;
public Element(T val, int index) {
this.val = val;
this.index = index;
}
@Override
public int compareTo(Element o) {
int cmp = val.compareTo(o.val);
if (cmp != 0) {
return 0;
}
return index - o.index;
}
}
private Element[] pq;
private int size;
public StableMaxHeap(T[] array) {
// pq = new Element[array.length + 1];
for (int i = 0; i < array.length; i++) {
// pq[i + 1] = new Element<>(array[i], sid++);
}
size = array.length;
for (int i = size / 2; i > 0; i--) {
sink(i);
}
}
public StableMaxHeap(int size) {
this.size = size;
}
@Override
public void sort(Comparable[] a, Comparator c) {
}
@Override
public void sort(Comparable[] array) {
// pq = new Element[array.length + 1];
for (int i = 0; i < array.length; i++) {
// pq[i + 1] = new Element<>(array[i], sid++);
}
size = array.length;
for (int i = size / 2; i > 0; i--) {
sink(i);
}
int n = size;
while (n > 1) {
exch(1, n--);
sink(1);
}
for (int i = 0; i < array.length; i++) {
array[i] = pq[i + 1].val;
}
}
public void insert(T data) {
size++;
if (size == pq.length - 1) {
resize(size * 2);
}
pq[size] = new Element(data, sid++);
swim(size);
}
public T max() {
return pq[1].val;
}
public T delMax() {
T data = pq[1].val;
pq[1] = pq[size];
pq[size--] = null;
sink(1);
return data;
}
private void swim(int i) {
while (i > 1 && less(i / 2, i)) {
exch(i, i / 2);
i /= 2;
}
}
private void sink(int i) {
while (2 * i <= size) {
int k = 2 * i;
if (k < size && less(k, k + 1)) {
k++;
}
if (less(k, i)) {
break;
}
exch(i, k);
i = k;
}
}
private void exch(int i, int j) {
Element e = pq[i];
pq[i] = pq[j];
pq[j] = e;
}
private boolean less(int i, int j) {
return pq[i].val.compareTo(pq[j].val) < 0;
}
private void resize(int newSize) {
Element[] newPQ = null;
System.arraycopy(pq, 1, newPQ, 1, size);
pq = newPQ;
}
public static void main(String[] args) {
testSorting(new StableMaxHeap<>(10));
String[] strArray = new String[10];
Object[] objArray = strArray;
List<String> li = new ArrayList();
}
}
|
public class Employee
{
private String name =" ";
private int idnumber = 0;
private String department = " ";
private String position =" ";
public Employee (String name, int idnumber, String department, String position)
{
this.name = name;
this.idnumber = idnumber;
this.department = department;
this.position = position;
}
public Employee(String name, int idnumber)
{
this.name = name;
this.idnumber = idnumber;
}
public Employee()
{
}
public String toString()
{
return this.name + "," + this.idnumber + "," + this.department + "," + this.position;
}
}
|
package com.insurance.quote.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.insurance.quote.entity.Accounts;
import com.insurance.quote.entity.Bussiness_Segment;
import com.insurance.quote.entity.Policy;
import com.insurance.quote.entity.Policy_Questions;
import com.insurance.quote.entity.User_Role;
import com.insurance.quote.utils.DatabaseConnection;
import com.insurance.quote.utils.InsuranceDBQueries;
public class InsuranceDaoImpl implements InsuranceDao{
private Connection conn;
private PreparedStatement pst;
private ResultSet rs;
@Override
public int CreateProfile(User_Role profile) {
// TODO Auto-generated method stub
conn=DatabaseConnection.getConnection();
int rows=0;
try {
pst=conn.prepareStatement(InsuranceDBQueries.ADDPROFILE);
pst.setString(1,profile.getUser_Name());
pst.setString(2,profile.getPassword());
pst.setString(3,profile.getRole_Code());
rows=pst.executeUpdate();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DatabaseConnection.closeConnection();
}
return rows;
}
@Override
public int CreateAccount(Accounts account) {
// TODO Auto-generated method stub
conn=DatabaseConnection.getConnection();
int rows=0;
try {
pst=conn.prepareStatement(InsuranceDBQueries.ADDACCOUNT);
pst.setInt(1,account.getAccount_Number());
pst.setString(2,account.getInsured_Name());
pst.setString(3,account.getInsured_Street());
pst.setString(4,account.getInsured_City());
pst.setString(5,account.getInsured_State());
pst.setInt(6,account.getInsured_Zip());
pst.setString(7,account.getBusiness_Segment());
pst.setString(8,account.getUser_Name());
rows=pst.executeUpdate();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DatabaseConnection.closeConnection();
}
return rows;
}
@Override
public int CreatePolicy(Policy policy) {
// TODO Auto-generated method stub
conn=DatabaseConnection.getConnection();
int rows=0;
try {
pst=conn.prepareStatement(InsuranceDBQueries.ADDPOLICY);
pst.setInt(1,policy.getPolicy_Number());
pst.setInt(2,policy.getPolicy_Premium());
pst.setLong(3,policy.getAccount_Number());
rows=pst.executeUpdate();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DatabaseConnection.closeConnection();
}
return rows;
}
@Override
public User_Role getUser(String userId) {
// TODO Auto-generated method stub
User_Role user=new User_Role();
conn=DatabaseConnection.getConnection();
try {
pst=conn.prepareStatement(InsuranceDBQueries.GETUSER);
pst.setString(1,userId);
rs=pst.executeQuery();
while(rs.next()) {
user.setUser_Name(rs.getString(1));
user.setPassword(rs.getString(2));
user.setRole_Code(rs.getString(3));
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DatabaseConnection.closeConnection();
}
return user;
}
@Override
public List<Policy_Questions> getPolicy_Questions(Bussiness_Segment Bus_Seg_Id) {
// TODO Auto-generated method stub
List<Policy_Questions> lis=new ArrayList<Policy_Questions>();
conn=DatabaseConnection.getConnection();
try {
PreparedStatement bus=conn.prepareStatement(InsuranceDBQueries.GETBUSID);
bus.setString(1, Bus_Seg_Id.getBus_Seg_Id());
pst=conn.prepareStatement(InsuranceDBQueries.GETPOLICY);
pst.setString(1,Bus_Seg_Id.getBus_Seg_Name() );
rs=pst.executeQuery();
while(rs.next()) {
Policy_Questions pol=new Policy_Questions();
pol.setPol_Ques_Desc(rs.getString(1));
pol.setPol_Ques_Ans1(rs.getString(2));
pol.setPol_Ques_Ans1_weightage(rs.getInt(3));
pol.setPol_Ques_Ans2(rs.getString(4));
pol.setPol_Ques_Ans2_weightage(rs.getInt(5));
pol.setPol_Ques_Ans3(rs.getString(6));
pol.setPol_Ques_Ans3_weightage(rs.getInt(7));
pol.setPol_Ques_Ans4(rs.getString(8));
pol.setPol_Ques_Ans4_weightage(rs.getInt(9));
lis.add(pol);
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DatabaseConnection.closeConnection();
}
return lis;
}
}
|
package net.davoleo.javagui.forms.controls;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class JMultiListGui extends JFrame {
private JList leftList, rightList;
private JButton moveButton;
private static String[] food = {"bacon", "wings", "ham", "beef", "more bacon"};
public JMultiListGui()
{
super("Multi-List");
setLayout(new FlowLayout());
leftList = new JList(food);
leftList.setVisibleRowCount(3);
leftList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(leftList));
moveButton = new JButton("Copy =>");
moveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
rightList.setListData(leftList.getSelectedValuesList().toArray());
}
});
add(moveButton);
rightList = new JList();
rightList.setVisibleRowCount(3);
rightList.setFixedCellWidth(100);
rightList.setFixedCellHeight(15);
rightList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
add(new JScrollPane(rightList));
}
}
|
package com.example.android.geoquizstudyguide;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.LinearLayoutManager;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private List<Question> questions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialData();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new QuestionAdapter (questions,this));
}
private void initialData(){
questions = new ArrayList<>();
questions.add(new Question(R.string.europe, R.string.question_europe, R.drawable.europe,true));
questions.add(new Question(R.string.ocean,R.string.question_ocean,R.drawable.oceans,false));
questions.add(new Question(R.string.asia,R.string.question_asia,R.drawable.asia,true));
questions.add(new Question(R.string.americas, R.string.question_americas, R.drawable.americas,false));
questions.add(new Question(R.string.city,R.string.question_city,R.drawable.rome,false));
questions.add(new Question(R.string.river,R.string.question_river,R.drawable.river,true));
}
}
|
package com.offbeat.apps.tasks.Utils;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.offbeat.apps.tasks.R;
public class Utils {
Context mContext;
public Utils(Context mContext) {
this.mContext = mContext;
}
public static void setTypeFace(Context context) {
FontsOverride.setDefaultFont(context, "DEFAULT", "font/prod_sans_regular.ttf");
FontsOverride.setDefaultFont(context, "MONOSPACE", "font/prod_sans_regular.ttf");
FontsOverride.setDefaultFont(context, "SERIF", "font/prod_sans_regular.ttf");
FontsOverride.setDefaultFont(context, "SANS_SERIF", "font/prod_sans_regular.ttf");
}
public static void setWindowFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
public static void setLightStatusBar(Context context, View view, Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
activity.getWindow().setStatusBarColor(context.getColor(R.color.colorPrimary));
}
}
}
|
package com.boge.controller;
import com.boge.service.MessageService;
import com.boge.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by boge on 2018/1/12.
*/
@RestController
@EnableAutoConfiguration
@RequestMapping(value = "/wechat")
public class WeChatController {
private static Logger log = LoggerFactory.getLogger(WeChatController.class);
@Autowired
private MessageService messageService;
@RequestMapping(value = "/checkSignature")
public String checkSignature(@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "echostr", required = false) String echostr, HttpServletRequest request, HttpServletResponse response) {
//设置中文编码格式
response.setHeader("Content-type", "text/html;charset=UTF-8");
try {
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
log.info("接入成功");
String result = messageService.analyMessage(request);
response.getWriter().write(result);
return echostr;
}
} catch (Exception e) {
log.error("接入失败");
}
return "";
}
@RequestMapping(value = "/receiveTextMessage")
public String receiveTextMessage(HttpServletRequest request) {
String result = "";
try {
result = messageService.receiveTextMessage(request);
} catch (Exception e) {
log.error("receiveTxtMessage()", e);
}
return result;
}
}
|
package xyz.spacexplorer.utils;
public class Result extends BaseEntity {
private static final long serialVersionUID = -6547341289120281153L;
public static final String SUCCESS_CODE = "0";
public static final String FAILE_CODE = "1";
private String retCode;
private String retMessage;
public Result() {
}
public Result(String retCode, String retMessage) {
super();
this.retCode = retCode;
this.retMessage = retMessage;
}
public String getRetCode() {
return retCode;
}
public void setRetCode(String retCode) {
this.retCode = retCode;
}
public String getRetMessage() {
return retMessage;
}
public void setRetMessage(String retMessage) {
this.retMessage = retMessage;
}
public boolean isSuccess() {
if (SUCCESS_CODE.equals(getRetCode())) {
return true;
} else if ("200".equals(getRetCode())) {
return true;
} else {
return false;
}
}
}
|
package ch.ffhs.ftoop.doppelgruen.quiz.game;
/** Representations for all the valid locations for the game where the player could be. */
public enum Location {
LOBBY,
LOOKING_FOR_GAME,
INGAME
}
|
package com.DataDriven_NewTours;
import org.testng.annotations.Test;
public class xmlDemo {
@Test
public void DisplayResult() {
System.out.println("Hello welcome to selenium world");
}
}
|
package com.bcq.oklib.net.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
import com.bcq.oklib.net.listener.refresh.OnLoadListener;
import com.bcq.oklib.net.listener.refresh.OnRefreshListener;
/**
* @author: BaiCQ
* @className: BaseListView
* @Description: 所有刷新listview的基类
*/
public class BaseListView extends ListView {
public BaseListView(Context context) {
super(context);
}
public BaseListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 刷新结束
*/
public void onRefreshComplete() {}
/**
* 刷新监听
* @param onRefreshListener
*/
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {}
/*
* load 结束
*/
public void onLoadComplete() {}
/**
* load 监听
* @param onRefreshListener
*/
public void setOnLoadListener(OnLoadListener onRefreshListener) {}
/**
* 设置loadFull
* @param isLoadFull
*/
public void setLoadFull(boolean isLoadFull) {}
}
|
package com.servlets;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import com.beans.DeliveryService;
import com.entities.DeliveryOrder;
import com.entities.DeliveryProduct;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.utils.Utils;
/**
* Servlet implementation class Deliver
*/
@WebServlet("/DeliverOrder")
public class Deliver extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
DeliveryService bean;
/**
* @see HttpServlet#HttpServlet()
*/
public Deliver() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Deliver!");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
DeliveryOrder deliveryOrder = gson.fromJson(request.getReader(), DeliveryOrder.class);
boolean deliveryCreated = false;
if ( deliveryOrder.getProducts() != null) {
deliveryCreated = bean.deliver( deliveryOrder.getDestin_address(), deliveryOrder.getProducts());
}
else {
deliveryCreated = false;
}
if ( deliveryCreated ) {
response.getWriter().append( Boolean.toString( deliveryCreated ) );
}
else {
response.setStatus( response.SC_INTERNAL_SERVER_ERROR );
response.getWriter().append( "No se creó el delivery" );
}
}
}
|
import java.io.Console;
import java.math.BigInteger;
public class HashMap<Key, Value> {
private boolean quadratic = false; // Use quadratic probing
private boolean exactSize = false; // Don't round capacity up to next prime
private double maxLoad = 0.5; // Load factor at which table is resized
private int compares = 0; // Number of equality tests
private int searches = 0; // Number of search operations
private int capacity;
private int size;
private Key[] keys;
private Value[] values;
private int nextPrime(int n) { // Returns next prime number following n
return BigInteger.valueOf(n).nextProbablePrime().intValue();
}
public HashMap(int capacity, boolean quadratic, boolean exactSize) {
if (!exactSize) {
capacity = nextPrime(capacity);
}
this.quadratic = quadratic;
this.exactSize = exactSize;
this.keys = (Key[]) new Object[capacity];
this.values = (Value[]) new Object[capacity];
this.capacity = capacity;
this.size = size;
}
public HashMap(int capacity) {
this(capacity, false, false);
}
public HashMap() {
this(16, false, false);
}
public int capacity() {
return this.capacity;
}
public int size() {
return this.size;
}
public boolean isEmpty() {
return this.size == 0;
}
private int hash(Key key) {
return (key.hashCode() & 0x7FFFFFFF) % this.capacity;
}
private void resize(int capacity) {
Key[] oldKeys = this.keys;
Value[] oldValues = this.values;
this.keys = (Key[]) new Object[capacity];
this.values = (Value[]) new Object[capacity];
this.capacity = capacity;
this.size = 0;
for (int i = 0; i < oldKeys.length; i++) {
if (oldKeys[i] != null) {
add(oldKeys[i], oldValues[i]);
}
}
}
private void resize() {
if (this.exactSize) {
resize(2 * this.capacity);
} else {
resize(nextPrime(2 * this.capacity));
}
}
private int locate(Key key) {
int index = hash(key);
int step = 1;
while (this.keys[index] != null && !this.keys[index].equals(key)) {
index = Math.abs(index + step) % this.capacity;
if (this.quadratic) {
step *= 2;
}
this.compares++;
}
this.compares++;
this.searches++;
return index;
}
public boolean contains(Key key) {
int index = locate(key);
return this.keys[index] != null;
}
public Value find(Key key) {
int index = locate(key);
return this.values[index];
}
public void add(Key key, Value value) {
if (loadFactor() > this.maxLoad) {
resize();
}
int index = locate(key);
if (this.keys[index] == null) {
this.keys[index] = key;
}
this.values[index] = value;
this.size++;
}
public void remove(Key key) {
int index = hash(key);
int step = 1;
while (keys[index] != null & !keys[index].equals(key)) {
index = (index + step) % this.capacity;
if (this.quadratic) {
step *= 2;
}
}
keys[index] = null;
values[index] = null;
this.size--;
index = (index + step) % this.capacity;
if (this.quadratic) {
step *= 2;
}
while (keys[index] != null) {
Key savedKey = keys[index];
Value savedValue = values[index];
keys[index] = null;
values[index] = null;
this.size--;
index = (index + step) % this.capacity;
if (this.quadratic) {
step *= 2;
}
add(savedKey, savedValue);
}
}
public void print() {
for (int i = 0; i < this.capacity; i++) {
System.out.print(i);
System.out.print(": ");
if (keys[i] != null) {
System.out.print(keys[i]);
System.out.print(" => ");
System.out.print(values[i]);
}
System.out.println();
}
}
private int next(int index) {
return (++index < this.capacity) ? index : 0;
}
private int nextCluster(int index) {
while (this.keys[index] != null) {
index = next(index);
}
while (this.keys[index] == null) {
index = next(index);
}
return index;
}
private int clusterLength(int start) {
int index = start;
while (this.keys[index] != null) {
index = next(index);
}
if (index >= start) {
return index - start;
} else {
return index + this.capacity - start;
}
}
public int numberClusters() {
int count = 0;
if (this.size > 0) {
int start = nextCluster(0);
int index = start;
do {
index = nextCluster(index);
count++;
} while (index != start);
}
return count;
}
public int largestClusterSize() {
int max = 0;
if (this.size > 0) {
int start = nextCluster(0);
int index = start;
do {
int length = clusterLength(index);
if (length > max) {
max = length;
}
index = nextCluster(index);
} while (index != start);
}
return max;
}
public double averageClusterSize() {
int total = 0;
int count = 0;
if (this.size > 0) {
int start = nextCluster(0);
int index = start;
do {
total += clusterLength(index);
index = nextCluster(index);
count++;
} while (index != start);
}
if (count > 0) {
return (double) total / (double) count;
} else {
return 0.0;
}
}
public double loadFactor() {
if (this.capacity > 0) {
return (double) this.size / (double) this.capacity;
} else {
return 0.0;
}
}
public int searches() {
return this.searches;
}
public int compares() {
return this.compares;
}
public double averageCompares() {
if (this.searches > 0) {
return (double) this.compares / (double) this.searches;
} else {
return 0.0;
}
}
private static String getArgument(String line, int index) {
String[] words = line.split("\\s");
return words.length > index ? words[index] : "";
}
private static String getCommand(String line) {
return getArgument(line, 0);
}
private void printStatistics() {
System.out.println("Size = " + this.size());
System.out.println("Capacity = " + this.capacity());
System.out.println("Searches = " + this.searches());
System.out.println("Compares = " + this.compares());
System.out.println("Load factor = " + this.loadFactor());
System.out.println("Number clusters = " + this.numberClusters());
System.out.println("Average cluster size = " + this.averageClusterSize());
System.out.println("Largest cluster size = " + this.largestClusterSize());
System.out.println("Average compares per search = " + this.averageCompares());
}
public static void main(String[] args) {
HashMap<String, String> map = null;
Console console = System.console();
boolean statistics = false;
boolean quadratic = false;
boolean exact = false;
int capacity = 16;
double load = 0.5;
String option = "";
if (console == null) {
System.err.println("No console");
return;
}
// Command line options:
//
// -prime Round capacity up to the next prime number
// -exact Don't round capacity up to the next prime
// -linear Use linear probing
// -quadratic Use quadric probing
// -capacity <n> Initial capacity of the hash table
// -load <x> Load factor at which table is resized
// -statistics Print statistics when done
// key (key, "") is added to the map
//
for (String arg : args) {
switch (arg) {
case "-prime":
exact = false;
continue;
case "-exact":
exact = true;
continue;
case "-linear":
quadratic = false;
continue;
case "-quadratic":
quadratic = true;
continue;
case "-capacity":
option = arg;
continue;
case "-load":
option = arg;
continue;
case "-statistics":
statistics = true;
continue;
default:
break;
}
switch (option) {
case "-capacity":
try {
capacity = Integer.parseInt(arg);
} catch (NumberFormatException e) {
System.err.println("Invalid capacity: " + arg);
continue;
}
break;
case "-load":
try {
load = Double.parseDouble(arg);
} catch (NumberFormatException e) {
System.err.println("Invalid load factor: " + arg);
continue;
}
break;
default:
if (map == null) {
map = new HashMap<String, String>(capacity, quadratic, exact);
map.maxLoad = load;
}
map.add(arg, "");
break;
}
option = "";
}
// Allow the user to enter commands on standard input:
//
// hash <key> prints the hash index for a given key
// contains <key> prints true if a key is in the map; false if not
// find <key> prints the value associated with the key
// add <key> <value> adds an item to the tree
// remove <key> removes an item from the tree (if present)
// clear removes all items from the tree
// print prints the contents of the hash table
// clusters prints the number of clusters in the map
// average prints the average cluster size
// largest prints the largest cluster size
// load prints the load factor
// linear use linear probing**
// quadratic use quadratic probing**
// prime round up capacity to a prime**
// exact use exact capacity (don't round up to a prime)**
// exit quit the program
//
// ** takes effect on the next clear command.
if (map == null) {
map = new HashMap<String, String>(capacity, quadratic, exact);
map.maxLoad = load;
}
String line = console.readLine("Command: ").trim();
while (line != null) {
String command = getCommand(line);
switch (command) {
case "hash":
System.out.println(map.hash(getArgument(line, 1)));
break;
case "size":
System.out.println(map.size());
break;
case "capacity":
System.out.println(map.capacity());
break;
case "contains":
System.out.println(map.contains(getArgument(line, 1)));
break;
case "find":
System.out.println(map.find(getArgument(line, 1)));
break;
case "add":
case "insert":
map.add(getArgument(line, 1), getArgument(line, 2));
break;
case "delete":
case "remove":
map.remove(getArgument(line, 1));
break;
case "print":
map.print();
break;
case "clear":
map = new HashMap<>(capacity, quadratic, exact);
break;
case "stats":
case "statistics":
map.printStatistics();
break;
case "linear":
quadratic = false;
break;
case "quadratic":
quadratic = true;
break;
case "prime":
exact = false;
break;
case "exact":
exact = true;
break;
case "end":
case "exit":
case "quit":
if (statistics) {
map.printStatistics();
}
return;
default:
System.out.println("Invalid command: " + command);
break;
}
line = console.readLine("Command: ").trim();
}
}
}
|
package StackAndQueue.WindowMaxValue;
import java.util.LinkedList;
/**
* @author zjbao123
* @version 1.0
* @since 2020-08-30 22:31:08
*/
public class WindowMaxValue {
public static int[] getWindowMaxValue(int[] arr, int w) {
if(arr == null || w < 1 || arr.length < w){
return null;
}
int n = arr.length;
int[] values = new int[n - w+1];
int index= 0;
int i = 0;
int count = 0;
LinkedList<Integer> qMax = new LinkedList<>();
while(i < n){
while(!qMax.isEmpty() && arr[qMax.peekLast()] <= arr[i]) {
qMax.pollLast();
}
qMax.addLast(i);
if(qMax.peekFirst() == i-w){
qMax.pollFirst();
}
if(i >= w-1){
values[index++] = arr[qMax.peekFirst()];
}
i++;
}
return values;
}
}
|
package com.atlassian.connector.intellij.remoteapi;
import com.atlassian.connector.commons.api.ConnectionCfg;
import com.atlassian.connector.intellij.util.HttpClientFactory;
import com.atlassian.theplugin.commons.cfg.ServerId;
import com.atlassian.theplugin.commons.exception.HttpProxySettingsException;
import com.atlassian.theplugin.commons.remoteapi.rest.AbstractHttpSession;
import com.atlassian.theplugin.commons.remoteapi.rest.HttpSessionCallbackImpl;
import com.atlassian.theplugin.idea.BugReporting;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author Wojciech Seliga, Piotr Maruszak
*/
public class IntelliJHttpSessionCallbackImpl extends HttpSessionCallbackImpl {
private static final String USER_AGENT = "Atlassian Connector for IntelliJ/" + BugReporting.getVersionString();
private final Map<String, HttpClient> httpClients =
Collections.synchronizedMap(new HashMap<String, HttpClient>());
public HttpClient getHttpClient(ConnectionCfg server) throws HttpProxySettingsException {
if (httpClients.get(server.getId()) == null) {
final HttpClient client = HttpClientFactory.getClient();
client.getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
client.getParams().setParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1048576);
httpClients.put(server.getId(), client);
}
return httpClients.get(server.getId());
}
@Override
public void configureHttpMethod(AbstractHttpSession session, HttpMethod method) {
super.configureHttpMethod(session, method);
}
public void disposeClient(ConnectionCfg server) {
httpClients.remove(server.getId());
}
public void disposeClient(ServerId serverId) {
String toRemove = null;
for (String id : httpClients.keySet()) {
if (id.equals(serverId.toString())) {
toRemove = id;
break;
}
}
if (toRemove != null) {
httpClients.remove(toRemove);
}
}
public Cookie[] getCookiesHeaders(ConnectionCfg server) {
Cookie[] cookies = new Cookie[0];
if (httpClients.containsKey(server.getId())) {
cookies = httpClients.get(server.getId()).getState().getCookies();
}
return cookies;
}
}
|
package net.mv.app;
import javax.ejb.Stateless;
@Stateless(name="calculate")
public class Calculator implements CalculatorRemote {
public Calculator(){
}
@Override
public double add(double first, double second) {
return first+second;
}
@Override
public double power(double first, double second) {
return Math.pow(first, second);
}
@Override
public double areaCircle(double diameter) {
return Math.PI * Math.pow((diameter/2), 2);
}
}
|
package com.example.httptestapp.http;
import android.content.Context;
import android.util.Log;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.navercorp.volleyextensions.volleyer.builder.PostBuilder;
import com.navercorp.volleyextensions.volleyer.builder.PutBuilder;
import com.navercorp.volleyextensions.volleyer.factory.DefaultRequestQueueFactory;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import static com.navercorp.volleyextensions.volleyer.Volleyer.volleyer;
/**
* Created by JongHunLee on 2015-04-24.
*/
public class HttpQueue implements Response.Listener<String>, Response.ErrorListener {
//Constants
public static final int GET = 0;
public static final int POST = 1;
public static final int PUT = 2;
public static final int DELETE = 3;
public final String APPLICATION_JSON = "application/json";
//Request Parameters
private final Context context;
private final int returnCode;
private final int methodType;
private final String url;
private final Map<String, String> paramsMap;
private final Map<String, File> fileMap;
private HttpQueueListener listener;
private RequestQueue requestQueue;
public HttpQueue(Builder builder) {
this.context = builder.context;
this.returnCode = builder.returnCode;
this.methodType = builder.methodType;
this.url = builder.url;
this.paramsMap = builder.paramsMap;
this.fileMap = builder.fileMap;
this.listener = builder.listener;
requestQueue = DefaultRequestQueueFactory.create(context);
requestQueue.start();
volleyer(requestQueue).settings().setAsDefault().done();
}
public static class Builder {
private Context context;
private int returnCode;
private int methodType;
private String url;
private Map<String, String> paramsMap;
private Map<String, File> fileMap;
private HttpQueueListener listener;
public Builder() {
paramsMap = new HashMap<>();
fileMap = new HashMap<>();
}
public Builder contxt(Context value) {
context = value;
return this;
}
public Builder returnCode(int returnCode) {
this.returnCode = returnCode;
return this;
}
public Builder methodType(int value) {
methodType = value;
return this;
}
public Builder url(String value) {
url = value;
return this;
}
public Builder addParameter(String key, String value) {
paramsMap.put(key, value);
return this;
}
public Builder setParameter(Map<String, String> value) {
paramsMap.clear();
paramsMap.putAll(value);
return this;
}
public Builder addFile(String key, File value) {
fileMap.put(key, value);
return this;
}
public Builder listener(HttpQueueListener value) {
listener = value;
return this;
}
public HttpQueue build() {
return new HttpQueue(this);
}
}
public HttpQueue execute() {
if (methodType == GET) {
get();
}
else if (methodType == POST) {
post();
}
else if (methodType == PUT) {
put();
}
else if (methodType == DELETE) {
delete();
}
return this;
}
private final String STR_ACCEPT = "Accept";
private void get() {
volleyer().get(url).addHeader(STR_ACCEPT, APPLICATION_JSON).withListener(this).withErrorListener(this).execute();
}
private void post() {
PostBuilder postBuilder = volleyer().post(url);
postBuilder.addHeader(STR_ACCEPT, APPLICATION_JSON);
if (!paramsMap.isEmpty()) {
for (String key : paramsMap.keySet()) {
postBuilder.addStringPart(key, paramsMap.get(key));
}
}
if (!fileMap.isEmpty()) {
for (String key : fileMap.keySet()) {
postBuilder.addFilePart(key, fileMap.get(key));
}
}
postBuilder.withListener(this).withErrorListener(this).execute();
}
private void put() {
PutBuilder putBuilder = volleyer().put(url);
putBuilder.addHeader(STR_ACCEPT, APPLICATION_JSON);
if (!paramsMap.isEmpty()) {
for (String key : paramsMap.keySet()) {
putBuilder.addStringPart(key, paramsMap.get(key));
}
}
if (!fileMap.isEmpty()) {
for (String key : fileMap.keySet()) {
putBuilder.addFilePart(key, fileMap.get(key));
}
}
putBuilder.withListener(this).withErrorListener(this).execute();
}
private void delete() {
volleyer().delete(url).addHeader(STR_ACCEPT, APPLICATION_JSON).withListener(this).withErrorListener(this).execute();
}
@Override
public void onErrorResponse(VolleyError error) {
Log.i("HttpQueue", "onErrorResponse");
listener.request_failed(error.getMessage());
}
@Override
public void onResponse(String response) {
Log.i("HttpQueue", String.valueOf(returnCode) + " : " + response);
listener.request_finished(this.returnCode, response);
}
}
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(Dtype)设备类型
//generate by redcloud,2020-07-24 19:59:20
public class Dtype implements Serializable {
private static final long serialVersionUID = 22L;
// 主键ID
private Long id ;
// 设备类型
private String title ;
// 备注
private String memo ;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this.title = title;
}
public String getMemo() {
return memo ;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
|
package edu.uestc.sdn;
import struct.StructClass;
import struct.StructField;
@StructClass
public class Packet_in {
@StructField(order = 0)
public short ingress_port ;
@StructField(order = 1)
public short reason ;
@StructField(order = 2)
public byte[] dmac = new byte[6];
@StructField(order = 3)
public byte[] smac = new byte[6];
}
|
/*
* 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 PO;
/**
*
* @author QueroDelivery
*/
public class cashback {
//para banco
private int cod_cash;
private int cod_ped;
private int usu_bene;
private float valor;
//nao ta no banco
private String nomeUsuario;
public String getNomeUsuario() {
return nomeUsuario;
}
public void setNomeUsuario(String nomeUsuario) {
this.nomeUsuario = nomeUsuario;
}
public int getCod_cash() {
return cod_cash;
}
public void setCod_cash(int cod_cash) {
this.cod_cash = cod_cash;
}
public int getCod_ped() {
return cod_ped;
}
public void setCod_ped(int cod_ped) {
this.cod_ped = cod_ped;
}
public int getUsu_bene() {
return usu_bene;
}
public void setUsu_bene(int usu_bene) {
this.usu_bene = usu_bene;
}
public float getValor() {
return valor;
}
public void setValor(float valor) {
this.valor = valor;
}
@Override
public String toString() {
return "cashback{" + "cod_cash=" + cod_cash + ", cod_ped=" + cod_ped + ", usu_bene=" + usu_bene + ", valor=" + valor + ", nomeUsuario=" + nomeUsuario + '}';
}
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.base;
import java.util.List;
import java.io.FileNotFoundException;
import com.davivienda.sara.entitys.HostAtm;
import java.util.Collection;
public interface ProcesadorArchivoHostInterface
{
Collection<HostAtm> getRegistrosHost() throws FileNotFoundException, IllegalArgumentException;
Collection<HostAtm> getRegistrosHostXFilas(final int p0, final int p1) throws FileNotFoundException, IllegalArgumentException;
List<String> getErroresDelProceso();
}
|
package com.zarokima.mastersproject.util;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
public class MastersContactListener implements ContactListener
{
@Override
public void beginContact(Contact contact)
{
UserData a = (UserData) contact.getFixtureA().getBody().getUserData();
UserData b = (UserData) contact.getFixtureB().getBody().getUserData();
a.container.beginCollideWith(contact.getFixtureB().getBody());
b.container.beginCollideWith(contact.getFixtureA().getBody());
}
@Override
public void endContact(Contact contact)
{
UserData a = (UserData) contact.getFixtureA().getBody().getUserData();
UserData b = (UserData) contact.getFixtureB().getBody().getUserData();
a.container.endCollideWith(contact.getFixtureB().getBody());
b.container.endCollideWith(contact.getFixtureA().getBody());
}
@Override
public void preSolve(Contact contact, Manifold oldManifold)
{
// TODO Auto-generated method stub
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse)
{
// TODO Auto-generated method stub
}
}
|
package com.mabang.android.entity;
public enum Enable {
ENABLE(1, "可用"), UNABLE(0, "不可用");
private Integer value;
private String text;
private Enable(Integer value, String text) {
this.value = value;
this.text = text;
return;
}
public Integer getValue() {
return this.value;
}
public String getText() {
return this.text;
}
public static String getTextByValue(Integer value) {
try {
for (Enable val : Enable.values()) {
if (val.value.equals(value))
return val.text;
}
} catch (Exception e) {
}
return "";
}
}
|
/**
* Test support for core AOT classes.
*/
@NonNullApi
@NonNullFields
package org.springframework.aot.test.generate;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package pl.basistam.books;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.Serializable;
import java.util.List;
@XmlRootElement(name = "book")
@XmlType(propOrder = {"authors", "titles", "isbn", "state"})
public class Book implements Serializable {
private List<String> authors;
private List<Title> titles;
private String isbn;
private State state;
public List<String> getAuthors() {
return authors;
}
public void setAuthors(List<String> authors) {
this.authors = authors;
}
public List<Title> getTitles() {
return titles;
}
public void setTitles(List<Title> titles) {
this.titles = titles;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
|
/*
* APNSMessenger.java
*
**********************************************************************
Copyright (c) 2013 - 2014 netty-apns
***********************************************************************/
package apns.netty;
import java.util.Calendar;
import org.apache.log4j.Logger;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import apns.netty.connection.impl.BatchApnsConnection;
import apns.netty.constants.ApplicationContextComponents;
import apns.netty.id.gen.BatchIdentifierGenerator;
import apns.netty.model.impl.ApnsMessage;
import apns.netty.model.impl.BatchFullMessage;
import apns.netty.queues.batch.BatchMessageQueue;
/**
* The Class APNSMessenger.
* @author arung
*/
@Component
public class APNSMessenger {
/** The Constant SINGLE_MESSAGE_QUEUE. */
private static final String SINGLE_MESSAGE_QUEUE = "singleMessageQueue";
/**
* The Class ShutDownHook.
*/
public static class ShutDownHook extends Thread {
/*
* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
APNSMessenger.LOGGER.info(APNSMessenger.RUNNING_SHUTDOWN_HOOK);
APNSMessenger.getRunner().getContext().close();
// getRunner().getLock().notify();
}
}
/** The Constant LOGGER. */
private static final Logger LOGGER = Logger
.getLogger(APNSMessenger.class);
/** The Constant SHUT_DOWN_HOOK_ATTACHED. */
private static final String SHUT_DOWN_HOOK_ATTACHED = "Shut Down Hook Attached.";
/** The Constant RUNNING_SHUTDOWN_HOOK. */
private static final String RUNNING_SHUTDOWN_HOOK = "Running shutdown hook.";
/** The Constant MAIN_APPLICATION_CONTEXT_XML. */
private static final String MAIN_APPLICATION_CONTEXT_XML = "apnsAppContext.xml";
/** The runner. */
private static APNSMessenger runner;
/** The context. */
private AbstractApplicationContext context;
/**
* The main method.
* @param args
* the arguments
*/
public static void main(final String[] args) {
APNSMessenger.setRunner(new APNSMessenger());
APNSMessenger.getRunner().attachShutDownHook();
APNSMessenger.getRunner().setContext(
new ClassPathXmlApplicationContext(
APNSMessenger.MAIN_APPLICATION_CONTEXT_XML));
APNSMessenger.getRunner().getContext().registerShutdownHook();
new Thread(new Runnable() {
@Override
public void run() {
APNSMessenger.getRunner().getContext()
.getBean(APNSMessenger.SINGLE_MESSAGE_QUEUE);
// final SingleMessageQueue singleMessageQueue =
// (SingleMessageQueue) APNSMessenger
// .getRunner().getContext()
// .getBean("singleMessageQueue");
//
// {
// final ApnsMessage.Builder builder = new
// ApnsMessage.Builder();
// builder.deviceToken("02ae608511d2f858881c6761ae7d9278ffe6ea2a0a1f4fba9310dea63bea86dd");
// builder.payLoad("{\"aps\" : {\"alert\" : \"Reds trying to hold on to lead.\",\"badge\" : 9,\"sound\" : \"bingbong.aiff\"},\"acme1\" : \"bar\",\"acme2\" : 42}");
// builder.expTime((int) (Calendar.getInstance()
// .getTimeInMillis() / 1000 + 86400));
// builder.id(1244);
// builder.prio((byte) 10);
//
// singleMessageQueue.pushQueue(builder.build());
//
// }
//
// {
// final ApnsMessage.Builder builder = new
// ApnsMessage.Builder();
// builder.deviceToken("03ae608511d2f858881c6761ae7d9278ffe6ea2a0a1f4fba9310dea63bea86dd");
// builder.payLoad("{\"aps\" : {\"alert\" : \"Reds trying to hold on to lead.\",\"badge\" : 9,\"sound\" : \"bingbong.aiff\"},\"acme1\" : \"bar\",\"acme2\" : 42}");
// builder.expTime((int) (Calendar.getInstance()
// .getTimeInMillis() / 1000 + 86400));
// builder.id(1245);
// builder.prio((byte) 10);
//
// singleMessageQueue.pushQueue(builder.build());
//
// }
//
// {
// final ApnsMessage.Builder builder = new
// ApnsMessage.Builder();
// builder.deviceToken("7e590ccdadd7adf4294be527d41191eb4639a984f92121260a9995cc64c69aef");
// builder.payLoad("{\"aps\" : {\"alert\" : \"Reds trying to hold on to lead.\",\"badge\" : 9,\"sound\" : \"bingbong.aiff\"},\"acme1\" : \"bar\",\"acme2\" : 42}");
// builder.expTime((int) (Calendar.getInstance()
// .getTimeInMillis() / 1000 + 86400));
// builder.id(1246);
// builder.prio((byte) 10);
//
// singleMessageQueue.pushQueue(builder.build());
//
// }
final BatchMessageQueue batchMessageQueue = (BatchMessageQueue) APNSMessenger
.getRunner()
.getContext()
.getBean(
ApplicationContextComponents.BATCH_MESSAGE_QUEUE);
final BatchApnsConnection bConn = (BatchApnsConnection) APNSMessenger
.getRunner()
.getContext()
.getBean(
ApplicationContextComponents.BATCH_CONNECTION);
final BatchIdentifierGenerator batchIdentifierGenerator = (BatchIdentifierGenerator) APNSMessenger
.getRunner()
.getContext()
.getBean(
ApplicationContextComponents.BATCH_IDENTIFIER_GENERATOR);
while (bConn.getAtomicBatchCounter().intValue() != 75) {
;
}
final BatchFullMessage bfm = new BatchFullMessage();
for (int i = 0; i < 10; i++) {
final ApnsMessage.Builder builder = new ApnsMessage.Builder();
if (i == 5) {
builder.deviceToken("8e590ccdadd7adf4294be527d41191eb4639a984f92121260a9995cc64c69aef");
} else {
builder.deviceToken("7e590ccdadd7adf4294be527d41191eb4639a984f92121260a9995cc64c69aef");
}
builder.payLoad("{\"aps\" : {\"alert\" : \"Reds trying to hold on to lead."
+ i
+ "\",\"badge\" : 9,\"sound\" : \"bingbong.aiff\"},\"acme1\" : \"bar\",\"acme2\" : 42}");
builder.expTime((int) (Calendar.getInstance()
.getTimeInMillis() / 1000 + 86400));
builder.id(batchIdentifierGenerator.newIdentifier());
builder.prio((byte) 10);
bfm.addInvMessages(builder.build());
}
batchMessageQueue.pushQueue(bfm);
// bfm = new BatchFullMessage();
//
// for (int i = 10; i < 20; i++) {
// final ApnsMessage.Builder builder = new
// ApnsMessage.Builder();
// if (i == 5) {
// builder.deviceToken("03ae608511d2f858881c6761ae7d9278ffe6ea2a0a1f4fba9310dea63bea86dd");
// } else {
// builder.deviceToken("02ae608511d2f858881c6761ae7d9278ffe6ea2a0a1f4fba9310dea63bea86dd");
// }
// builder.payLoad("{\"aps\" : {\"alert\" : \"Reds trying to hold on to lead."
// + i
// +
// "\",\"badge\" : 9,\"sound\" : \"bingbong.aiff\"},\"acme1\" : \"bar\",\"acme2\" : 42}");
// builder.expTime((int) (Calendar.getInstance()
// .getTimeInMillis() / 1000 + 86400));
// builder.id(batchIdentifierGenerator.newIdentifier());
// builder.prio((byte) 10);
//
// bfm.addInvMessages(builder.build());
// }
//
// batchMessageQueue.pushQueue(bfm);
}
}).start();
// final ApnsMessage.Builder builder = new ApnsMessage.Builder();
// builder.deviceToken("02ae608511d2f858881c6761ae7d9278ffe6ea2a0a1f4fba9310dea63bea86dd");
// builder.payLoad("{\"aps\" : {\"alert\" : \"test local .\",\"badge\" : 9,\"sound\" : \"bingbong.aiff\"}");
// builder.expTime(10000000);
// builder.id("ab");
// builder.prio((byte) 1);
// factory.getSingleConnection().write(builder.build());
}
/**
* Attach shut down hook.
*/
public void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new ShutDownHook());
APNSMessenger.LOGGER.info(APNSMessenger.SHUT_DOWN_HOOK_ATTACHED);
}
/**
* Gets the runner.
* @return the runner
*/
public static APNSMessenger getRunner() {
return APNSMessenger.runner;
}
/**
* Sets the runner.
* @param runner
* the new runner
*/
public static void setRunner(final APNSMessenger runner) {
APNSMessenger.runner = runner;
}
/**
* Gets the context.
* @return the context
*/
public AbstractApplicationContext getContext() {
return context;
}
/**
* Sets the context.
* @param context
* the new context
*/
public void setContext(final AbstractApplicationContext context) {
this.context = context;
}
}
|
package com.test.base;
/**
* On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
* 在一个二维矩阵上,放置一些点,每个点最多有一个值
*
* Now, a move consists of removing a stone that shares a column or row with another stone on the grid.
* 然后,如果点的行或列相同,可以移除一些点
*
* What is the largest possible number of moves we can make?
* 请问,最多可以移除多少个点
*
* 点 个数范围:
* 1 <= stones.length <= 1000
* 点 大小范围:
* 0 <= stones[i][j] < 10000
*
* @author YLine
*
* 2019年6月3日 上午10:17:29
*/
public interface Solution
{
public int removeStones(int[][] stones);
}
|
package com.emed.shopping.dao.model.admin.system;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Date;
public class ShopAccessory implements Serializable {
@Id
@GeneratedValue(generator = "JDBC")
private Long id;
/**
* 附件名称
*
* @mbg.generated
*/
private String name;
/**
* 附件路径
*
* @mbg.generated
*/
private String path;
/**
* 后缀名
*
* @mbg.generated
*/
private String ext;
/**
* 大小
*
* @mbg.generated
*/
private Integer size;
/**
* 高度
*
* @mbg.generated
*/
private Integer height;
/**
* 宽度
*
* @mbg.generated
*/
private Integer width;
/**
* 详情
*
* @mbg.generated
*/
private String info;
/**
* 所属人
*
* @mbg.generated
*/
private Long userId;
/**
* 所属相册
*
* @mbg.generated
*/
private Long albmId;
/**
* 系统配置
*
* @mbg.generated
*/
private Long configId;
/**
* 添加时间
*
* @mbg.generated
*/
private Date createTime;
/**
* 删除状态
*
* @mbg.generated
*/
private String deleteStatus;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getExt() {
return ext;
}
public void setExt(String ext) {
this.ext = ext;
}
public Integer getSize() {
return size;
}
public void setSize(Integer size) {
this.size = size;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getAlbmId() {
return albmId;
}
public void setAlbmId(Long albmId) {
this.albmId = albmId;
}
public Long getConfigId() {
return configId;
}
public void setConfigId(Long configId) {
this.configId = configId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getDeleteStatus() {
return deleteStatus;
}
public void setDeleteStatus(String deleteStatus) {
this.deleteStatus = deleteStatus;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", path=").append(path);
sb.append(", ext=").append(ext);
sb.append(", size=").append(size);
sb.append(", height=").append(height);
sb.append(", width=").append(width);
sb.append(", info=").append(info);
sb.append(", userId=").append(userId);
sb.append(", albmId=").append(albmId);
sb.append(", configId=").append(configId);
sb.append(", createTime=").append(createTime);
sb.append(", deleteStatus=").append(deleteStatus);
sb.append("]");
return sb.toString();
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
ShopAccessory other = (ShopAccessory) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getPath() == null ? other.getPath() == null : this.getPath().equals(other.getPath()))
&& (this.getExt() == null ? other.getExt() == null : this.getExt().equals(other.getExt()))
&& (this.getSize() == null ? other.getSize() == null : this.getSize().equals(other.getSize()))
&& (this.getHeight() == null ? other.getHeight() == null : this.getHeight().equals(other.getHeight()))
&& (this.getWidth() == null ? other.getWidth() == null : this.getWidth().equals(other.getWidth()))
&& (this.getInfo() == null ? other.getInfo() == null : this.getInfo().equals(other.getInfo()))
&& (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
&& (this.getAlbmId() == null ? other.getAlbmId() == null : this.getAlbmId().equals(other.getAlbmId()))
&& (this.getConfigId() == null ? other.getConfigId() == null : this.getConfigId().equals(other.getConfigId()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getDeleteStatus() == null ? other.getDeleteStatus() == null : this.getDeleteStatus().equals(other.getDeleteStatus()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getPath() == null) ? 0 : getPath().hashCode());
result = prime * result + ((getExt() == null) ? 0 : getExt().hashCode());
result = prime * result + ((getSize() == null) ? 0 : getSize().hashCode());
result = prime * result + ((getHeight() == null) ? 0 : getHeight().hashCode());
result = prime * result + ((getWidth() == null) ? 0 : getWidth().hashCode());
result = prime * result + ((getInfo() == null) ? 0 : getInfo().hashCode());
result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode());
result = prime * result + ((getAlbmId() == null) ? 0 : getAlbmId().hashCode());
result = prime * result + ((getConfigId() == null) ? 0 : getConfigId().hashCode());
result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
result = prime * result + ((getDeleteStatus() == null) ? 0 : getDeleteStatus().hashCode());
return result;
}
}
|
package com.hanks.algorithm.service;
import com.hanks.algorithm.common.exception.ServiceException;
public interface AlgorithmService {
Integer[] bubbleSort(Integer[] metaData) throws ServiceException;
Integer[] selectionSort(Integer[] metaData) throws ServiceException;
Integer[] quickSort(Integer[] metaData) throws ServiceException;
Integer[] mergeSort(Integer[] metaData) throws ServiceException;
Integer[] insertSort(Integer[] metaData) throws ServiceException;
Integer[] shellSort(Integer[] metaData) throws ServiceException;
double[] bucketSort(double[] metaData) throws ServiceException;
Integer[] heapSort(Integer[] metaData) throws ServiceException;
}
|
package com.sansan.tx.transfer_demo4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:com/sansan/tx/transfer_demo4/applicationContext.xml")
public class TxTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer() {
// String xmlPath = "com/sansan/tx/transfer_demo4/applicationContext.xml";
// ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
// AccountService accountService = (AccountService) applicationContext.getBean("accountService");
accountService.transfer("jack", "rose", 1000);
}
}
|
package fr.skytasul.quests.utils.compatibility;
public class MissingDependencyException extends RuntimeException{
private static final long serialVersionUID = 8636504175650105867L;
public MissingDependencyException(String depend){
super("Missing dependency: " + depend);
}
}
|
package com.dfire.dao;
import com.dfire.common.entity.*;
import com.dfire.common.entity.model.HeraJobBean;
import com.dfire.common.entity.vo.HeraDebugHistoryVo;
import com.dfire.common.enums.StatusEnum;
import com.dfire.common.service.*;
import com.dfire.common.util.ActionUtil;
import com.dfire.common.util.BeanConvertUtils;
import com.dfire.common.entity.vo.HeraHostGroupVo;
import com.dfire.core.lock.DistributeLock;
import com.dfire.core.netty.master.Master;
import com.dfire.core.netty.master.MasterContext;
import com.dfire.core.schedule.HeraSchedule;
import com.dfire.common.entity.model.JsonResponse;
import com.dfire.monitor.service.JobManageService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author: <a href="mailto:lingxiao@2dfire.com">凌霄</a>
* @time: Created in 下午5:15 2018/5/14
* @desc
*/
@ComponentScan(basePackages = "com.dfire")
@MapperScan(basePackages = "com.dfire.common.mapper")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = HeraBaseDaoTest.class)
public class HeraBaseDaoTest {
@Autowired
HeraJobActionService heraJobActionService;
@Autowired
HeraPermissionService heraPermissionService;
@Autowired
HeraDebugHistoryService heraDebugHistoryService;
@Autowired
HeraFileService heraFileService;
@Autowired
HeraGroupService heraGroupService;
@Autowired
HeraLockService heraLockService;
@Autowired
HeraHostRelationService heraHostRelationService;
@Autowired
HeraHostGroupService heraHostGroupService;
@Autowired
HeraJobService heraJobService;
@Autowired
JobManageService jobManageService;
HeraAction heraAction;
HeraPermission heraPermission;
HeraDebugHistory heraDebugHistory;
HeraFile heraFile;
HeraGroup heraGroup;
HeraLock heraLock;
@Autowired
DistributeLock distributeLock;
@Before
public void doBefore() {
heraAction = HeraAction.builder()
.id(1111111111111111111L)
.jobId(6666)
.gmtCreate(new Date())
.gmtModified(new Date())
.groupId(1)
.name("lx")
.owner("lx")
.build();
heraPermission = HeraPermission
.builder()
.gmtCreate(new Date())
.build();
heraDebugHistory = HeraDebugHistory
.builder()
.fileId(1)
.hostGroupId(1)
.owner("import")
.gmtCreate(new Date())
.gmtModified(new Date())
.startTime(new Date())
.endTime(new Date())
.build();
heraFile = HeraFile.builder()
.build();
heraGroup = HeraGroup.builder().build();
heraLock = HeraLock.builder()
.subgroup("test")
.host("127.0.0.1")
.serverUpdate(new Date())
.build();
}
@Test
public void heraActionDaoTest() {
HeraAction action = HeraAction.builder().id(201801010010000350L).jobId(350).build();
System.out.println(heraAction.getGmtCreate());
List<HeraAction> list = heraJobActionService.getAll();
System.out.println(list.get(5).getJobDependencies());
heraJobActionService.insert(heraAction, Long.parseLong(ActionUtil.getCurrActionVersion()));
heraJobActionService.delete("1111111111111111111");
HeraAction heraAction = heraJobActionService.findById("201806190000000002");
System.out.println(heraAction.getJobDependencies());
}
@Test
public void heraActionBatchDaoTest() {
// heraJobActionService.delete("1111111111111111111");
// heraJobActionService.insert(heraAction);
HeraAction heraAction = heraJobActionService.findById("201806190000000002");
List<HeraAction> list = Arrays.asList(heraAction);
heraJobActionService.batchInsert(list, Long.parseLong(ActionUtil.getCurrActionVersion()));
//
// HeraAction heraAction = heraJobActionService.findById("201806190000000002");
// System.out.println(heraAction.getJobDependencies());
}
@Test
public void heraPermissionDaoTest() {
int id = heraPermissionService.insert(heraPermission);
System.out.println(id);
System.out.println(System.currentTimeMillis());
heraPermission.setGmtModified(new Date());
heraPermissionService.update(heraPermission);
List<Integer> list = Arrays.asList(new Integer[]{new Integer(20), new Integer(12)});
List<HeraPermission> permissions = heraPermissionService.findByIds(list);
System.out.println(permissions.get(0).getGmtCreate());
heraPermission.setId(19);
heraPermissionService.delete("250");
heraPermissionService.findById(heraPermission);
}
@Test
public void heraDebugHistoryDaoTest() {
HeraDebugHistoryVo debugHistory = heraDebugHistoryService.findById(271);
debugHistory.setStatus(StatusEnum.FAILED);
heraDebugHistoryService.update(BeanConvertUtils.convert(debugHistory));
HeraDebugHistory history = BeanConvertUtils.convert(debugHistory);
history.setLog("test11ssss1");
history.setGmtCreate(new Date());
history.setGmtModified(new Date());
heraDebugHistoryService.update(history);
System.out.println(debugHistory.getStatus().toString());
System.out.println(history.getLog());
}
@Test
public void heraFileDaoTest() {
heraFile = heraFileService.findById(2);
System.out.println(heraFile.getName());
heraFile.setContent("test");
heraFileService.update(heraFile);
List<Integer> list = Arrays.asList(new Integer[]{new Integer(20), new Integer(12)});
List<HeraFile> heraFileList = heraFileService.findByIds(list);
System.out.println(heraFileList.size());
heraFileService.delete(3);
List<HeraFile> subList = heraFileService.findByParent(3);
System.out.println(subList.size());
List<HeraFile> pList = heraFileService.findByOwner("biadmin");
System.out.println(pList.size());
heraFile = HeraFile.builder().owner("test").name("test").type(2).build();
heraFileService.insert(heraFile);
}
@Test
public void heraFileContent() {
HeraFile heraFile = HeraFile.builder().id(4).content("ls /").build();
heraFileService.updateContent(heraFile);
}
@Test
public void heraGroupDaoTest() {
heraGroup = heraGroupService.findById(3579);
System.out.println(heraGroup.getConfigs());
heraGroup.setConfigs("test");
heraGroupService.update(heraGroup);
HeraGroup group = heraGroupService.findById(3587);
System.out.println(group.getConfigs());
List<Integer> list = Arrays.asList(new Integer[]{new Integer(3607), new Integer(3608)});
List<HeraGroup> groups = heraGroupService.findByIds(list);
System.out.println(groups.get(0).getOwner());
List<HeraGroup> subGroup = heraGroupService.findByParent(3578);
System.out.println(subGroup.size());
List<HeraGroup> userGroup = heraGroupService.findByOwner("biadmin");
System.out.println(userGroup.size());
heraGroupService.delete(3580);
}
@Test
public void JobGraphTest() {
HeraJobBean jobBean = heraGroupService.getUpstreamJobBean("90");
System.out.println(jobBean.getUpStream().size());
}
@Test
public void heraLockDaoTest() {
HeraLock lock = heraLockService.findBySubgroup("online");
lock.setServerUpdate(new Date());
heraLockService.update(lock);
heraLockService.insert(heraLock);
}
@Test
public void heraHostGroupDaoTest() {
HeraHostGroup group = heraHostGroupService.findById(1);
System.out.println(group.getName());
Map<Integer, HeraHostGroupVo> map = heraHostGroupService.getAllHostGroupInfo();
System.out.println(map.toString());
}
@Test
public void heraJobDaoTest() {
}
@Test
public void jobManageTest() {
// JsonResponse jsonResponse = jobManageService.findJobHistoryByStatus("failed");
// System.out.println(jsonResponse.getData());
JsonResponse top10 = jobManageService.findJobRunTimeTop10();
System.out.println(top10.getData());
}
@Test
public void dagTest() {
}
@Test
public void generateActionTest() {
try {
Field heraScheduleField = distributeLock.getClass().getDeclaredField("heraSchedule");
heraScheduleField.setAccessible(true);
HeraSchedule heraSchedule = (HeraSchedule) heraScheduleField.get(distributeLock);
heraSchedule.startup();
if(heraSchedule != null) {
Field masterContextField = heraSchedule.getClass().getDeclaredField("masterContext");
masterContextField.setAccessible(true);
MasterContext masterContext = (MasterContext) masterContextField.get(heraSchedule);
if(masterContext != null) {
Master master = masterContext.getMaster();
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
Map<Long, HeraAction> actionMap = new HashMap<>();
List<HeraJob> heraJobList = heraJobService.getAll();
String cronDate = ActionUtil.getActionVersionByTime(now);
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
@Test
public void generateSingleAction() {
try {
Field heraScheduleField = distributeLock.getClass().getDeclaredField("heraSchedule");
heraScheduleField.setAccessible(true);
HeraSchedule heraSchedule = (HeraSchedule) heraScheduleField.get(distributeLock);
heraSchedule.startup();
if(heraSchedule != null) {
Field masterContextField = heraSchedule.getClass().getDeclaredField("masterContext");
masterContextField.setAccessible(true);
MasterContext masterContext = (MasterContext) masterContextField.get(heraSchedule);
if(masterContext != null) {
Master master = masterContext.getMaster();
master.generateBatchAction();
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
|
package com.atlassian.theplugin.idea.action.issues;
import com.atlassian.theplugin.idea.IdeaHelper;
import com.atlassian.theplugin.idea.jira.IssueListToolWindowPanel;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
public class CreateIssueAction extends AnAction {
@Override
public void actionPerformed(AnActionEvent e) {
IssueListToolWindowPanel panel = IdeaHelper.getIssueListToolWindowPanel(e);
if (panel != null) {
panel.createIssue();
}
}
@Override
public void update(AnActionEvent event) {
IssueListToolWindowPanel panel = IdeaHelper.getIssueListToolWindowPanel(event);
boolean enabled = panel != null && panel.getSelectedServer() != null;
event.getPresentation().setEnabled(enabled);
}
}
|
package com.karya.dao;
import java.util.List;
import com.karya.model.Login001MB;
import com.karya.model.Role001MB;
import com.karya.model.UserRole001MB;
public interface IUserRoleDAO{
public void userRoleAddAction(UserRole001MB userrole001mb);
public UserRole001MB userRoleEditAction(int id);
public void userRoleDeleteAction(int id);
public List<UserRole001MB> listallusers();
public List<Role001MB> getRoleList();
public List<Login001MB> getUserList();
}
|
package jianzhioffer;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* @ClassName : Solution41
* @Description : 数据流中的中位数
* 用最大堆和最小堆来实现:中位数,把数组分成了两部分,一部分全小于mid,另一部分全大于mid
* 最大堆存小的数,最小堆存大的数,奇数放小数,偶数使放大数
* @Date : 2019/9/19 19:51
*/
public class Solution41 {
int count=0;
PriorityQueue<Integer> largePart=new PriorityQueue<>();
PriorityQueue<Integer> smallPart=new PriorityQueue<>(11, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
public void insert(int num){
count++;
if ((count&1)==1){
if (!largePart.isEmpty() && largePart.peek()<num){
largePart.offer(num);
num=largePart.poll();
}
smallPart.offer(num);
}else{
if (!smallPart.isEmpty() && smallPart.peek()>num){
smallPart.offer(num);
num=smallPart.poll();
}
largePart.offer(num);
}
}
public double getMidian(){
if ((count&1)==1)
return smallPart.isEmpty()?-1:smallPart.peek();
else
return (smallPart.peek()+largePart.peek())/2.0;
}
}
|
package com.tony.service.Impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tony.dao.WordDao;
import com.tony.model.WordModel;
import com.tony.service.WordService;
@Service("WordService")
public class WordServiceImpl implements WordService{
@Autowired
private WordDao worddao;
@Override
public int insertWord(WordModel wordModel) {
// TODO Auto-generated method stub
return worddao.insertWord(wordModel);
}
@Override
public int updateWord(WordModel wordModel) {
// TODO Auto-generated method stub
return worddao.updateWord(wordModel);
}
@Override
public int delWord(WordModel wordModel) {
// TODO Auto-generated method stub
return worddao.delWord(wordModel);
}
@Override
public List<WordModel> queryAllWord() {
// TODO Auto-generated method stub
return worddao.queryAllWord();
}
}
|
package com.java.util.one.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
public class ArticleListTest {
public static void main(String[] args) throws ParseException {
//创建集合对象
List<Article> list = new ArrayList<>();
//时间格式化
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
list.add(new Article(1,"总有一天,你要一个人走","马克 韦伯",simpleDateFormat.parse("2019-03-18 22:20:50")));
list.add(new Article(2,"人性的弱点,世界人文畅销书","卡耐基",simpleDateFormat.parse("2019-03-18 20:13:50")));
list.add(new Article(3,"今天也要用心过生活.........","松浦弥太郎",simpleDateFormat.parse("2019-03-17 00:14:50")));
System.out.println("id 标题 作者 时间");
//创建迭代器
Iterator<Article> iterator = list.iterator();
while(iterator.hasNext()){
//Article迭代
Article article = iterator.next();
//调用timeCha()方法
String result = timeCha(simpleDateFormat.format(article.getTime()));
System.out.println(article.getId()+" "+article.getTitle().substring(0,10)+"..."+
article.getAuthor()+" "+result);//substring(0,10)截取元素
}
}
private static String timeCha(String time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1;
long diff = 0;
try {
d1 = format.parse(time);
Date now = new Date();
diff = now.getTime() - d1.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
if (seconds < 60) {
return "刚刚";
} else if (minutes < 60) {
return minutes + "分钟前";
} else if (hours < 24) {
return hours + "小时前";
} else {
return days + "天前";
}
}
}
|
package com.laulee.gank.base;
/**
* Created by laulee on 16/12/25.
*/
public class HttpResult<T> {
private String source;
private String message;
private int code;
private T value;
public String getSource() {
return source;
}
public T getValue() {
return value;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
|
package bms.table;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import bms.table.Course.Trophy;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
* 難易度表パーサ
*
* @author exch
*/
public class DifficultyTableParser {
// TODO bug:HTTP RequestPropertyを指定しないと403を返すサイトへの対応(JSONは一度byteデータで読む必要あり)
/**
* 難易度表データ
*/
private Map<String, String[]> data = new HashMap<String, String[]>();
public DifficultyTableParser() {
}
/**
* 難易度表ヘッダを含んでいるかどうかを判定する
*
* @return 難易度表ヘッダを含んでいればtrue
*/
public boolean containsHeader(String urlname) {
return getMetaTag(urlname, "bmstable") != null;
}
/**
* 難易度表ヘッダを含んでいるかどうかを判定する
*
* @return 難易度表ヘッダを含んでいればtrue
*/
public String getAlternateBMSTableURL(String urlname) {
return getMetaTag(urlname, "bmstable-alt");
}
private String[] readAllLines(String urlname) {
String[] result = null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(urlname).openStream()))) {
List<String> l = new ArrayList();
String line = null;
while ((line = br.readLine()) != null) {
l.add(line);
}
result = l.toArray(new String[l.size()]);
} catch (IOException e) {
Logger.getGlobal().severe("難易度表サイト解析中の例外:" + e.getMessage());
}
return result;
}
private String getMetaTag(String urlname, String name) {
if (data.get(urlname) == null) {
data.put(urlname, readAllLines(urlname));
}
if (data.get(urlname) == null) {
return null;
}
for (String line : data.get(urlname)) {
// 難易度表ヘッダ
if (line.toLowerCase().contains("<meta name=\"" + name + "\"")) {
Pattern p = Pattern.compile("\"");
return p.split(line)[3];
}
}
return null;
}
/**
* 難易度表ページをデコードし、反映する
*
* @param b
* 譜面データも取り込むかどうか。設定項目のみを取り出したい場合はfalseとする
* @param diff
* 難易度表の情報(名称、記号、タグ)
* @throws IOException
*/
public void decode(boolean b, DifficultyTable diff) throws IOException {
String urlname = diff.getSourceURL();
String tableurl = null;
String enc = null;
if (urlname == null || urlname.length() == 0) {
tableurl = diff.getHeadURL();
} else {
if (data.get(urlname) == null) {
data.put(urlname, readAllLines(urlname));
}
if (data.get(urlname) == null) {
throw new IOException();
}
Pattern p = Pattern.compile("\"");
for (String line : data.get(urlname)) {
// 文字エンコード
if (line.toLowerCase().contains("<meta http-equiv=\"content-type\"")) {
String str = p.split(line)[3];
enc = str.substring(str.indexOf("charset=") + 8);
}
// 難易度表ヘッダ
if (line.toLowerCase().contains("<meta name=\"bmstable\"")) {
tableurl = p.split(line)[3];
}
}
}
// 難易度表ヘッダ(JSON)がある場合
if (tableurl != null) {
this.decodeJSONTable(diff, new URL(this.getAbsoluteURL(urlname, tableurl)), b);
diff.setSourceURL(urlname);
} else {
// 難易度表ヘッダ(JSON)がない場合は、IRmemo用難易度表パーサに移行
// ただしcontainsHeaderでヘッダの存在を確認してからdecodeを実行するため、ここには到達しない
// エンコード不明の場合はreturn
if (enc != null) {
// エンコード表記の統一
if (enc.toUpperCase().equals("UTF-8")) {
enc = enc.toUpperCase();
}
if (enc.toUpperCase().equals("SHIFT_JIS")) {
enc = "Shift_JIS";
}
// this.parseDifficultyTable(diff, diff.getID(),
// new InputStreamReader(new
// ByteArrayInputStream(data.get(urlname)), enc), b);
}
}
}
private String getAbsoluteURL(String source, String path) {
// DataURL相対パス対応
String urldir = source.substring(0, source.lastIndexOf('/') + 1);
if (!path.startsWith("http") && !path.startsWith(urldir)) {
if (path.startsWith("./")) {
path = path.substring(2);
}
return urldir + path;
}
return path;
}
/**
* 難易度表JSONページをデコードし、反映する
*
* @param jsonheader
* 難易度表JSONヘッダURL
* @param saveElements
* 譜面データも取り込むかどうか。設定項目のみを取り出したい場合はfalseとする
*/
public void decodeJSONTable(DifficultyTable dt, URL jsonheader, boolean saveElements) throws IOException {
// 難易度表ヘッダ(JSON)読み込み
this.decodeJSONTableHeader(dt, jsonheader);
String[] urls = dt.getDataURL();
if (saveElements) {
dt.removeAllElements();
List<DifficultyTableElement> elements = new ArrayList();
List<String> levels = new ArrayList();
for (String url : urls) {
Map<String, String> conf = dt.getMergeConfigurations().get(url);
if (conf == null) {
conf = new HashMap();
}
DifficultyTable table = new DifficultyTable();
this.decodeJSONTableData(
table,
new URL(this.getAbsoluteURL(
(dt.getSourceURL() == null || dt.getSourceURL().length() == 0) ? dt.getHeadURL() : this
.getAbsoluteURL(dt.getSourceURL(), dt.getHeadURL()), url)));
levels.addAll(Arrays.asList(table.getLevelDescription()));
// 重複BMSの処理
for (DifficultyTableElement dte : table.getElements()) {
if (conf.get(dte.getLevel()) == null || conf.get(dte.getLevel()).length() > 0) {
boolean contains = false;
for (DifficultyTableElement dte2 : elements) {
if ((dte.getMD5() != null && dte.getMD5().length() > 10
&& dte.getMD5().equals(dte2.getMD5()) || (dte.getSHA256() != null
&& dte.getSHA256().length() > 10 && dte.getSHA256().equals(dte2.getSHA256())))) {
contains = true;
break;
}
}
if (!contains) {
if (conf.get(dte.getLevel()) != null) {
dte.setLevel(conf.get(dte.getLevel()));
}
elements.add(dte);
}
}
}
}
if (dt.getLevelDescription().length == 0) {
dt.setLevelDescription(levels.toArray(new String[levels.size()]));
}
dt.setModels(elements);
}
}
/**
* JSONヘッダ部をデコードして指定のDifficultyTableオブジェクトに反映する
*
* @param dt
* 反映するDifficultyTableオブジェクト
* @param jsonheader
* JSONヘッダ部ファイル
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
public void decodeJSONTableHeader(DifficultyTable dt, File jsonheader) throws IOException {
ObjectMapper mapper = new ObjectMapper();
this.decodeJSONTableHeader(dt, mapper.readValue(jsonheader, Map.class));
}
/**
* JSONヘッダ部をデコードして指定のDifficultyTableオブジェクトに反映する
*
* @param dt
* 反映するDifficultyTableオブジェクト
* @param jsonheader
* JSONヘッダ部URL
* @throws JsonParseException
* @throws JsonMappingException
* @throws IOException
*/
public void decodeJSONTableHeader(DifficultyTable dt, URL jsonheader) throws IOException {
ObjectMapper mapper = new ObjectMapper();
this.decodeJSONTableHeader(dt, mapper.readValue(jsonheader, Map.class));
dt.setHeadURL(jsonheader.toExternalForm());
}
private DifficultyTable decodeJSONTableHeader(DifficultyTable dt, Map<String, Object> result) throws IOException {
dt.setValues(result);
// level_order処理
Object dataurl = result.get("data_url");
if (dataurl instanceof String) {
dt.setDataURL(new String[] { (String) dataurl });
}
if (dataurl instanceof List) {
dt.setDataURL((String[]) ((List) dataurl).toArray(new String[0]));
}
Map<String, Map<String, String>> mergerule = new HashMap();
List<Map<String, String>> merge = (List<Map<String, String>>) result.get("data_rule");
if (merge == null) {
merge = new ArrayList();
}
for (int i = 0; i < dt.getDataURL().length; i++) {
if (i == merge.size()) {
break;
}
mergerule.put(dt.getDataURL()[i], merge.get(i));
}
dt.setMergeConfigurations(mergerule);
List<Course[]> courses = new ArrayList();
if (result.get("course") != null) {
List<List<Map<String, Object>>> courselist = new ArrayList<List<Map<String, Object>>>();
if (((List) result.get("course")).get(0) instanceof List) {
courselist = (List<List<Map<String, Object>>>) result.get("course");
}
if (((List) result.get("course")).get(0) instanceof Map) {
courselist.add((List<Map<String, Object>>) result.get("course"));
}
for (List<Map<String, Object>> course : courselist) {
List<Course> l = new ArrayList<Course>();
for (Map<String, Object> grade : course) {
Course gr = new Course();
gr.setName((String) grade.get("name"));
List<BMSTableElement> charts = new ArrayList();
if(grade.get("charts") != null) {
for(Map<String, Object> chart : (List<Map<String, Object>>) grade.get("charts")) {
BMSTableElement dte = new DifficultyTableElement();
dte.setValues(chart);
charts.add(dte);
}
} else {
for(String md5 : (List<String>) grade.get("md5")) {
BMSTableElement dte = new DifficultyTableElement();
dte.setMD5(md5);
charts.add(dte);
}
}
gr.setCharts(charts.toArray(new BMSTableElement[charts.size()]));
gr.setStyle((String) grade.get("style"));
gr.setConstraint(((List<String>) grade.get("constraint")).toArray(new String[0]));
if (grade.get("trophy") != null) {
List<Trophy> trophy = new ArrayList();
for (Map<String, Object> tr : (List<Map<String, Object>>) grade.get("trophy")) {
Trophy t = new Trophy();
t.setName((String) tr.get("name"));
t.setMissrate((double) tr.get("missrate"));
t.setScorerate((double) tr.get("scorerate"));
t.setStyle((String) tr.get("style"));
trophy.add(t);
}
gr.setTrophy(trophy.toArray(new Trophy[trophy.size()]));
}
l.add(gr);
}
courses.add(l.toArray(new Course[l.size()]));
}
} else if (result.get("grade") != null) {
List<Course> l = new ArrayList<Course>();
for (Map<String, Object> grade : (List<Map<String, Object>>) result.get("grade")) {
Course gr = new Course();
gr.setName((String) grade.get("name"));
List<BMSTableElement> charts = new ArrayList();
for(String md5 : (List<String>) grade.get("md5")) {
BMSTableElement dte = new DifficultyTableElement();
dte.setMD5(md5);
charts.add(dte);
}
gr.setCharts(charts.toArray(new BMSTableElement[charts.size()]));
gr.setStyle((String) grade.get("style"));
gr.setConstraint(new String[] { "grade_mirror","gauge_lr2" });
l.add(gr);
}
courses.add(l.toArray(new Course[l.size()]));
}
dt.setCourse(courses.toArray(new Course[courses.size()][]));
// 必須項目が定義されていない場合は例外をスロー
if (result.get("name") == null || result.get("symbol") == null) {
throw new IOException("ヘッダ部の情報が不足しています", null);
}
return dt;
}
/**
* 難易度表JSONデータをデコードし、指定の難易度表に反映する
*
* @param dt
* 難易度表
* @param jsondata
* 難易度表JSONデータファイル
*/
public void decodeJSONTableData(DifficultyTable dt, File jsondata) throws IOException {
// JSON読み込み
ObjectMapper mapper = new ObjectMapper();
this.decodeJSONTableData(dt, mapper.readValue(jsondata, List.class), true);
}
/**
* 難易度表JSONデータをデコードし、指定の難易度表に反映する
*
* @param dt
* 難易度表
* @param jsondata
* 難易度表JSONデータURL
*/
public void decodeJSONTableData(DifficultyTable dt, URL jsondata) throws IOException {
Logger.getGlobal().info("難易度表データ読み込み - " + jsondata.toExternalForm());
// JSON読み込み
ObjectMapper mapper = new ObjectMapper();
// 難易度表に変換
this.decodeJSONTableData(dt, mapper.readValue(jsondata, List.class), false);
}
private void decodeJSONTableData(DifficultyTable dt, List<Map<String, Object>> result, boolean accept) {
dt.removeAllElements();
List<String> levelorder = new ArrayList<String>();
for (Map<String, Object> m : result) {
// levelとmd5(sha256)が定義されていない要素は弾く
if (accept
|| (m.get("level") != null && ((m.get("md5") != null && m.get("md5").toString().length() > 24) || (m
.get("sha256") != null && m.get("sha256").toString().length() > 24)))) {
DifficultyTableElement dte = new DifficultyTableElement();
dte.setValues(m);
if(dte.getMode() == null) {
dte.setMode(dt.getMode());
}
String level = String.valueOf(m.get("level"));
boolean b = true;
for (int j = 0; j < levelorder.size(); j++) {
if (levelorder.get(j).equals(level)) {
b = false;
}
}
if (b) {
levelorder.add(level);
}
dt.addElement(dte);
} else {
Logger.getGlobal().info(
m.get("title") + "の譜面定義に不備があります - level:" + m.get("level") + " md5:" + m.get("md5"));
}
}
if (dt.getLevelDescription().length == 0) {
dt.setLevelDescription(levelorder.toArray(new String[levelorder.size()]));
}
}
/**
* 難易度表モデルをJSONヘッダ部にエンコードし、指定のファイルに保存する
*
* @param dt
* エンコードする難易度表モデル
* @param jsonheader
* JSONヘッダ部ファイル
*/
public void encodeJSONTableHeader(DifficultyTable dt, File jsonheader) {
try {
// ヘッダ部のエクスポート
Map<String, Object> header = new HashMap<String, Object>();
header.put("name", dt.getName());
header.put("symbol", dt.getID());
header.put("tag", dt.getTag());
header.put("level_order", dt.getLevelDescription());
if (dt.getDataURL().length > 1) {
header.put("data_url", dt.getDataURL());
} else if (dt.getDataURL().length == 1) {
header.put("data_url", dt.getDataURL()[0]);
}
if (dt.getAttrmap().keySet().size() > 0) {
header.put("attr", dt.getAttrmap());
}
// TODO 後でcourseの仕様に合わせる
List<Map<String, Object>> grade = new ArrayList<Map<String, Object>>();
for (Course g : dt.getCourse()[0]) {
Map<String, Object> m = new HashMap<String, Object>();
m.put("name", g.getName());
// m.put("md5", g.getHash());
m.put("style", g.getStyle());
grade.add(m);
}
header.put("course", grade);
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(header);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(jsonheader), "UTF-8");
osw.write(json);
osw.flush();
osw.close();
} catch (Exception e) {
// controller.showErrorMessage("難易度表の保存に失敗しました");
Logger.getGlobal().severe("難易度表の保存中の例外:" + e.getMessage());
}
}
/**
* 難易度表モデルをJSONヘッダ部/データ部にエンコードし、指定のファイルに保存する
*
* @param dt
* エンコードする難易度表モデル
* @param jsonheader
* JSONヘッダ部ファイル
* @param jsondata
* JSONデータ部ファイル
*/
public void encodeJSONTableData(DifficultyTable dt, File jsonheader, File jsondata) {
try {
dt.setDataURL(new String[] { jsondata.getName() });
// ヘッダ部のエクスポート
this.encodeJSONTableHeader(dt, jsonheader);
// データ部のエクスポート
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
for (DifficultyTableElement te : dt.getElements()) {
datas.add(te.getValues());
}
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
String json = objectMapper.writeValueAsString(datas);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(jsondata), "UTF-8");
osw.write(json);
osw.flush();
osw.close();
} catch (Exception e) {
// controller.showErrorMessage("難易度表の保存に失敗しました");
Logger.getGlobal().severe("難易度表の保存中の例外:" + e.getMessage());
}
}
/**
* 旧難易度表フォーマットを解析する。現在は使用していない
*
* @param dt
* @param mark
* 難易度表マーク
* @param isr
* 難易度表ストリームリーダー
* @param saveElement
* 要素を保存するかどうか
* @return 難易度表データ
* @throws NumberFormatException
* @throws IOException
*/
private DifficultyTable parseDifficultyTable(DifficultyTable dt, String mark, InputStreamReader isr,
boolean saveElement) throws NumberFormatException, IOException {
// System.out.println("難易度表チェック...");
String line = null;
BufferedReader br = new BufferedReader(isr);
boolean diff = false;
int state = -1;
List<DifficultyTableElement> result = new ArrayList<DifficultyTableElement>();
DifficultyTableElement dte = null;
Pattern p = Pattern.compile("\"");
dt.removeAllElements();
Pattern first = Pattern.compile("\\s*\\[\\s*\\d+,\\s*\"" + mark + ".+\"\\s*,.*");
while ((line = br.readLine()) != null) {
if (line.contains("var mname = [")) {
// System.out.println("難易度表を検出しました");
diff = true;
}
if (line.contains("</script>")) {
diff = false;
}
if (diff && state == -1 && first.matcher(line).matches()) {
dte = new DifficultyTableElement();
String did = p.split(line)[1].substring(mark.length());
// dte.setID(p.split(line)[0].replaceAll("[\\[\\s,]", ""));
dte.setLevel(did);
state = 0;
}
if (state >= 0) {
switch (state) {
case 0:
state++;
break;
case 1:
// 曲名
dte.setTitle(p.split(line)[1]);
state++;
break;
case 2:
// bmsid
dte.setBMSID(Integer.parseInt(p.split(line)[1].replaceAll("[\\s]", "")));
state++;
break;
case 3:
// URL1
String[] split = p.split(line)[1].split("'");
if (split.length > 2) {
dte.setURL(split[1]);
}
split = p.split(line)[1].split("<[bB][rR]\\s*/*>");
dte.setArtist(split[0].replaceFirst("<[aA]\\s[hH][rR][eE][fF]=.+'>|</[aA]>", "").replaceFirst(
"</[aA]>", ""));
// URL1サブ
if (split.length > 1) {
String[] split2 = split[1].split("'");
if (split2.length > 2) {
dte.setPackageURL(split2[1]);
}
dte.setPackageName(split[1].replaceFirst("<[aA]\\s[hH][rR][eE][fF]=.+'>|</[aA]>", "")
.replaceFirst("</[aA]>", ""));
}
state++;
break;
case 4:
// URL2
String[] split3 = p.split(line)[1].split("'");
if (split3.length > 2) {
dte.setAppendURL(split3[1]);
}
dte.setAppendArtist(p.split(line)[1].replaceFirst("<[aA]\\s[hH][rR][eE][fF]=.+'>|</[aA]>", "")
.replaceFirst("</[aA]>", ""));
state++;
break;
case 5:
// コメント
dte.setComment(p.split(line)[1].replaceFirst("Avg:.*JUDGE:[A-Z]+\\s*", ""));
result.add(dte);
dte = null;
state = -1;
break;
}
}
}
if (saveElement) {
for (int i = 0; i < result.size(); i++) {
dt.addElement(result.get(i));
}
}
if (dt.getLevelDescription().length == 0) {
List<String> l = new ArrayList<String>();
for (int i = 0; i < result.size(); i++) {
boolean b = true;
for (int j = 0; j < l.size(); j++) {
if (l.get(j).equals(result.get(i).getLevel())) {
b = false;
}
}
if (b) {
l.add(result.get(i).getLevel());
}
}
dt.setLevelDescription(l.toArray(new String[0]));
}
// System.out.println("難易度表リスト抽出完了 リスト数:" + dt.getElements().length);
return dt;
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.sp;
import org.springframework.stereotype.Component;
import pl.edu.icm.unity.server.utils.RemoteAuthenticationContextManagement;
/**
* Singleton component managing SAML contexts used in all remote authentications currently handled by the server.
* See {@link RemoteAuthenticationContextManagement}.
* @author K. Benedyczak
*/
@Component
public class SamlContextManagement extends RemoteAuthenticationContextManagement<RemoteAuthnContext>
{
}
|
package msip.go.kr.board.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import msip.go.kr.board.entity.BoardMaster;
import msip.go.kr.board.service.BoardMasterService;
import msip.go.kr.common.entity.Tree;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
/**
* BoardMaster entity 관련 업무 처리를 위한 Sevice Interface 구현 클래스 정의
*
* @author 정승철
* @since 2015.07.10
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.10 정승철 최초생성
* 2015.07.31 양준호 findAll(boolean isUse) 추가
* </pre>
*/
@Service("boardMasterService")
@Transactional(rollbackFor = { Exception.class }, propagation = Propagation.REQUIRED)
public class BoardMasterServiceImpl extends EgovAbstractServiceImpl implements BoardMasterService {
/** boardMasterDAO */
@Resource(name="boardMasterDAO")
private BoardMasterDAO boardMasterDAO;
/**
* 선택된 id에 따라 게시판 속성 entity 정보를 데이터베이스에서 삭제하도록 요청
* @param CopMaster entity
* @throws Exception
*/
public void remove(BoardMaster entity) throws Exception {
boardMasterDAO.remove(entity);
}
/**
* 새로운 게시판 속성 entity 정보를 입력받아 데이터베이스에 저장하도록 요청
* @param CopMaster entity
* @return Long
* @throws Exception
*/
public void persist(BoardMaster entity) throws Exception {
/* BoardMaster entity정보 등록 */
entity.setIsuse(true);
entity.setRegDate(new Date());
boardMasterDAO.persist(entity);
}
/**
* 전체 게시판 속성 entity 목록을 데이터베이스에서 읽어와 화면에 출력하도록 요청
* @return List<BoardMaster> 산하기관 BoardMaster entity 목록
* @throws Exception
*/
public List<BoardMaster> findAll() throws Exception {
return boardMasterDAO.findAll();
}
/**
* 사용여부에 따른 게시판 속성 목록을 조회하여 출력하도록 요청
* @param isUse 사용여부
* @return List<BoardMaster> BoardMaster entity 목록
* @throws Exception
*/
@Override
public List<BoardMaster> findAll(boolean isuse) throws Exception {
return boardMasterDAO.findAll(isuse);
}
/**
* 수정된 게시판 속성 entity 정보를 데이터베이스에 반영하도록 요청
* @param CopMaster entity
* @throws Exception
*/
public void merge(BoardMaster entity) throws Exception {
boardMasterDAO.merge(entity);
}
/**
* 선택된 id에 따라 데이터베이스에서 게시판 속성 entity 정보를 읽어와 화면에 출력하도록 요청
* @param Long id
* @return BoardMaster entity
* @throws Exception
*/
public BoardMaster findById(Long id) throws Exception {
BoardMaster result = boardMasterDAO.findById(id);
if(result==null)
throw processException("info.nodata.msg");
return result;
}
/**
* 게시판 속성 목록을 Tree 컴포넌트 용 목록으로 출력하도록 요청
* @param Long id
* @return List<Tree>
* @throws Exception
*/
@Override
public List<Tree> treeList() throws Exception {
List<Tree> treeList = new ArrayList<Tree>();
List<BoardMaster> list = boardMasterDAO.findAll();
for(BoardMaster entity : list) {
Tree t = new Tree();
t.setId(entity.getId().toString());
t.setParent("#");
t.setText(entity.getBoardNm());
treeList.add(t);
}
return treeList;
}
}
|
package com.codemybrainsout.onboarder;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import com.twitter.sdk.android.tweetcomposer.TweetComposer;
public class AhoyOnboarderTextInputShareOptionFragment extends AhoyOnboarderTextInputFragment
{
private static final String AHOY_PAGE_TITLE = "ahoy_page_title";
private static final String AHOY_PAGE_SHARE_TITLE = "ahoy_page_share_title";
private static final String AHOY_PAGE_TITLE_RES_ID = "ahoy_page_title_res_id";
private static final String AHOY_PAGE_TITLE_COLOR = "ahoy_page_title_color";
private static final String AHOY_PAGE_SHARE_TITLE_COLOR = "ahoy_page_share_title_color";
private static final String AHOY_PAGE_TITLE_TEXT_SIZE = "ahoy_page_title_text_size";
private static final String AHOY_PAGE_DESCRIPTION = "ahoy_page_description";
private static final String AHOY_PAGE_DESCRIPTION_RES_ID = "ahoy_page_description_res_id";
private static final String AHOY_PAGE_DESCRIPTION_COLOR = "ahoy_page_description_color";
private static final String AHOY_PAGE_DESCRIPTION_TEXT_SIZE = "ahoy_page_description_text_size";
private static final String AHOY_PAGE_IMAGE_RES_ID = "ahoy_page_image_res_id";
private static final String AHOY_PAGE_IMAGE_ACCEPT_RES_ID = "ahoy_page_image_accept_res_id";
private static final String AHOY_PAGE_IMAGE_REJECT_RES_ID = "ahoy_page_image_reject_res_id";
private static final String AHOY_PAGE_BACKGROUND_COLOR = "ahoy_page_background_color";
private static final String AHOY_PAGE_ICON_WIDTH = "ahoy_page_icon_width";
private static final String AHOY_PAGE_ICON_HEIGHT = "ahoy_page_icon_height";
private static final String AHOY_PAGE_MARGIN_LEFT = "ahoy_page_margin_left";
private static final String AHOY_PAGE_MARGIN_RIGHT = "ahoy_page_margin_right";
private static final String AHOY_PAGE_MARGIN_TOP = "ahoy_page_margin_top";
private static final String AHOY_PAGE_MARGIN_BOTTOM = "ahoy_page_margin_bottom";
private String title;
private String shareTitle;
private String hint;
@StringRes
private int titleResId;
@ColorRes
private int titleColor;
@ColorRes
private int shareTitleColor;
@StringRes
private int hintResId;
@ColorRes
private int backgroundColor;
@ColorRes
private int hintColor;
@DrawableRes
private int imageResId;
@DrawableRes
private int imageAcceptResId;
@DrawableRes
private int imageRejectResId;
private float titleTextSize;
private float hintTextSize;
private View view;
private FloatingActionButton fabOnBoarderImage;
private TextView tvOnboarderTitle;
private EditText etxtOnboarderInput;
private TextInputLayout tilOnboarderInput;
private TextView txtvShareTitle;
private CardView cardView;
private SwipeRefreshLayout srLayLoading;
private ImageView btnFb;
private ImageView btnTw;
private ImageView btnWa;
private int iconHeight, iconWidth;
private int marginTop, marginBottom, marginLeft, marginRight;
private OnTextInputProvidedListener onTextInputProvidedListener;
private int inputClass;
private int inputVariation;
private int currentIconResId;
private boolean fabVisible = false;
public AhoyOnboarderTextInputShareOptionFragment()
{
}
public static AhoyOnboarderTextInputShareOptionFragment newInstance(AhoyOnboarderCard card, OnTextInputProvidedListener onTextInputProvidedListener)
{
Bundle args = new Bundle();
args.putString(AHOY_PAGE_TITLE, card.getTitle());
args.putString(AHOY_PAGE_SHARE_TITLE, card.getShareTitle());
args.putString(AHOY_PAGE_DESCRIPTION, card.getDescription());
args.putInt(AHOY_PAGE_TITLE_RES_ID, card.getTitleResourceId());
args.putInt(AHOY_PAGE_DESCRIPTION_RES_ID, card.getDescriptionResourceId());
args.putInt(AHOY_PAGE_TITLE_COLOR, card.getTitleColor());
args.putInt(AHOY_PAGE_SHARE_TITLE_COLOR, card.getShareTitleColor());
args.putInt(AHOY_PAGE_DESCRIPTION_COLOR, card.getDescriptionColor());
args.putInt(AHOY_PAGE_IMAGE_RES_ID, card.getImageResourceId());
args.putInt(AHOY_PAGE_IMAGE_ACCEPT_RES_ID, card.getImageAcceptResourceId());
args.putInt(AHOY_PAGE_IMAGE_REJECT_RES_ID, card.getImageRejectResourceId());
args.putFloat(AHOY_PAGE_TITLE_TEXT_SIZE, card.getTitleTextSize());
args.putFloat(AHOY_PAGE_DESCRIPTION_TEXT_SIZE, card.getDescriptionTextSize());
args.putInt(AHOY_PAGE_BACKGROUND_COLOR, card.getBackgroundColor());
args.putInt(AHOY_PAGE_ICON_HEIGHT, card.getIconHeight());
args.putInt(AHOY_PAGE_ICON_WIDTH, card.getIconWidth());
args.putInt(AHOY_PAGE_MARGIN_LEFT, card.getMarginLeft());
args.putInt(AHOY_PAGE_MARGIN_RIGHT, card.getMarginRight());
args.putInt(AHOY_PAGE_MARGIN_TOP, card.getMarginTop());
args.putInt(AHOY_PAGE_MARGIN_BOTTOM, card.getMarginBottom());
AhoyOnboarderTextInputShareOptionFragment fragment = new AhoyOnboarderTextInputShareOptionFragment();
fragment.setArguments(args);
//Set listeners & other inits
fragment.setListener(onTextInputProvidedListener);
fragment.setInputType(card.getInputClass(), card.getInputVariation());
return fragment;
}
@Override
public void onAttach(Context context)
{
super.onAttach(context);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle bundle = getArguments();
title = bundle.getString(AHOY_PAGE_TITLE, null);
shareTitle = bundle.getString(AHOY_PAGE_SHARE_TITLE, null);
titleResId = bundle.getInt(AHOY_PAGE_TITLE_RES_ID, 0);
titleColor = bundle.getInt(AHOY_PAGE_TITLE_COLOR, 0);
shareTitleColor = bundle.getInt(AHOY_PAGE_SHARE_TITLE_COLOR, 0);
titleTextSize = bundle.getFloat(AHOY_PAGE_TITLE_TEXT_SIZE, 0f);
hint = bundle.getString(AHOY_PAGE_DESCRIPTION, null);
hintResId = bundle.getInt(AHOY_PAGE_DESCRIPTION_RES_ID, 0);
hintColor = bundle.getInt(AHOY_PAGE_DESCRIPTION_COLOR, 0);
hintTextSize = bundle.getFloat(AHOY_PAGE_DESCRIPTION_TEXT_SIZE, 0f);
imageResId = bundle.getInt(AHOY_PAGE_IMAGE_RES_ID, 0);
imageAcceptResId = bundle.getInt(AHOY_PAGE_IMAGE_ACCEPT_RES_ID, 0);
imageRejectResId = bundle.getInt(AHOY_PAGE_IMAGE_REJECT_RES_ID, 0);
backgroundColor = bundle.getInt(AHOY_PAGE_BACKGROUND_COLOR, 0);
iconWidth = bundle.getInt(AHOY_PAGE_ICON_WIDTH, (int) dpToPixels(128, getActivity()));
iconHeight = bundle.getInt(AHOY_PAGE_ICON_HEIGHT, (int) dpToPixels(128, getActivity()));
marginTop = bundle.getInt(AHOY_PAGE_MARGIN_TOP, (int) dpToPixels(80, getActivity()));
marginBottom = bundle.getInt(AHOY_PAGE_MARGIN_BOTTOM, (int) dpToPixels(0, getActivity()));
marginLeft = bundle.getInt(AHOY_PAGE_MARGIN_LEFT, (int) dpToPixels(0, getActivity()));
marginRight = bundle.getInt(AHOY_PAGE_MARGIN_RIGHT, (int) dpToPixels(0, getActivity()));
view = inflater.inflate(R.layout.fragment_ahoy_text_input_share_option, container, false);
fabOnBoarderImage = (FloatingActionButton) view.findViewById(R.id.fab_image);
tvOnboarderTitle = (TextView) view.findViewById(R.id.tv_title);
etxtOnboarderInput = (EditText) view.findViewById(R.id.etxt_input);
tilOnboarderInput = (TextInputLayout) view.findViewById(R.id.til_input);
txtvShareTitle = (TextView) view.findViewById(R.id.txtvShareTitle);
btnFb = (ImageView) view.findViewById(R.id.btnFacebook);
btnWa = (ImageView) view.findViewById(R.id.btnWhatsapp);
btnTw = (ImageView) view.findViewById(R.id.btnTwitter);
cardView = (CardView) view.findViewById(R.id.cv_cardview);
srLayLoading = (SwipeRefreshLayout) view.findViewById(R.id.srLay_loading);
etxtOnboarderInput.setInputType(inputClass | inputVariation);
if (title != null)
{
tvOnboarderTitle.setText(title);
}
if (shareTitle != null)
{
txtvShareTitle.setText(shareTitle);
}
if (titleResId != 0)
{
tvOnboarderTitle.setText(getResources().getString(titleResId));
}
if (hint != null)
{
etxtOnboarderInput.setHint(hint);
}
if (hintResId != 0)
{
etxtOnboarderInput.setHint(getResources().getString(hintResId));
}
if (titleColor != 0)
{
tvOnboarderTitle.setTextColor(ContextCompat.getColor(getActivity(), titleColor));
}
if(shareTitleColor != 0)
{
txtvShareTitle.setTextColor(ContextCompat.getColor(getActivity(), shareTitleColor));
}
if (hintColor != 0)
{
etxtOnboarderInput.setHintTextColor(ContextCompat.getColor(getActivity(), hintColor));
}
if (imageResId != 0)
{
showEnterIcon();
}
if (titleTextSize != 0f)
{
tvOnboarderTitle.setTextSize(titleTextSize);
}
if (hintTextSize != 0f)
{
etxtOnboarderInput.setTextSize(hintTextSize);
}
if (backgroundColor != 0)
{
cardView.setCardBackgroundColor(ContextCompat.getColor(getActivity(), backgroundColor));
}
// if (iconWidth != 0 && iconHeight != 0)
// {
// FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(iconWidth, iconHeight);
// layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
// layoutParams.setMargins(marginLeft, marginTop, marginRight, marginBottom);
// ivOnboarderImage.setLayoutParams(layoutParams);
// }
//Set text watcher to provide input as it is typed
etxtOnboarderInput.addTextChangedListener(new TextWatcher()
{
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
{
onSendInput();
}
@Override
public void afterTextChanged(Editable editable)
{
}
});
etxtOnboarderInput.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent)
{
onTextInputProvidedListener.onImeEnterPressed(tilOnboarderInput);
return false;
}
});
//Set msg
final String shareMsg = getString(R.string.shareAppMsg);
//Set sharing btn on click listeners
btnFb.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
ShareDialog shareDialog = new ShareDialog(getActivity());
//Create link content
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(getString(R.string.appUrlANDROID)))
.setQuote(shareMsg).build();
shareDialog.show(linkContent);
}
});
btnWa.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
whatsappIntent.setType("text/plain");
whatsappIntent.setPackage("com.whatsapp");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, shareMsg + getString(R.string.appUrlANDROID));
try
{
getActivity().startActivity(whatsappIntent);
}
catch (android.content.ActivityNotFoundException ex)
{
Snackbar.make(btnWa, getString(R.string.WANotInstalled), Snackbar.LENGTH_LONG).show();
}
}
});
btnTw.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Uri imageUri = Uri.parse("android.resource://io.flyingmongoose.brave/drawable/ic_share");
TweetComposer.Builder builder = new TweetComposer.Builder(getActivity())
.text(shareMsg + getString(R.string.appUrlANDROID))
.image(imageUri);
builder.show();
}
});
initLoadingCircle();
return view;
}
private void initLoadingCircle()
{
srLayLoading.setEnabled(false);
srLayLoading.setColorSchemeColors(getResources().getColor(R.color.FlatLightBlue), getResources().getColor(R.color.Red), getResources().getColor(R.color.SeaGreen));
srLayLoading.setProgressBackgroundColor(R.color.CircleProgLoadingColor);
srLayLoading.setProgressViewOffset(true, 0, 8);
}
public float dpToPixels(int dp, Context context)
{
return dp * (context.getResources().getDisplayMetrics().density);
}
@Override
public void onDetach()
{
super.onDetach();
}
public CardView getCardView()
{
return cardView;
}
public TextView getTitleView()
{
return tvOnboarderTitle;
}
public EditText getInputView()
{
return etxtOnboarderInput;
}
public TextInputLayout getTextInputView(){return tilOnboarderInput;}
public void setListener(OnTextInputProvidedListener onTextInputProvidedListener)
{
this.onTextInputProvidedListener = onTextInputProvidedListener;
}
public void onSendInput()
{
//Send the imput to the listener interface provided with this item
String inputText = etxtOnboarderInput.getText().toString().trim();
onTextInputProvidedListener.onInputProvided(inputText, tilOnboarderInput);
}
public void onValidate(boolean fromScroll)
{
//Send the imput to the listener interface provided with this item
String inputText = etxtOnboarderInput.getText().toString().trim();
onTextInputProvidedListener.onValidate(inputText, tilOnboarderInput, fromScroll);
}
public void animateFloat()
{
Animation animFloat;
if(!fabVisible)
{
animFloat = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_float_register);
fabVisible = true;
}
else
animFloat = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_float_register_no_fade_in);
fabOnBoarderImage.startAnimation(animFloat);
}
public void setInputType(int inputClass, int inputVariation)
{
this.inputClass = inputClass;
this.inputVariation = inputVariation;
}
public void showAcceptIcon()
{
if(currentIconResId != imageAcceptResId)
{
animatePopIn();
fabOnBoarderImage.setImageDrawable(ContextCompat.getDrawable(getActivity(), imageAcceptResId));
currentIconResId = imageAcceptResId;
}
}
public void showRejectIcon()
{
if(currentIconResId != imageRejectResId)
{
animatePopIn();
fabOnBoarderImage.setImageDrawable(ContextCompat.getDrawable(getActivity(), imageRejectResId));
currentIconResId = imageRejectResId;
}
}
public void showEnterIcon()
{
if(currentIconResId != imageResId)
{
animatePopIn();
fabOnBoarderImage.setImageDrawable(ContextCompat.getDrawable(getActivity(), imageResId));
currentIconResId = imageResId;
}
}
private void animatePopIn()
{
fabOnBoarderImage.clearAnimation();
Animation popin = AnimationUtils.loadAnimation(getActivity(), R.anim.pop_in);
popin.setAnimationListener(new Animation.AnimationListener()
{
@Override
public void onAnimationStart(Animation animation)
{
}
@Override
public void onAnimationEnd(Animation animation)
{
animateFloat();
}
@Override
public void onAnimationRepeat(Animation animation)
{
}
});
fabOnBoarderImage.startAnimation(popin);
}
public String getInputData()
{
Log.d("debugRegister", "Value from frag: " + etxtOnboarderInput.getText().toString().trim());
return etxtOnboarderInput.getText().toString().trim();
}
public void animateLoading(boolean loading)
{
if(loading)
srLayLoading.setRefreshing(true);
else
srLayLoading.setRefreshing(false);
}
}
|
package com.citibank.ods.entity.pl;
import com.citibank.ods.entity.pl.valueobject.TbgSystemEntityVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
*@author michele.monteiro,02/05/2007
*/
public class TbgSystemEntity extends BaseTbgSystemEntity
{
/**
* Cria novo objeto TplEntryInterEntity
*/
public TbgSystemEntity()
{
m_data = new TbgSystemEntityVO();
}
}
|
package pl.basistam.zad2;
import org.xml.sax.SAXException;
import pl.basistam.zad3.books.Books;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.SchemaFactory;
import java.io.File;
public class Reader {
public void read() throws JAXBException, SAXException {
final File inputFile = new File("books.xml");
if (!inputFile.exists()) {
System.err.println("Plik nie istneieje");
return;
}
JAXBContext context = JAXBContext.newInstance(Books.class);
Unmarshaller um = context.createUnmarshaller();
um.setSchema(SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(new File("books.xsd")));
Books books = (Books) um.unmarshal(inputFile);
books.print();
}
}
|
package main.java;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
import sx.blah.discord.handle.obj.Status;
import sx.blah.discord.util.DiscordException;
public class Bot {
public static IDiscordClient discordClient;
/**
* Main function
* @param args the token
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if (args.length < 1) // If no args are passed
System.out.print("You need to specify a token before continuing"); // Tell the user
discordClient = new ClientBuilder() // Make a new client instance
.withToken(args[0]) // with the token passed in the build arguments
.login(); // and login
discordClient.getModuleLoader().loadModule(new GeneralCommands()); // Add the GeneralCommands Module
discordClient.getModuleLoader().loadModule(new CommandModule()); // Add the CommandModule Module
// Wait until the bit is fully connected
while (!discordClient.isReady()) {
Thread.sleep(100);
}
discordClient.changeStatus(Status.stream("Discord4J", "https://austinv11.github.io/Discord4J/")); // Change the bot's presence
}
/**
* @param token the unique ID of a bot
* @return a new client instance
* @throws DiscordException
*/
public static IDiscordClient login(String token) throws DiscordException {
return new ClientBuilder().withToken(token).login();
}
/**
* @return The connected Discord client
*/
public static IDiscordClient getDiscordClient() {
return discordClient;
}
}
|
package edu.nyu.cs9053.homework4.hierarchy;
import java.util.Objects;
public class Swamp extends BodyOfWater {
private final int swampParameter;
public Swamp(String name, double volume, int swampParameter) {
super(name, volume);
this.swampParameter = swampParameter;
}
public int getSwampParameter() {
return swampParameter;
}
@Override
public String getDescription() {
return String.format("a swamp with parameter %d", swampParameter);
}
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Swamp other = (Swamp) otherObject;
return swampParameter == other.swampParameter && getName().equals(other.getName()) && getVolume() == other.getVolume();
}
@Override
public int hashCode() {
return 7 * Objects.hashCode(getName()) + 11 * Integer.hashCode(swampParameter) + 13 * Double.hashCode(getVolume());
}
}
|
package com.test.utilities;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.aeonbits.owner.ConfigFactory;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class TestEnv {
Environment testEnvironment;
@Test
public void functionalTest() {
System.out.println(testEnvironment.url());
System.out.println(testEnvironment.username());
System.out.println(testEnvironment.getPassword());
}
@BeforeTest
@Parameters({"environment"})
public void beforeTest(String environemnt) {
ConfigFactory.setProperty("env", environemnt);
testEnvironment=ConfigFactory.create(Environment.class);
}
}
|
package be.dpms.medwan.webapp.wo.authentication;
import be.dpms.medwan.common.model.IConstants;
import java.util.Hashtable;
/**
* Created by IntelliJ IDEA.
* User: MichaŽl
* Date: 15-avr.-2003
* Time: 10:59:16
* To change this template use Options | File Templates.
*/
public class AuthenticationTokenWO {
private Hashtable hashtable = null;
public AuthenticationTokenWO() {
hashtable = new Hashtable();
}
public void setInitialHTTPRequest(String initialHTTPRequest) {
hashtable.put(IConstants.AUTHENTICATION_TOKEN_INITIAL_HTTP_REQUEST, initialHTTPRequest);
}
public String getInitialHTTPRequest() {
return (String)hashtable.get(IConstants.AUTHENTICATION_TOKEN_INITIAL_HTTP_REQUEST);
}
}
|
package br.senai.sp.jandira.app;
import br.senai.sp.jandira.lista.TipoConta;
import br.senai.sp.jandira.model.Agencia;
import br.senai.sp.jandira.model.Cliente;
import br.senai.sp.jandira.model.Conta;
public class App {
public static void main(String[] args) {
//Criação da Agência que os Todos os Clientes Fazem Parte
Agencia agenciaTeste = new Agencia();
agenciaTeste.setNomeGerente("Carlos Eduardo Novaes");
agenciaTeste.setNumeroAgencia("4214-9");
agenciaTeste.setTelefone("4194-5549");
agenciaTeste.setCidadeDaAgencia("Barueri");
// Criação a cliente Maria
Cliente clienteMaria = new Cliente();
clienteMaria.setNome("Maria Antonieta");
clienteMaria.setEmail("mariaantonieta@gmail.com");
clienteMaria.setSalario(5000.00);
// Criação da conta da Maria
Conta contaMaria = new Conta("7845-8");
contaMaria.setCliente(clienteMaria);
contaMaria.setAgencia(agenciaTeste);
contaMaria.depositar(500.00);
contaMaria.setTipo(TipoConta.CORRENTE);
System.out.println(contaMaria.getTipo());
System.out.println(contaMaria.getAgencia().getNumeroAgencia());
// Criação o cliente Pedro
Cliente clientePedro = new Cliente();
clientePedro.setNome("Pedro Cabral");
clientePedro.setEmail("pedrocabral@gmail.com");
clientePedro.setSalario(1000.00);
// Criação da conta do Pedro
Conta contaPedro = new Conta("6547-6");
contaPedro.setCliente(clientePedro);
contaPedro.depositar(200);
contaPedro.setTipo(TipoConta.SALARIO);
contaPedro.setAgencia(agenciaTeste);
System.out.println(contaPedro.getTipo());
// Criação o cliente Ana
Cliente clienteAna = new Cliente();
clienteAna.setNome("Ana Gomes");
clienteAna.setEmail("anagomes@gmail.com");
clienteAna.setSalario(5000.00);
// Criação da conta da Ana
Conta contaAna = new Conta("23145-9");
contaAna.setCliente(clienteAna);
contaAna.depositar(2000);
contaAna.setTipo(TipoConta.POUPANCA);
contaAna.setAgencia(agenciaTeste);
System.out.println(contaAna.getTipo());
// Exibir os detalhes das contas
contaMaria.exibirDetalhes();
contaPedro.exibirDetalhes();
contaAna.exibirDetalhes();
System.out.println();
System.out.println("-------------------------");
System.out.println();
// Depositar 100 reais na conta da Maria
contaMaria.depositar(100);
contaMaria.exibirDetalhes();
System.out.println();
System.out.println("-------------------------");
System.out.println();
// Sacar 100 reais na conta da Maria
contaMaria.sacar(300);
contaMaria.exibirDetalhes();
// Transferir 200 da Conta da Maria para a Conta do Pedro
contaMaria.transferir(contaPedro, 2000);
contaMaria.exibirDetalhes();
contaPedro.exibirDetalhes();
}
}
|
package com.minefrance.vampire;
import org.bukkit.Location;
public class Totem {
private String name;
private Location l1;
private Location l2;
private Location spawnLocation;
private String owner;
public Totem(String name, Location l1, Location l2, Location spawnLocation, String owner)
{
this.name = name;
this.l1 = l1;
this.l2 = l2;
this.spawnLocation = spawnLocation;
this.owner = owner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Location getL1() {
return l1;
}
public void setL1(Location l1) {
this.l1 = l1;
}
public Location getL2() {
return l2;
}
public void setL2(Location l2) {
this.l2 = l2;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
|
package sonto.common;
public abstract class KeyValue {
public String key;
public Object value;
public KeyValue () {
}
public KeyValue (String key, Object v) {
this.key = key;
this.value = v;
}
public KeyValue (String key, int v) {
this (key, new Integer (v));
}
public KeyValue (String key, boolean v) {
this (key, new Boolean (v));
}
public KeyValue (String key, float f) {
this (key, new Float (f));
}
}
|
package com.tvm.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectClassDeclaration {
public static void main(String[] args) {
try {
Class<?> myClass = Class.forName("com.tvm.reflection.MyClass");
System.out.println(
"Canonical Form " + myClass.getCanonicalName() + " Modifiers " + myClass.getModifiers());
Field field = myClass.getDeclaredField("name");
System.out.println(field.getName() + " " + field.getModifiers());
Field[] fieldArray = myClass.getDeclaredFields();
for (Field fields : fieldArray) {
System.out.println("Field available in class = " + fields);
}
Method getIdThroughReflect = myClass.getDeclaredMethod("getId", null);
Method setIdThroughReflect = myClass.getDeclaredMethod("setId", String.class);
System.out.println("Return Type of getId() " + getIdThroughReflect.getReturnType());
System.out.println("Return Type of setId() " + setIdThroughReflect.getReturnType());
Method[] methods = myClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println("method available in class = " + method.getName());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
/*
Canonical Form com.tvm.reflection.MyClass Modifiers 1
name 2
Field available in class = private java.lang.String com.tvm.reflection.MyClass.name
Field available in class = private java.lang.String com.tvm.reflection.MyClass.id
Return Type of getId() class java.lang.String
Return Type of setId() void
method available in class = setId
method available in class = getName
method available in class = setName
method available in class = getId
*/
|
package fr.ucbl.disp.vfos.controller.service;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface CPSLocalService {
@WebMethod String getCPSStatutJSON(String name);
@WebMethod String setCPSStatutJSON(String name);
@WebMethod String getLastDecision(String name);
@WebMethod String get5LastDecision(String name);
@WebMethod String getPredictDecision(String name);
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.web.servlet.mvc.method.annotation;
import jakarta.servlet.ServletException;
import org.junit.jupiter.api.AfterEach;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.lang.Nullable;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;
import org.springframework.web.testfixture.servlet.MockServletConfig;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Base class for tests using on the DispatcherServlet and HandlerMethod infrastructure classes:
* <ul>
* <li>RequestMappingHandlerMapping
* <li>RequestMappingHandlerAdapter
* <li>ExceptionHandlerExceptionResolver
* </ul>
*
* @author Rossen Stoyanchev
*/
public abstract class AbstractServletHandlerMethodTests {
@Nullable
private DispatcherServlet servlet;
protected DispatcherServlet getServlet() {
assertThat(servlet).as("DispatcherServlet not initialized").isNotNull();
return servlet;
}
@AfterEach
public void tearDown() {
this.servlet = null;
}
/**
* Initialize a DispatcherServlet instance registering zero or more controller classes.
*/
protected WebApplicationContext initDispatcherServlet(
Class<?> controllerClass, boolean usePathPatterns) throws ServletException {
return initDispatcherServlet(controllerClass, usePathPatterns, null);
}
@SuppressWarnings("serial")
WebApplicationContext initDispatcherServlet(
@Nullable Class<?> controllerClass, boolean usePathPatterns,
@Nullable ApplicationContextInitializer<GenericWebApplicationContext> initializer)
throws ServletException {
final GenericWebApplicationContext wac = new GenericWebApplicationContext();
servlet = new DispatcherServlet() {
@Override
protected WebApplicationContext createWebApplicationContext(@Nullable WebApplicationContext parent) {
if (controllerClass != null) {
wac.registerBeanDefinition(
controllerClass.getSimpleName(), new RootBeanDefinition(controllerClass));
}
if (initializer != null) {
initializer.initialize(wac);
}
if (!wac.containsBeanDefinition("handlerMapping")) {
BeanDefinition def = register("handlerMapping", RequestMappingHandlerMapping.class, wac);
def.getPropertyValues().add("removeSemicolonContent", "false");
}
BeanDefinition mappingDef = wac.getBeanDefinition("handlerMapping");
if (!usePathPatterns) {
mappingDef.getPropertyValues().add("patternParser", null);
}
register("handlerAdapter", RequestMappingHandlerAdapter.class, wac);
register("requestMappingResolver", ExceptionHandlerExceptionResolver.class, wac);
register("responseStatusResolver", ResponseStatusExceptionResolver.class, wac);
register("defaultResolver", DefaultHandlerExceptionResolver.class, wac);
wac.refresh();
return wac;
}
};
MockServletConfig config = new MockServletConfig();
config.addInitParameter("jakarta.servlet.http.legacyDoHead", "true");
servlet.init(config);
return wac;
}
private BeanDefinition register(String beanName, Class<?> beanType, GenericWebApplicationContext wac) {
if (wac.containsBeanDefinition(beanName)) {
return wac.getBeanDefinition(beanName);
}
RootBeanDefinition beanDef = new RootBeanDefinition(beanType);
wac.registerBeanDefinition(beanName, beanDef);
return beanDef;
}
}
|
/**
*/
package iso20022;
import java.lang.String;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Sender Asynchronicity</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* characteristic from the MessageTransport, indicating whether a sending Messaging Endpoint blocks after sending a TransportMessage to the MessageTransportSystem while waiting for a response from a MessagingEndpoint
* <!-- end-model-doc -->
* @see iso20022.Iso20022Package#getSenderAsynchronicity()
* @model
* @generated
*/
public enum SenderAsynchronicity implements Enumerator {
/**
* The '<em><b>ENDPOINT SYNCHRONOUS</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #ENDPOINT_SYNCHRONOUS_VALUE
* @generated
* @ordered
*/
ENDPOINT_SYNCHRONOUS(0, "ENDPOINT_SYNCHRONOUS", "ENDPOINT_SYNCHRONOUS"),
/**
* The '<em><b>CONVERSATION SYNCHRONOUS</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CONVERSATION_SYNCHRONOUS_VALUE
* @generated
* @ordered
*/
CONVERSATION_SYNCHRONOUS(1, "CONVERSATION_SYNCHRONOUS", "CONVERSATION_SYNCHRONOUS"),
/**
* The '<em><b>ASYNCHRONOUS</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #ASYNCHRONOUS_VALUE
* @generated
* @ordered
*/
ASYNCHRONOUS(2, "ASYNCHRONOUS", "ASYNCHRONOUS");
/**
* The '<em><b>ENDPOINT SYNCHRONOUS</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The sending MessagingEndpoint blocks the sending and receipt of other TransportMessages while waiting for a response to the sent TransportMessage.
* <!-- end-model-doc -->
* @see #ENDPOINT_SYNCHRONOUS
* @model
* @generated
* @ordered
*/
public static final int ENDPOINT_SYNCHRONOUS_VALUE = 0;
/**
* The '<em><b>CONVERSATION SYNCHRONOUS</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The sending MessagingEndpoint blocks the sending and receipt of other TransportMessages within the conversation, in which the TransportMessage was sent, while waiting for a response to this sent TransportMessage.
* <!-- end-model-doc -->
* @see #CONVERSATION_SYNCHRONOUS
* @model
* @generated
* @ordered
*/
public static final int CONVERSATION_SYNCHRONOUS_VALUE = 1;
/**
* The '<em><b>ASYNCHRONOUS</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The sending MessagingEndpoint shall not block the sending or receipt of other TransportMessages while waiting for a response to the sent TransportMessage.
* <!-- end-model-doc -->
* @see #ASYNCHRONOUS
* @model
* @generated
* @ordered
*/
public static final int ASYNCHRONOUS_VALUE = 2;
/**
* An array of all the '<em><b>Sender Asynchronicity</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final SenderAsynchronicity[] VALUES_ARRAY =
new SenderAsynchronicity[] {
ENDPOINT_SYNCHRONOUS,
CONVERSATION_SYNCHRONOUS,
ASYNCHRONOUS,
};
/**
* A public read-only list of all the '<em><b>Sender Asynchronicity</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<SenderAsynchronicity> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Sender Asynchronicity</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static SenderAsynchronicity get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
SenderAsynchronicity result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Sender Asynchronicity</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static SenderAsynchronicity getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
SenderAsynchronicity result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Sender Asynchronicity</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static SenderAsynchronicity get(int value) {
switch (value) {
case ENDPOINT_SYNCHRONOUS_VALUE: return ENDPOINT_SYNCHRONOUS;
case CONVERSATION_SYNCHRONOUS_VALUE: return CONVERSATION_SYNCHRONOUS;
case ASYNCHRONOUS_VALUE: return ASYNCHRONOUS;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private SenderAsynchronicity(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //SenderAsynchronicity
|
package bicycles;
import java.util.ArrayList;
import java.util.List;
public class FunRide {
//--
private int max;
private List <Bicycle> bikeList;
public FunRide(int maxNum){
this.max = maxNum;
bikeList = new ArrayList<>();
}
public String accept(Bicycle bicycleType){
//EMPTY LIST SO THAT ANY BIKETYPE CAN ENTER ON IT
if (bikeList.size() < max && !bikeList.contains(bicycleType)) {
bikeList.add(bicycleType);
return "Accepted!";
// BIKETYPE ADDED TO THE LIST NOW I NEEED TO CHECK HOW MANY IN THE LIST
}
return "FUll!";
}
public int getCountForType(BicycleType getType){
int counter = 0;
// I must use a enhanced loop looping through the bikelist
for(Bicycle bike : bikeList ){
if(bike.getBicycleType() == getType){
counter++;
}
}
return counter;
}
//----ACCEPTS BICYCLES AND RETURN THE NUMBER OF THEM ALL
public int getEnteredCount(){
return bikeList.size();
}
}
|
package com.krt.gov.strategy.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.krt.common.util.StringUtils;
import com.krt.gov.device.entity.GovDevice;
import com.krt.gov.device.service.IGovDeviceService;
import com.krt.gov.strategy.service.CallBackService;
import com.krt.gov.thread.CallbackThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class CallBackServiceImpl implements CallBackService {
private static final String URL_AC = "http://localhost:32003/iot-cloud/api/cmd/ac";
private static final String URL_SWT = "http://localhost:32003/iot-cloud/api/cmd/swt";
@Autowired
private IGovDeviceService deviceService;
@Override
public void swt(List<Map> devices){
Integer deviceLen = devices.size();
if( deviceLen > 0 ) {
List<GovDevice> deviceList = new ArrayList<>();
String[] ids = new String[deviceLen];
String[] ctrl = new String[deviceLen];
String[] onOff = new String[deviceLen];
String[] time = new String[deviceLen];
for (int i = 0; i < deviceLen; i++) {
JSONObject action = JSONObject.parseObject(String.valueOf(devices.get(i).get("action")));
ids[i] = String.valueOf(devices.get(i).get("deviceId"));
ctrl[i] = String.valueOf(devices.get(i).get("port"));
onOff[i] = action.getString("onOff");
time[i] = action.getString("time");
action.put("onOff", onOff[i]);
GovDevice updateDevice = new GovDevice();
updateDevice.setId(Integer.valueOf(String.valueOf(devices.get(i).get("dId"))));
updateDevice.setAction(action.toString());
// updateDevice.setStatus(Integer.valueOf(onOff[i])==0?1:0);
deviceList.add(updateDevice);
}
IdentityHashMap map = new IdentityHashMap();
map.put("deviceId", StringUtils.join(ids, ","));
map.put("ctrl", StringUtils.join(ctrl, ","));
map.put("onOff", StringUtils.join(onOff, ","));
map.put("time", StringUtils.join(time, ","));
CallbackThread.add(URL_SWT, map);
if( deviceList.size() > 0 ){
deviceService.updateBatchByIdPort(deviceList);
}
}
}
@Override
public void ac(List<Map> devices) {
Integer deviceLen = devices.size();
if( deviceLen > 0 ) {
List<GovDevice> deviceList = new ArrayList<>();
String[] ids = new String[deviceLen];
String[] power = new String[deviceLen];
String[] mode = new String[deviceLen];
String[] tem = new String[deviceLen];
String[] windSpeed = new String[deviceLen];
for (int i = 0; i < deviceLen; i++) {
JSONObject action = JSONObject.parseObject(String.valueOf(devices.get(i).get("action")));
ids[i] = String.valueOf(devices.get(i).get("deviceId"));
mode[i] = action.getString("mode");
tem[i] = String.valueOf(Integer.valueOf(action.getString("temp"))-16);
power[i] = action.getString("onOff");
windSpeed[i] = "0";
action.put("onOff", power[i]);
GovDevice updateDevice = new GovDevice();
updateDevice.setId(Integer.valueOf(String.valueOf(devices.get(i).get("dId"))));
updateDevice.setAction(action.toString());
updateDevice.setStatus(Integer.valueOf(power[i])==0?1:0);
deviceList.add(updateDevice);
}
IdentityHashMap map = new IdentityHashMap();
map.put("deviceId", StringUtils.join(ids, ","));
map.put("power", StringUtils.join(power, ","));
map.put("mode", StringUtils.join(mode, ","));
map.put("temp", StringUtils.join(tem, ","));
map.put("windSpeed", StringUtils.join(windSpeed, ","));
CallbackThread.add(URL_AC, map);
if( deviceList.size() > 0 ){
deviceService.updateBatchByIdPort(deviceList);
}
}
}
}
|
package com.metaco.api.contracts;
import com.google.gson.annotations.SerializedName;
public class PageDetails {
@SerializedName("number")
private int number;
@SerializedName("size")
private int size;
public PageDetails() {
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
|
package org.umssdiplo.automationv01.stepdefinitionproject;
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.testng.Assert;
import org.umssdiplo.automationv01.core.managepage.Adidas.AdidasHeader;
import org.umssdiplo.automationv01.core.utils.Adidas.AdidasHeaderPage;
public class StepsDefinitionPHPtravel {
private AdidasHeader adidas;
private String priceShoe;
@Given("^'Addidas' page is loaded$")
public void addidasPageIsLoaded() throws Throwable {
adidas=AdidasHeaderPage.loginPage();
}
@And("^Ir al subMenu de Futbol de la columna Tennis$")
public void irAlSubMenuDeFutbolDeLaColumnaTennis() throws Throwable {
adidas.obtenerPrecioProducto();
}
@And("^get price for 'Calzado de Fútbol X' on 'futbol' catalog$")
public void getPriceForCalzadoDeFútbolXOnFutbolCatalog() throws Throwable {
priceShoe = adidas.getPriceShoe();
}
@When("^select size \"([^\"]*)\" on 'Calzado' page$")
public void selectSizeOnCalzadoPage() throws Throwable {
adidas.selectSize();
}
@And("^click 'añadir al carrito' button$")
public void clickAñadirAlCarritoButton() throws Throwable {
adidas.clickCarritoBtn();
}
@Then("^Verify that VIEW SHOOPING BAG is ONE \"([^\"]*)\"$")
public void verifyThatVIEWSHOOPINGBAGIsONE(String cantEsperado) throws Throwable {
String actual = adidas.verifyQuantity();
Assert.assertEquals(actual, cantEsperado, "La cantidad es diferente de 1");
}
@When("^click 'ver carrito' link on VIEW SHOOPING BAG$")
public void clickVerCarritoLinkOnVIEWSHOOPINGBAG() throws Throwable {
adidas.clickVerCarrito();
}
@Then("^Verify \"([^\"]*)\" title is displayed on 'tu carrito' page$")
public void verifyTitleIsDisplayedOnTuCarritoPage(String tituloEsperado) throws Throwable {
String tituloActual = adidas.getTitle();
Assert.assertEquals(tituloActual, tituloEsperado.toUpperCase(), "El titulo no es el esperado");
}
@When("^Quantity should be \"([^\"]*)\" on 'tu carrito' page$")
public void quantityShouldBeOnTuCarritoPage(String cantEsperada) throws Throwable {
String cantActual = adidas.getCantidad();
Assert.assertEquals(cantActual, cantEsperada, "La cantidad es mayor a 1");
}
@Then("^Price should be \"([^\"]*)\"$")
public void priceShouldBe(String priceEsperado) throws Throwable {
String priceActual = adidas.getPriceFinal();
Assert.assertEquals(priceActual, priceEsperado, "Los precios son diferentes");
}
@And("^Total should be \"([^\"]*)\"$")
public void totalShouldBe(String totalEsperado) throws Throwable {
String totalActual = adidas.getTotalPrice();
Assert.assertEquals(totalActual, totalEsperado, "Los precios totales son diferentes");
}
}
|
package lab.heisenbug.sandbox;
import lab.heisenbug.sandbox.payroll.repositories.EmployeeRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by parker on 09/01/2017.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public abstract class SandboxApplicationTest {
}
|
package com.esum.framework.security.crypto.encrypt;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import signgate.crypto.util.CipherUtil;
import com.esum.framework.security.pki.manager.PKIException;
import com.esum.framework.security.pki.manager.info.PKIStoreInfo;
class DataEncryptWithSignGate extends DataEncrypt {
/* (non-Javadoc)
* @see com.esum.framework.security.crypto.encrypt.DataEncrypt#encryptWithAsymmetric(byte[], java.security.cert.Certificate)
*/
public byte[] encryptWithAsymmetric(byte[] data, Certificate cert)
throws NoSuchPaddingException, NoSuchAlgorithmException, CertificateEncodingException,
InvalidKeyException, CertificateException, IllegalStateException,
IllegalBlockSizeException, BadPaddingException {
CipherUtil cipherUtil = new CipherUtil("RSA");
cipherUtil.encryptInit(cert.getEncoded());
byte[] encryptSymmetricKey = cipherUtil.encryptUpdate(data);
cipherUtil.encryptFinal();
return encryptSymmetricKey;
}
/* (non-Javadoc)
* @see com.esum.framework.security.crypto.encrypt.DataEncrypt#decryptWithAsymmetric(byte[], com.esum.framework.security.pki.manager.info.PKIStoreInfo)
*/
public byte[] decryptWithAsymmetric(byte[] encryptedData, PKIStoreInfo pkiStoreInfo)
throws IOException, NoSuchPaddingException, NoSuchAlgorithmException,
InvalidKeyException, IllegalStateException, IllegalBlockSizeException,
BadPaddingException, PKIException {
CipherUtil cipherutil = new CipherUtil("RSA");
cipherutil.decryptInit(pkiStoreInfo.getPrivateKeyBytes(), pkiStoreInfo.getPrivateKeyPassword());
if(cipherutil.getErrorMsg()!= null)
throw new PKIException("decryptWithAsymmetric()", cipherutil.getErrorMsg());
byte[] decryptedData = cipherutil.decryptUpdate(encryptedData);
cipherutil.decryptFinal();
if(cipherutil.getErrorMsg()!= null)
throw new PKIException("decryptWithAsymmetric()", cipherutil.getErrorMsg());
return decryptedData;
}
/* (non-Javadoc)
* @see com.esum.framework.security.crypto.encrypt.DataEncrypt#encryptWithSymmetric(byte[], byte[], java.lang.String)
*/
public byte[] encryptWithSymmetric(byte[] data, byte[] symmetricKey, String encryptMethod)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
PKIException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
BadPaddingException {
CipherUtil cipherUtil = new CipherUtil();
cipherUtil.encryptInitBySeed(symmetricKey);
byte[] encryptData = cipherUtil.encryptUpdate(data);
cipherUtil.doFinal();
return encryptData;
}
/* (non-Javadoc)
* @see com.esum.framework.security.crypto.encrypt.DataEncrypt#decryptWithSymmetric(byte[], byte[], java.lang.String)
*/
public byte[] decryptWithSymmetric(byte[] encryptedData, byte[] symmetricKey, String encryptMethod)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException,
InvalidAlgorithmParameterException, IllegalStateException, IllegalBlockSizeException,
BadPaddingException, PKIException {
CipherUtil cutil = new CipherUtil();
cutil.decryptInit(symmetricKey);
byte[] decryptedData = cutil.decryptUpdate(encryptedData);
cutil.doFinal();
return decryptedData;
}
}
|
package com.sid.notepad;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Sid on 01-09-2016.
*/
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder>{
Context context;
Context c;
ArrayList<Information> data;
LayoutInflater inflator;
public MyCustomAdapter(Context context, ArrayList<Information> data) {
this.context = context;
this.data = data;
inflator = LayoutInflater.from(context);
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflator.inflate(R.layout.list_item_row , parent , false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final String temp_title = data.get(position).title;
final String temp_content = data.get(position).content;
final String temp_synced = data.get(position).isSynced;
holder.tv1.setText(temp_title);
holder.tv2.setText(temp_content);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(context , temp_title + " selected " + MainActivity.globalUsername, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context , AddNote.class);
intent.putExtra("by", "adapter");
intent.putExtra("title" , temp_title);
intent.putExtra("content" , temp_content);
intent.putExtra("pos" , position);
context.startActivity(intent);
((Activity)context).finish();
}
});
if (temp_synced.equals("false")){
holder.imageView.setVisibility(View.GONE);
}
}
@Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv1, tv2;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
tv1 = (TextView) itemView.findViewById(R.id.title_row);
tv2 = (TextView) itemView.findViewById(R.id.content_row);
imageView = (ImageView) itemView.findViewById(R.id.sync_ic);
}
}
}
|
package com.zzh.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* 电影Ribbon微服务集成Hystrix增加隔离策略控制线程数或请求数来达到熔断降级的作用。
* 传播安全上下文或使用,通过增加 HystrixCommand 的 commandProperties 属性,
* 来增加相关的配置来达到执行隔离策略,控制线程数或者控制并发请求数来达到熔断降级的作用。
* Hystrix 断路器实现失败快速响应,达到熔断效果;
* 注解 EnableCircuitBreaker 表明需要集成断路器模块;
* 如果你想把本地线程上下文传播到@HystrixCommand,默认的声明将不可用因为它是在一个线程池中被启动的。
* 你可以选择让Hystrix使用同一个线程,通过一些配置,或直接写在注解上,通过使用isolation strategy属性;
**/
@SpringBootApplication
@EnableCircuitBreaker
@EnableEurekaClient
public class MovieConsumerRibbonHystrixPropApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MovieConsumerRibbonHystrixPropApplication.class, args);
}
}
|
package IO;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Sivan on 5/16/2017.
*/
public class MyDecompressorInputStream extends InputStream {
private InputStream in;
public MyDecompressorInputStream(InputStream in) {
this.in = in;
}
@Override
public int read() throws IOException { //todo implement read
int val = in.read();
return val;
}
public int read(byte []b) throws IOException {
int row = read() & (0xff);
int col = read();
int startRow = read()& (0xff);
int startCol = read()& (0xff);
int goalRow = read()& (0xff);
int goalCol = read()& (0xff);
b[0] = ((Integer)row).byteValue();
b[1] = ((Integer)col).byteValue();
b[2] = ((Integer)startRow).byteValue();
b[3] = ((Integer)startCol).byteValue();
b[4] = ((Integer)goalRow).byteValue();
b[5] = ((Integer)goalCol).byteValue();
int n =0;
int i = 6;
while(i < b.length) {
int flag = 0;
n = read()& (0xff);
for(int j = 0; i < b.length && j < n; j++) {
b[i] = 0;
i++;
flag = 1;
}
n = read()& (0xff);
for(int j = 0; i < b.length && j < n; j++) {
b[i] = 1;
i++;
flag = 1;
}
if(flag == 0)
i++;
}
return -1;
}
}
|
package com.dinglan.moffice.model;
import java.util.Date;
import java.util.List;
import com.dinglan.ext.plugin.TableBind;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
@SuppressWarnings("serial")
@TableBind(tableName="wx_notice")
public class Notice extends Model<Notice> {
public static final Notice me = new Notice();
public Notice(){}
public Notice create(){
Notice model = new Notice();
long time =new Date().getTime();
model.set("createTime",time);
model.set("startTime",time);
model.set("endTime",time);
model.set("state",0);
return model;
}
public List<Notice> listOuting(int pageNumber, int pageSize){
Page<Notice> pages = paginate(pageNumber, pageSize, "select *", "from wx_notice where state=0");
return pages.getList();
}
}
|
package com.sportyShoes.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sportyShoes.model.User;
import com.sportyShoes.repository.UserRepository;
import com.sportyShoes.service.UserCrudService;
@Service
public class UserCrudServiceImpl implements UserCrudService{
@Autowired
private UserRepository userRepository;
@Override
public User createUser(User user) {
return userRepository.save(user);
}
@Override
public User updateUser(User user) {
return userRepository.save(user);
}
@Override
public User getUserById(int id) {
return userRepository.findById(id).get();
}
@Override
public void deleteUserById(int id) {
userRepository.deleteById(id);
}
@Override
public List<User> userList() {
return userRepository.findAll();
}
}
|
package com.project.coupons;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import com.project.dao.CompanyDBDAO;
import com.project.dao.DaoException;
import com.project.dao.ICompanyDAO;
public class TestCoupon {
public static void main(String[] args) throws FileNotFoundException, IOException, DaoException {
// TODO Auto-generated method stub
Company comp1 = new Company("comp4","12345","comp3@mail.com");
CompanyDBDAO company_dao1 = new CompanyDBDAO();
try {
company_dao1.createCompany(comp1);
} catch (DaoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Company> comp_list= null;
try {
comp_list = (ArrayList<Company>) company_dao1.getAllCompanies();
} catch (DaoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Company company : comp_list) {
try {
company_dao1.removeCompany(company);
} catch (DaoException e) {
// TODO Auto-generated catch block
throw new DaoException();
}
}
}
}
|
package com.example.android.navigationaldrawer2.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.example.android.navigationaldrawer2.R;
import com.example.android.navigationaldrawer2.adapters.FlowerAdapter;
import com.example.android.navigationaldrawer2.models.Flower;
import com.example.android.navigationaldrawer2.rest.client.RestClient;
import com.example.android.navigationaldrawer2.rest.interfaces.FlowerService;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* A simple {@link Fragment} subclass.
*/
public class HanselAndPetalsFragment extends Fragment {
private View view;
public HanselAndPetalsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_hansel_and_petals, container, false);
fetchFlowers();
return view;
}
private void fetchFlowers() {
FlowerService flowerService = RestClient.createService(FlowerService.class);
Call<List<Flower>> call = flowerService.getFlowers();
call.enqueue(new Callback<List<Flower>>() {
@Override
public void onResponse(Call<List<Flower>> call, Response<List<Flower>> response) {
if (response.isSuccessful()) {
ListView lvFlowers = (ListView) view.findViewById(R.id.lvFlowers);
List<Flower> flowers = response.body();
FlowerAdapter flowerAdapter = new FlowerAdapter(getActivity(), flowers);
lvFlowers.setAdapter(flowerAdapter);
} else {
System.out.println("Error response, no access to resource?");
}
}
@Override
public void onFailure(Call<List<Flower>> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
|
package co.company.test.config;
import org.springframework.stereotype.Component;
@Component
public class AppleSpeaker implements Speaker {
@Override
public void volumeup() {
System.out.println("AppleSpeaker");
}
}
|
package utils;
import org.apache.commons.codec.digest.DigestUtils;
/**
* @program: left-box
* @description:
* @author: Payton Wang
* @date: 2019-10-01 13:34
**/
public class SessionUtil {
public static String getSha256Hex(String secret) {
return DigestUtils.sha256Hex(secret);
}
}
|
package br.com.finpe.biblestudy;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import br.com.finpe.biblestudy.dto.Book;
import br.com.finpe.biblestudy.dto.BookList;
import br.com.finpe.biblestudy.service.BibleService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private BibleService bibleService = new BibleService("90799bb5b996fddc-01");
private TextView tvMainContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMainContent = findViewById(R.id.tv_main_content);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
final Context context = MainActivity.this;
switch (item.getItemId()) {
case R.id.action_search_book:
String searchingBook = getResources().getString(R.string.search_book_started);
Toast.makeText(context, searchingBook, Toast.LENGTH_SHORT).show();
bibleService.getBooks(new Callback<BookList>() {
@Override
public void onResponse(Call<BookList> call, Response<BookList> response) {
StringBuilder books = new StringBuilder();
for (Book book:response.body().getData()) {
books.append(book.getName() + "\n\n\n\n");
}
tvMainContent.setText(books.toString());
}
@Override
public void onFailure(Call<BookList> call, Throwable t) {
String searchingBookFailed = getResources().getString(R.string.search_book_failed);
Toast.makeText(context, searchingBookFailed, Toast.LENGTH_SHORT).show();
}
});
break;
}
return true;
}
}
|
package examples;
public class example6 {
static int metodo(int x, int y, int z) {
return (x+y+z);
}
static int metodo(int x, int z) {
return (x+z);
}
public static void main(String[] args) {
System.out.println("Resultado do metodo 1 = " + metodo(3, 5));
System.out.println("Resultado do metodo 2 = " + metodo(3, 40, 20));
}
}
|
package com.example.gameproject.kittyjump;
import com.example.gameproject.gl.DynamicGameObject;
public class Cat extends DynamicGameObject {
public static final int CAT_STATE_JUMP = 0;
public static final int CAT_STATE_FALL = 1;
public static final int CAT_STATE_HIT = 2;
public static final float CAT_JUMP_VELOCITY = 11;
public static final float CAT_MOVE_VELOCITY = 20;
public static final float CAT_WIDTH = 0.8f;
public static final float CAT_HEIGHT = 0.8f;
int state;
float stateTime;
public Cat(float x, float y) {
super(x, y, CAT_WIDTH, CAT_HEIGHT);
state = CAT_STATE_FALL;
stateTime = 0;
}
public void update(float deltaTime) {
velocity.add(World.gravity.x * deltaTime, World.gravity.y * deltaTime);
position.add(velocity.x * deltaTime, velocity.y * deltaTime);
bounds.lowerLeft.set(position).sub(bounds.width / 2, bounds.height / 2);
if (velocity.y > 0 && state != CAT_STATE_HIT) {
if (state != CAT_STATE_JUMP) {
state = CAT_STATE_JUMP;
stateTime = 0;
}
}
if (velocity.y < 0 && state != CAT_STATE_HIT) {
if (state != CAT_STATE_FALL) {
state = CAT_STATE_FALL;
stateTime = 0;
}
}
if (position.x < 0)
position.x = World.WORLD_WIDTH;
if (position.x > World.WORLD_WIDTH)
position.x = 0;
stateTime += deltaTime;
}
public void hitDog() {
velocity.set(0, 0);
state = CAT_STATE_HIT;
stateTime = 0;
}
public void hitPlatform() {
velocity.y = CAT_JUMP_VELOCITY;
state = CAT_STATE_JUMP;
stateTime = 0;
}
public void hitSpring() {
velocity.y = CAT_JUMP_VELOCITY * 1.5f;
state = CAT_STATE_JUMP;
stateTime = 0;
}
}
|
package com.example.examplemod.init;
import com.example.examplemod.blocks.BlockCheese;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.common.registry.GameRegistry;
public class ModBlocks {
public static Block cheese;
public static void init() {
cheese = new BlockCheese();
}
public static void register() {
registerBlock(cheese);
}
private static void registerBlock(Block block) {
GameRegistry.register(block);
GameRegistry.register(new ItemBlock(block), block.getRegistryName());
}
public static void registerRenders() {
registerRender(cheese);
}
private static void registerRender(Block block) {
Minecraft.getMinecraft()
.getRenderItem()
.getItemModelMesher()
.register(Item.getItemFromBlock(block), 0, new ModelResourceLocation(block.getRegistryName(), "inventory"));
}
}
|
package com.logicbig.example.primary;
public class DaoB implements Dao {
@Override
public void saveOrder(String orderId) {
System.out.println("DaoB Order saved " + orderId);
}
}
|
package br.com.candleanalyser.genetics;
public enum Gene {
BUY_ADVISOR(0, 0, true),
SELL_ADVISOR(0, 0, true),
RSI_ADVISOR_BUY_WEIGHT(0, 0),
RSI_ADVISOR_BUY_NR_CANDLES(14, 14),
RSI_ADVISOR_SELL_WEIGHT(0, 0),
RSI_ADVISOR_SELL_NR_CANDLES(14, 14),
STOCH_RSI_ADVISOR_BUY_WEIGHT(1, 1),
STOCH_RSI_ADVISOR_BUY_NR_CANDLES(14, 14),
STOCH_RSI_ADVISOR_BUY_DIVERGENCE_WEIGHT(0.5F, 0.5F),
STOCH_RSI_ADVISOR_BUY_RSI_VALUE_WEIGHT(0.5F, 0.5F),
STOCH_RSI_ADVISOR_SELL_WEIGHT(1, 1),
STOCH_RSI_ADVISOR_SELL_NR_CANDLES(14, 14),
STOCH_RSI_ADVISOR_SELL_DIVERGENCE_WEIGHT(0.5F, 0.5F),
STOCH_RSI_ADVISOR_SELL_RSI_VALUE_WEIGHT(0.5F, 0.5F),
CHANNEL_ADVISOR_BUY_WEIGHT(0, 0),
CHANNEL_ADVISOR_BUY_NR_CANDLES(4, 360),
CHANNEL_ADVISOR_BUY_CONTAINED_CANDLES_RATIO(0, 1),
CHANNEL_ADVISOR_SELL_WEIGHT(0, 0),
CHANNEL_ADVISOR_SELL_NR_CANDLES(4, 360),
CHANNEL_ADVISOR_SELL_CONTAINED_CANDLES_RATIO(0, 1),
CANDLE_INDICATOR_BUY_WEIGHT(0, 0),
CANDLE_INDICATOR_SELL_WEIGHT(0, 0),
MACD_ADVISOR_SELL_WEIGHT(0, 0),
MACD_ADVISOR_SELL_MACD_EMA(9, 9),
MACD_ADVISOR_SELL_FASTER_EMA(12, 12),
MACD_ADVISOR_SELL_SLOWER_EMA(26, 26),
MACD_ADVISOR_BUY_WEIGHT(0, 0),
MACD_ADVISOR_BUY_MACD_EMA(9, 9),
MACD_ADVISOR_BUY_FASTER_EMA(12, 12),
MACD_ADVISOR_BUY_SLOWER_EMA(26, 26);
private float minValue;
private float maxValue;
private String name;
private boolean isInteger;
private Gene(float minValue, float maxValue) {
this(minValue, maxValue, false);
}
private Gene(float minValue, float maxValue, boolean isInteger) {
this.maxValue = maxValue;
this.minValue = minValue;
this.isInteger = isInteger;
}
public float getValue(float raw) {
if(!isInteger) {
return minValue + raw*(maxValue-minValue);
} else {
return getIntegerValue(raw);
}
}
private int getIntegerValue(float raw) {
return (int)(minValue + raw*(maxValue-minValue+0.99F));
}
public float getMinValue() {
return minValue;
}
public float getMaxValue() {
return maxValue;
}
public String getName() {
return name;
}
}
|
package com.capitalone.socialApiFb.controllers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
@RestController
@RequestMapping("/socialapi/twitter/rest")
public class TwitterRestController {
private static final Logger log = LoggerFactory.getLogger(FacebookApiController.class);
ObjectMapper mapper= new ObjectMapper();
/*@Autowired
TwitterService tweetservice;*/
@Autowired
private TwitterTemplateCreator twitterTemplateCreator;
@RequestMapping(value = "/getTweetsBasedonhashtag",method = RequestMethod.GET)
public ResponseEntity<JsonNode> getTweetsBasedonhashtag(@RequestParam String hashtag)
{ log.info("inside getStatus method");
ObjectNode result = mapper.createObjectNode();
try {
//JsonNode data = mapper.convertValue(tweetservice.getTweets(hashtag), JsonNode.class);
JsonNode data = mapper.convertValue(twitterTemplateCreator.getTwitterTemplate().searchOperations().search(hashtag,20).getTweets(), JsonNode.class);;
result.put("data", data);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return new ResponseEntity<JsonNode>(result,HttpStatus.OK);
}
}
|
package com.sirma.itt.javacourse.intro.task4.arraySorting;
import java.util.List;
import com.sirma.itt.javacourse.InputUtils;
/**
* Class for running the QuickSort class.
*
* @author simeon
*/
public class RunQuickSort {
/**
* Main method for QuickSortImpl.
*
* @param args
* for main method.
*/
public static void main(String[] args) {
List<Integer> arr = InputUtils.inputListOfIntegers();
InputUtils.printConsoleMessage("Array before sorting " + arr);
InputUtils.printConsoleMessage("Array after sorting " + QuickSortImpl.quickSortArray(arr));
}
}
|
package no.hartvigor.s306386mappe1;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
import java.util.MissingResourceException;
public class GameActivity extends AppCompatActivity {
private ArrayList<GameItem> gameItems = new ArrayList<>();
/**
* array_position -1 fordi den ikke er tatt i bruk altså blir 0 ved bruk
*/
private int array_position = -1;
/**
* variabler for statestikk
*/
private int score_number;
private int sum_total_games;
private int score_total_history;
private int sum_total_history;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
/*
starte metode for laging av spm. if spill er igang er ikke saveIS null
*/
//Hvis ikke det er lagret spill i InstanceState lag nytt spill
if(savedInstanceState == null) {
createRandomMathQuestions();
}
keyboard_input_listener();
}
/**
* Ved endring for eks horizontalt (config) lagres aktivit i objektet i en bundle(objekt)
* @param outState
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
GameHolder Holder = new GameHolder(gameItems);
outState.putSerializable("holder", Holder);
String currentAnswer = ((TextView)findViewById(R.id.game_answer_field)).getText().toString();
outState.putString("currentAnswer", currentAnswer);
outState.putInt("position", array_position);
outState.putInt("score", score_number);
String language = PreferenceManager.getDefaultSharedPreferences(this).getString("languages", "default");
Configuration config = getResources().getConfiguration();
if( language.equals("default") ) language = Locale.getDefault().getLanguage();
config.locale = new Locale(language);
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
super.onSaveInstanceState(outState);
}
/**
* her hentes lagret fra onSaveIS og restores
* @param savedInstanceState
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState.containsKey("holder")) {
GameHolder restoreHolder = (GameHolder) savedInstanceState.getSerializable("holder");
if (restoreHolder != null) {
gameItems = restoreHolder.getItems();
}
}
if(savedInstanceState.containsKey("currentAnswer")){
((TextView)findViewById(R.id.game_answer_field)).setText(savedInstanceState.getString("currentAnswer"));
}
if(savedInstanceState.containsKey("position")){
array_position = savedInstanceState.getInt("position");
}
if(savedInstanceState.containsKey("score")){
score_number = savedInstanceState.getInt("score");
}
restoreQuestion();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_game);
}
/**
* laging av spm
*/
public void createRandomMathQuestions() {
//??
String[] ql = getResources().getStringArray(R.array.math_questions);
String[] qa = getResources().getStringArray(R.array.math_answers);
//henting av valgt antall spm
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String desiredPreference = sharedPreferences.getString("number_of_questions", "5");
//Gjør string til int
int max = Integer.valueOf(desiredPreference);
ArrayList<GameItem> temp = new ArrayList<GameItem>();
if(ql.length == qa.length){
for(int i = 0; i < qa.length; i++){
temp.add(new GameItem(i, ql[i], qa[i]));
}
}
else{
throw new MissingResourceException("Length in Array not the same", "GameActivity", null);
}
Log.e("Objekt listen", "Objetktet:"+ Arrays.toString(new ArrayList[]{gameItems}));
Collections.shuffle(temp);
for(GameItem item : temp){
gameItems.add(item);
if(gameItems.size() == max)
break;
}
nextQuestion();
}
/**
* metode setter score i view
*/
public void setScoreView(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
TextView setScoreView = findViewById(R.id.game_score_view);
setScoreView.setText(score_number + "/" + sharedPreferences.getString("number_of_questions", "5"));
}
/**
* calles ved gjennomoppretting av aktivitet(for eks horizontalt endring)
*/
public void restoreQuestion() {
GameItem restore = gameItems.get(array_position);
setScoreView();
((TextView)findViewById(R.id.game_math_question)).setText(restore.getQuestion());
}
public void nextQuestion(){
//legge til i variabel for totalt spillte spill
sum_total_games++;
setScoreView();
array_position++;
((TextView)findViewById(R.id.game_math_question)).setText(gameItems.get(array_position).getQuestion());
((TextView)findViewById(R.id.game_answer_field)).setText("");
}
private void onCheckAnswer (){
gameItems.get(array_position).setAnswered(true);
TextView Attempt = findViewById(R.id.game_answer_field);
String current = Attempt.getText().toString();
if(gameItems.get(array_position).getAnswer().equals(current)){
score_number++;
gameItems.get(array_position).setCorrect(true);
toastHelper(getString(R.string.string_correct));
}
else{
toastHelper(getString(R.string.string_wrong));
}
if(gameItems.size()-1 == array_position && gameItems.get(array_position).isAnswered()){
gameCompleted();
}
else{
nextQuestion();
}
}
//Hjelper for å plassere toast melding riktig posisjon på skjermen
private void toastHelper(String text_for_toast){
Toast correct_toast = Toast.makeText(this, text_for_toast, Toast.LENGTH_SHORT);
View toastStyle = correct_toast.getView();
if(text_for_toast.equals(getString(R.string.string_correct))){
toastStyle.setBackgroundResource(R.drawable.toast_styling);
}
else{
toastStyle.setBackgroundResource(R.drawable.toast_styling_alt);
}
int orientation = getResources().getConfiguration().orientation;
if(orientation == Configuration.ORIENTATION_LANDSCAPE){
correct_toast.setGravity(Gravity.CENTER,-200,10);
}
else{
correct_toast.setGravity(Gravity.CENTER,0,-80);
}
correct_toast.show();
}
//ved avsluttning
private void statisticHelper(){
/**
* ved avslutting av spill lagres score i shared preferences
*/
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
score_total_history = sharedPreferences.getInt("score_total", 0);
sum_total_history = sharedPreferences.getInt("sum_total_games", 0);
score_total_history += score_number;
sum_total_history += sum_total_games;
SharedPreferences.Editor editor = sharedPreferences.edit();
//siste spill score
editor.putInt("score", score_number);
editor.apply();
//totalt riktig score
editor.putInt("score_total", score_total_history);
editor.apply();
//totalt antall spill
editor.putInt("sum_total_games", sum_total_history);
editor.apply();
}
private void gameCompleted(){
setScoreView();
AlertDialog.Builder adb = new AlertDialog.Builder(this);
final View customLayout = getLayoutInflater().inflate(R.layout.game_activity_dialog_alert, null);
adb.setView(customLayout);
adb.setPositiveButton(getResources().getString(R.string.string_finished), (dialogInterface, i) -> {
statisticHelper();
finish();
});
adb.setNegativeButton(getResources().getString(R.string.string_new_game), (dialogInterface, i) -> {
sum_total_games++;
gameItems.clear();
array_position = -1;
score_number = 0;
createRandomMathQuestions();
});
adb.create().show();
}
/**
* listener som aktiverer metode fra trykk på keyboard
*/
private void keyboard_input_listener(){
findViewById(R.id.button_0).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_zero)));
findViewById(R.id.button_1).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_one)));
findViewById(R.id.button_2).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_two)));
findViewById(R.id.button_3).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_three)));
findViewById(R.id.button_4).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_four)));
findViewById(R.id.button_5).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_five)));
findViewById(R.id.button_6).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_six)));
findViewById(R.id.button_7).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_seven)));
findViewById(R.id.button_8).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_eight)));
findViewById(R.id.button_9).setOnClickListener(view -> keyboard_set_input(getString(R.string.string_number_nine)));
findViewById(R.id.button_check_answer).setOnClickListener(view -> onCheckAnswer());
findViewById(R.id.button_delete).setOnClickListener(view -> deleteInput());
}
/**
* legger inn innput fra keybord og lager string av inputten
* @param v
*/
private void keyboard_set_input(String v){
TextView Answer = findViewById(R.id.game_answer_field);
Answer.append(v);
}
/**
* fjerner siste bokstav fra input fra keyboard
*/
private void deleteInput(){
TextView Answer = findViewById(R.id.game_answer_field);
if (Answer != null) {
String v = Answer.getText().toString();
if (v.length() > 0) {
v = v.substring(0, v.length() -1);
Answer.setText(v);
}
}
}
@Override
public void onBackPressed() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle(R.string.string_leaving_game);
adb.setPositiveButton(getResources().getString(R.string.string_exit), ((dialogInterface, i) -> {
finish();
}));
adb.setNegativeButton(getResources().getString(R.string.string_cancell), ((dialogInterface, i) -> {
dialogInterface.dismiss();
}));
adb.create().show();
}
}
|
package com.esum.comp.ws.table;
import com.esum.common.record.InterfaceInfoRecord;
import com.esum.framework.common.sql.Record;
import com.esum.framework.core.component.ComponentException;
/**
* WS_INFO 테이블의 레코드와 매칭되는 클래스
*
* Copyright(c) eSum Technologies, Inc. All rights reserved.
*/
public class WsInfoRecord extends InterfaceInfoRecord {
private boolean useInbound;
private String inboundServiceName;
private String inboundServiceClass;
private String inboundServiceImpl;
private boolean inboundClientAuth;
// private String inboundAuthInfoId;
private boolean useInboundResponse;
private String inboundResponseRule;
private boolean useInboundWsAddressing;
private boolean useInboundWsSecurity;
private WsSecurityServerInfo inboundWsSecurityInfo;
private boolean useOutbound;
private String outboundWsdlUrl;
private String outboundServiceUrl;
private String outboundServiceOpName;
private String outboundServiceOpParamsCreator;
private boolean outboundClientAuth;
private String outboundAuthInfoId;
private boolean useOutboundWsSecurity;
private WsSecurityServerInfo outboundWsSecurityInfo;
public WsInfoRecord(Record record) throws ComponentException {
super(record);
}
public WsInfoRecord(String[] ids, Record record) throws ComponentException {
super(ids, record);
}
protected void init(Record record) throws ComponentException {
super.setInterfaceId(record.getString("INTERFACE_ID").trim());
super.setNodeList(toArrayList(record.getString("NODE_ID"), ","));
super.setParsingRule(record.getString("PARSING_RULE").trim());
this.useInbound = record.getString("USE_INBOUND", "N").trim().equals("Y");
if(this.useInbound) {
this.inboundServiceName = record.getString("INBOUND_SERVICE_NAME");
this.inboundServiceClass = record.getString("INBOUND_SERVICE_CLASS");
this.inboundServiceImpl = record.getString("INBOUND_SERVICE_IMPL");
this.inboundClientAuth = record.getString("INBOUND_HTTP_AUTH_FLAG").trim().equals("Y");
// if(this.inboundClientAuth)
// this.inboundAuthInfoId = record.getString("INBOUND_HTTP_AUTH_ID");
this.useInboundResponse = record.getString("INBOUND_RESPONSE_FLAG").trim().equals("Y");
this.inboundResponseRule = record.getString("INBOUND_RESPONSE_RULE");
this.useInboundWsAddressing = record.getString("INBOUND_WS_ADDRESSING", "N").equals("Y");
this.useInboundWsSecurity = record.getString("INBOUND_WS_SECURITY", "N").equals("Y");
if(this.useInboundWsSecurity) {
this.inboundWsSecurityInfo = new WsSecurityServerInfo();
this.inboundWsSecurityInfo.initInbound(record);
}
}
this.useOutbound = record.getString("USE_OUTBOUND", "N").trim().equals("Y");
if(useOutbound) {
this.outboundWsdlUrl = record.getString("OUTBOUND_WSDL_URL");
this.outboundServiceUrl = record.getString("OUTBOUND_SERVICE_URL");
this.outboundServiceOpName = record.getString("OUTBOUND_SERVICE_OPNAME");
this.outboundServiceOpParamsCreator = record.getString("OUTBOUND_SERVICE_OPPARAM");
this.outboundClientAuth = record.getString("OUTBOUND_HTTP_AUTH_FLAG").trim().equals("Y");
this.outboundAuthInfoId = record.getString("OUTBOUND_HTTP_AUTH_ID");
this.useOutboundWsSecurity = record.getString("OUTBOUND_WS_SECURITY", "N").equals("Y");
if(this.useOutboundWsSecurity) {
this.outboundWsSecurityInfo = new WsSecurityServerInfo();
this.outboundWsSecurityInfo.initOutbound(record);
}
}
}
public boolean isUseInbound() {
return useInbound;
}
public void setUseInbound(boolean useInbound) {
this.useInbound = useInbound;
}
public String getInboundServiceName() {
return inboundServiceName;
}
public void setInboundServiceName(String inboundServiceName) {
this.inboundServiceName = inboundServiceName;
}
public String getInboundServiceClass() {
return inboundServiceClass;
}
public void setInboundServiceClass(String inboundServiceClass) {
this.inboundServiceClass = inboundServiceClass;
}
public String getInboundServiceImpl() {
return inboundServiceImpl;
}
public void setInboundServiceImpl(String inboundServiceImpl) {
this.inboundServiceImpl = inboundServiceImpl;
}
public boolean isInboundClientAuth() {
return inboundClientAuth;
}
public void setInboundClientAuth(boolean inboundClientAuth) {
this.inboundClientAuth = inboundClientAuth;
}
//
// public String getInboundAuthInfoId() {
// return inboundAuthInfoId;
// }
//
// public void setInboundAuthInfoId(String inboundAuthInfoId) {
// this.inboundAuthInfoId = inboundAuthInfoId;
// }
public boolean isUseInboundResponse() {
return useInboundResponse;
}
public void setUseInboundResponse(boolean useInboundResponse) {
this.useInboundResponse = useInboundResponse;
}
public String getInboundResponseRule() {
return inboundResponseRule;
}
public void setInboundResponseRule(String inboundResponseRule) {
this.inboundResponseRule = inboundResponseRule;
}
public boolean isUseInboundWsAddressing() {
return useInboundWsAddressing;
}
public void setUseInboundWsAddressing(boolean useInboundWsAddressing) {
this.useInboundWsAddressing = useInboundWsAddressing;
}
public boolean isUseInboundWsSecurity() {
return useInboundWsSecurity;
}
public void setUseInboundWsSecurity(boolean useInboundWsSecurity) {
this.useInboundWsSecurity = useInboundWsSecurity;
}
public boolean isUseOutbound() {
return useOutbound;
}
public void setUseOutbound(boolean useOutbound) {
this.useOutbound = useOutbound;
}
public String getOutboundWsdlUrl() {
return outboundWsdlUrl;
}
public void setOutboundWsdlUrl(String outboundWsdlUrl) {
this.outboundWsdlUrl = outboundWsdlUrl;
}
public String getOutboundServiceUrl() {
return outboundServiceUrl;
}
public void setOutboundServiceUrl(String outboundServiceUrl) {
this.outboundServiceUrl = outboundServiceUrl;
}
public String getOutboundServiceOpName() {
return outboundServiceOpName;
}
public void setOutboundServiceOpName(String outboundServiceOpName) {
this.outboundServiceOpName = outboundServiceOpName;
}
public String getOutboundServiceOpParamsCreator() {
return outboundServiceOpParamsCreator;
}
public void setOutboundServiceOpParamsCreator(
String outboundServiceOpParamsCreator) {
this.outboundServiceOpParamsCreator = outboundServiceOpParamsCreator;
}
public boolean isOutboundClientAuth() {
return outboundClientAuth;
}
public void setOutboundClientAuth(boolean outboundClientAuth) {
this.outboundClientAuth = outboundClientAuth;
}
public String getOutboundAuthInfoId() {
return outboundAuthInfoId;
}
public void setOutboundAuthInfoId(String outboundAuthInfoId) {
this.outboundAuthInfoId = outboundAuthInfoId;
}
public WsSecurityServerInfo getInboundWsSecurityInfo() {
return inboundWsSecurityInfo;
}
public void setInboundWsSecurityInfo(WsSecurityServerInfo inboundWsSecurityInfo) {
this.inboundWsSecurityInfo = inboundWsSecurityInfo;
}
public boolean isUseOutboundWsSecurity() {
return useOutboundWsSecurity;
}
public void setUseOutboundWsSecurity(boolean useOutboundWsSecurity) {
this.useOutboundWsSecurity = useOutboundWsSecurity;
}
public WsSecurityServerInfo getOutboundWsSecurityInfo() {
return outboundWsSecurityInfo;
}
public void setOutboundWsSecurityInfo(WsSecurityServerInfo outboundWsSecurityInfo) {
this.outboundWsSecurityInfo = outboundWsSecurityInfo;
}
}
|
package com.lenovohit.hwe.treat.service.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.lenovohit.hwe.treat.dao.HisRestDao;
import com.lenovohit.hwe.treat.dao.HisRestEntityResponse;
import com.lenovohit.hwe.treat.dao.HisRestListResponse;
import com.lenovohit.hwe.treat.dao.HisRestRequest;
import com.lenovohit.hwe.treat.dto.GenericRestDto;
import com.lenovohit.hwe.treat.model.ConsultDept;
import com.lenovohit.hwe.treat.model.Department;
import com.lenovohit.hwe.treat.service.HisDepartmentService;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
import com.lenovohit.hwe.treat.transfer.RestListResponse;
/**
*
* @author xiaweiyi
*/
public class HisDepartmentRestServiceImpl implements HisDepartmentService {
GenericRestDto<Department> dto;
GenericRestDto<ConsultDept> consultDeptDto;
private HisRestDao hisRestDao;
public HisDepartmentRestServiceImpl(final GenericRestDto<Department> dto, final GenericRestDto<ConsultDept> consultDeptDto) {
super();
this.dto = dto;
this.consultDeptDto = consultDeptDto;
}
public HisRestDao getHisRestDao() {
return hisRestDao;
}
public void setHisRestDao(HisRestDao hisRestDao) {
this.hisRestDao = hisRestDao;
}
@Override
public ConsultDept forConsultDept(Department dept) {
RestEntityResponse<ConsultDept> restResponse = consultDeptDto.getForEntity("hcp/test/department/select", dept);
if(null != restResponse && restResponse.isSuccess()){
return restResponse.getEntity();
} else {
return null;
}
}
@Override
public RestEntityResponse<Department> getInfo(Department dept, Map<String, ?> variables) {
// TODO Auto-generated method stub
return null;
}
@Override
public RestListResponse<Department> findList(Department dept, Map<String, ?> variables) {
HisRestListResponse response = hisRestDao.postForList("APPOINT001", HisRestRequest.SEND_TYPE_LOCATION, variables);
return parseList(response);
}
private Department parseEntity(Map<String, Object> entity) {
if (entity == null) {
return null;
}
Department _entity = new Department();
_entity.setNo(entity.get("DEPT_CODE").toString());
_entity.setName(entity.get("DEPT_NAME").toString());
_entity.setDescription(entity.get("DEPT_INTRODUCE").toString());
_entity.setPinyin(entity.get("PINYIN").toString());
return _entity;
}
private RestEntityResponse<Department> parseEntity(HisRestEntityResponse entityResponse) {
if (entityResponse == null) {
return null;
}
RestEntityResponse<Department> response = new RestEntityResponse<Department>();
response.setSuccess(entityResponse.getResultcode());
response.setMsg(entityResponse.getResult());
if (entityResponse.isSuccess()) {
Department entity = parseEntity(entityResponse.getEntity());
response.setEntity(entity);
}
return response;
}
private RestListResponse<Department> parseList(HisRestListResponse listResponse) {
if (listResponse == null) {
return null;
}
RestListResponse<Department> response = new RestListResponse<Department>();
response.setSuccess(listResponse.getResultcode());
response.setMsg(listResponse.getResult());
if (listResponse.isSuccess()) {
List<Department> list = new ArrayList<Department>();
for(Map<String, Object> _entity : listResponse.getList()){
list.add(parseEntity(_entity));
}
response.setList(list);
}
return response;
}
}
|
class car {
Interger id;
String license;
String driver;
Interger passenger;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.persistence.germplasm;
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.inbio.ara.dto.inventory.SelectionListEntity;
import org.inbio.ara.persistence.SelectionListGenericEntity;
/**
*
* @author dasolano
*/
@Entity
@Table(name = "crop_system")
public class CropSystem extends SelectionListGenericEntity{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO, generator="crop_system")
@SequenceGenerator(name="crop_system", sequenceName="crop_system_seq")
@Basic(optional = false)
@Column(name = "crop_system_id")
private Long cropSystemId;
public CropSystem() {
}
public CropSystem(Long cropSystemId) {
this.cropSystemId = cropSystemId;
}
public CropSystem(Long cropSystemId, String name, String createdBy, Calendar creationDate, String lastModificationBy, Calendar lastModificationDate) {
this.cropSystemId = cropSystemId;
this.setName(name);
this.setCreatedBy(createdBy);
this.setCreationDate(creationDate);
this.setLastModificationBy(lastModificationBy);
this.setLastModificationDate(lastModificationDate);
}
public Long getCropSystemId() {
return cropSystemId;
}
public void setCropSystemId(Long cropSystemId) {
this.cropSystemId = cropSystemId;
}
@Override
public int hashCode() {
int hash = 0;
hash += (cropSystemId != null ? cropSystemId.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 CropSystem)) {
return false;
}
CropSystem other = (CropSystem) object;
if ((this.cropSystemId == null && other.cropSystemId != null) || (this.cropSystemId != null && !this.cropSystemId.equals(other.cropSystemId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.inbio.ara.persistence.germoplasma.CropSystem[cropSystemId=" + cropSystemId + "]";
}
@Override
public Long getId() {
return cropSystemId;
}
@Override
public void setId(Long id) {
this.cropSystemId = id;
}
@Override
public SelectionListEntity getSelectionListEntity() {
return SelectionListEntity.CROP_SYSTEM;
}
}
|
package com.raymon.api.demo.synchronizeddemo;
/**
* Author: raymon
* Date: 2019/4/7
* Description:可重入粒度测试,调用父类的方法,即调用其他类中的方法
*/
public class SynchronizedSuperClass12 {
public synchronized void doSomthing(){
System.out.println("This is super class");
}
}
class TestClass extends SynchronizedSuperClass12{
public synchronized void doSomthing(){
System.out.println("This is son class");
super.doSomthing();
}
public static void main(String[] args) {
TestClass testClass = new TestClass();
testClass.doSomthing();
}
}
|
package com.example.chat.dto.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ApiResponse {
private Boolean success;
private String message;
}
|
package com.xi.main;
import com.xi.ListDemo.MergeList;
import java.text.DecimalFormat;
/**
* Created by Administrator on 2015/12/26.
*/
public class Execute {
public static void main(String[] args) {
// MergeList ml=new MergeList();
// ml.queryList();
// Integer vacantRoom=671;
// Integer allRoom=1472;
// Double vacancy_rate = Double.valueOf((double) vacantRoom / allRoom);
// DecimalFormat df = new DecimalFormat("#.0000");
// Double d = Double.valueOf(df.format(vacancy_rate));
// System.out.println(d);
// for(int i=1;i<101;i++){
// System.out.println(i);
// }
/*int i=1;
while(i<101){
System.out.println(i);
i++;
}*/
// int i=0;
// do{
//// i=1;
// i++;
// System.out.println(i);
// }while(i<100);
/*Integer score=-19;
if(score>=0&&score<60){
System.out.println("不及格");
}
if(score>=60&&score<80){
System.out.println("合格");
}
if(score>=80&&score<90){
System.out.println("良");
}
if(score>=90&&score<=100){
System.out.println("优秀");
}
else if(score<0||score>100){
System.out.println("非法成绩");
}*/
//分级打印的例子 0-59不及格 60-79合格 80-89 良 90 -100优秀 否则 非法成绩
/*Integer score=90;
char sc='E';//用A表示优秀 B良 C合格 D不及格
if(score>=0&&score<60){
sc='D';
}
if(score>=60&&score<80){
sc='C';
}
if(score>=80&&score<90){
sc='B';
}
if(score>=90&&score<=100){
sc='A';
}
else if(score<0||score>100){
sc='E';
}
switch (sc){
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良");
break;
case 'C':
System.out.println("合格");
break;
case 'D':
System.out.println("不及格");
break;
default:
System.out.println("非法成绩");
break;
}*/
/*int result = 991;
if (result >= 0 && result <= 59) {
System.out.println("不合格");
} else if (result >= 60 && result <= 79) {
System.out.println("合格");
} else if (result >= 80 && result <= 89) {
System.out.println("良好");
} else if (result >= 90 && result <= 100) {
System.out.println("优秀");
} else {
System.out.println("非法成绩");
}*/
String str="wbdr-bmxx-201707120000";
for(int i=0;i<2685;i++){
if(i<10&&i>=0){
System.out.println("wbdr-bmxx-20170712200"+i);
}else if(i<100&&i>=10){
System.out.println("wbdr-bmxx-2017071220"+i);
}else if(i<684&&i>=100){
System.out.println("wbdr-bmxx-201707122"+i);
}
}
}
}
|
package com.detroitlabs.comicview.controller;
import com.detroitlabs.comicview.model.*;
import com.detroitlabs.comicview.model.Character;
import com.detroitlabs.comicview.service.ComicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Controller
public class ComicController {
@Autowired
ComicService comicService;
@Autowired
Results results;
@Autowired
IssueResults issueResults;
@Autowired
CharacterWrapper characterWrapper;
@RequestMapping("/")
public String displayAllCharacters(ModelMap modelMap) {
ComicWrapper cw = comicService.fetchAllData();
List<Character> allCharacters = cw.getResults();
Collections.shuffle(allCharacters);
modelMap.put("allCharacters", allCharacters);
List<Character> carousel = new ArrayList<>();
for (int i = 0; i <= 2; i++) {
carousel.add(allCharacters.get(i));
}
modelMap.put("carousel", carousel);
return "index";
}
@RequestMapping("/allissues")
public String displayAllIssues(ModelMap modelMap){
IssuesWrapper issuesWrapper = comicService.DisplayAllIssueData();
List<IssueResults> allIssues = issuesWrapper.getResults();
modelMap.put("allIssues", allIssues);
return "allissues";
}
@RequestMapping("search")
public String searchByCharacterName(@RequestParam("q") String searchValue, ModelMap modelMap) {
comicService.setSearchName(searchValue);
ComicWrapper cw = comicService.fetchbyName();
List<Character> allCharacters = cw.getResults();
modelMap.put("allCharacters", allCharacters);
List<Character> carousel = new ArrayList<>();
for (int i = 0; i <= 2; i++) {
if (allCharacters.size() == 0) {
Character noResultsCharacter = new Character();
Images noResultsImage = new Images();
noResultsCharacter.setName("No Results");
noResultsCharacter.setDate_added("No Results");
noResultsImage.setSmall_url("/images/blank.png");
noResultsCharacter.setImages(noResultsImage);
carousel.add(noResultsCharacter);
} else if (allCharacters.size() <= 2) {
carousel.add(allCharacters.get(0));
} else {
carousel.add(allCharacters.get(i));
}
}
modelMap.put("carousel", carousel);
return "index";
}
@RequestMapping("/character/{characterId}")
public String searchByCharacter(@PathVariable String characterId, ModelMap modelMap) {
comicService.setSearchCharacter(characterId);
CharacterWrapper characterWrapper = comicService.fetchSingleCharacterById();
Character searchCharacter = characterWrapper.getResults();
modelMap.put("searchCharacter", searchCharacter);
IssuesWrapper issuesWrapper = comicService.DisplayAllIssueData();
List<IssueResults> allIssues = issuesWrapper.getResults();
modelMap.put("allIssues", allIssues);
return "single";
}
@RequestMapping("/issues")
@ResponseBody
public String displayIssueById(){
IssueWrapper issueWrapper = comicService.DisplayByIssue();
IssueResults results = issueWrapper.getResults();
return results.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.