text stringlengths 10 2.72M |
|---|
package com.kusu.ticksee.Adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.kusu.ticksee.Models.BrifcaseItem;
import com.kusu.ticksee.R;
import java.util.List;
public class BriefcaseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_HEADER = 0;
private static final int VIEW_TYPE_ITEM = 1;
private final View mHeaderView;
List<BrifcaseItem> list;
Context context;
public BriefcaseAdapter(Context context, List<BrifcaseItem> list, View headerView) {
this.list = list;
this.context = context;
mHeaderView = headerView;
}
public void updateList(List<BrifcaseItem> list){
this.list = list;
this.notifyDataSetChanged();
}
@Override
public int getItemCount() {
if (mHeaderView == null) {
return list.size();
} else {
return list.size() + 1;
}
}
@Override
public int getItemViewType(int position) {
return (position == 0)&&(mHeaderView != null) ? VIEW_TYPE_HEADER : VIEW_TYPE_ITEM;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_HEADER) {
return new HeaderViewHolder(mHeaderView);
} else {
return new ViewHolderBriefcase(LayoutInflater.from(context).inflate(R.layout.i_briefcase, parent, false));
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
switch (getItemViewType(position)){
case VIEW_TYPE_HEADER:
break;
case VIEW_TYPE_ITEM:
BrifcaseItem item = getItem(position);
ViewHolderBriefcase hold = (ViewHolderBriefcase) viewHolder;
hold.name.setText(item.getCurrency());
hold.free.setText(item.getFreeAmount()+"");
hold.amount.setText(item.getAmount()+"");
hold.lock.setText(item.getLockedAmount()+"");
}
}
private BrifcaseItem getItem(int position) {
if (mHeaderView == null)
return list.get(position);
else
return list.get(position-1);
}
public static class HeaderViewHolder extends RecyclerView.ViewHolder {
public HeaderViewHolder(View view) {
super(view);
}
}
public class ViewHolderBriefcase extends RecyclerView.ViewHolder {
TextView amount;
TextView lock;
TextView free;
TextView name;
public ViewHolderBriefcase(View itemView) {
super(itemView);
amount = (TextView) itemView.findViewById(R.id.textAmount);
lock = (TextView) itemView.findViewById(R.id.textLock);
free = (TextView) itemView.findViewById(R.id.textFree);
name = (TextView) itemView.findViewById(R.id.textName);
}
}
}
|
package com.hr.bulletin.controller;
import org.springframework.stereotype.Controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.sql.rowset.serial.SerialBlob;
import javax.sql.rowset.serial.SerialException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.hr.bulletin.model.Bulletin;
import com.hr.bulletin.service.BulletinService;
@Controller
public class BulletinUpdController implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(BulletinUpdController.class);
@Autowired
BulletinService bulletinService;
@Autowired
ServletContext ctx;
// 修改活動貼文頁 //h
@GetMapping("/bulletinEditEventPage") //h
public String findByIdEvent(@RequestParam("postno") int postno, Model model) {
Bulletin bulletin = bulletinService.findById(postno);
model.addAttribute("bulletin", bulletin);
return "/bulletin/eventEdit";
}
// 修改公告貼文頁 //h
@GetMapping("/bulletinEdiAnnoPage")
public String findByIdAnno(@RequestParam("postno") int postno, Model model) {
Bulletin bulletin = bulletinService.findById(postno);
model.addAttribute("bulletin", bulletin);
return "/bulletin/editAnno";
}
// 修改活動貼文(原圖) //h
@PostMapping("/bulletin/EditEventop")
public @ResponseBody String updateEventOp(Bulletin bulletin) {
log.info("updateop方法執行中...");
String result = "";
try {
bulletinService.updateop(bulletin);
result = "修改成功";
} catch (Exception e) {
result = "修改失敗,請再確認";
}
return result;
}
// 修改活動貼文(改圖) //h
@PostMapping("/bulletin/EditEvent")
public @ResponseBody String save(
@RequestParam("postno") int postno,
@RequestParam("title") String title,
@RequestParam("description") String description,
@RequestParam("desText") String desText,
@RequestParam(value = "file1", required = false) MultipartFile multipartFile,
@RequestParam("quotatype") String quotatype,
@RequestParam(value = "quota", defaultValue = "0") Integer quota,
@RequestParam("endDate") Date endDate,
@RequestParam("postDate") Date postdate,
@RequestParam("exp") Date exp,
HttpServletRequest request)
throws IllegalStateException, IOException, SerialException, SQLException {
Bulletin bulletin = new Bulletin();
log.info("update方法執行中...");
if (multipartFile == null) {
} else {
String fileName = multipartFile.getOriginalFilename();
System.out.println("fileName:" + fileName);
String saveDirPath = request.getSession().getServletContext().getRealPath("/") + "uploadTempDir//"; // 取得??路徑+資料夾
File savefileDir = new File(saveDirPath);
savefileDir.mkdirs();
File saveFilePath = new File(savefileDir, fileName);
multipartFile.transferTo(saveFilePath);
System.out.println("saveFilePath:" + saveFilePath);
if (fileName != null && fileName.length() != 0) {
String saveFilePathStr = saveDirPath + fileName;
bulletin.setFile1(fileName);
FileInputStream fis1 = new FileInputStream(saveFilePathStr);
byte[] b = new byte[fis1.available()];
fis1.read(b);
fis1.close();
bulletin.setPicture(new SerialBlob(b));
}
}
log.info("update方法執行2...");
bulletin.setPostno(postno);
bulletin.setTitle(title);
bulletin.setEndDate(endDate);
bulletin.setPostDate(postdate);
bulletin.setDescription(description);
bulletin.setDesText(desText);
bulletin.setExp(exp);
bulletin.setQuotatype(quotatype);
bulletin.setQuota(quota);
String result = "";
try {
bulletinService.update(bulletin);
result = "修改成功";
System.out.println("result1:"+result);
} catch (Exception e) {
result = "修改失敗,請再確認";
System.out.println("result2:"+result);
}
return result;
}
//刪除活動貼文頁 //h
@GetMapping("/bulletin/DelEventPage")
public @ResponseBody String delEvent(@RequestParam("postno") int postno) {
log.info("delEvent方法執行中...");
String result = "";
try {
bulletinService.delete(postno);
result = "刪除成功";
} catch (Exception e) {
result = "刪除失敗,請再確認";
}
return result;
}
// 刪除公告貼文頁 //h
@GetMapping("/bulletin/DelAnnoPage")
public @ResponseBody String delAnno(Bulletin bulletin) {
log.info("updateop方法執行中...");
System.out.println("bulletin=" + bulletin);
String result = "";
try {
bulletinService.updateop(bulletin);
result = "刪除成功";
} catch (Exception e) {
result = "刪除失敗,請再確認";
}
return result;
}
}
|
package com.trump.auction.pals.api.model.alipay;
import lombok.Data;
import java.io.Serializable;
import java.util.Map;
@Data
public class AlipayBackRequest implements Serializable {
private Map<String,String> params;
private String dataJson;
}
|
/* <applet code = "BannerApplet" width = 1000 height = 600> </applet> */
import java.applet.*;
import java.applet.*;
import java.awt.*;
public class BannerApplet extends Applet implements Runnable{
String str,str1;
Thread t;
char c,c1;
public void init(){
str="HELLO WORLD...THIS IS ROBO 2.0 :-) ";
str1="WELCOME TO THE WORLD OF ROBOTS ;-)";
}
public void start(){
t=new Thread(this);
t.start();
}
public void run(){
while(true){
try{
Thread.sleep(100);
repaint();
}
catch(InterruptedException e){}
}
}
public void paint(Graphics g)
{
g.setFont(new Font("Monospaced",Font.BOLD,50));
g.setColor(Color.orange);
c=str.charAt(0);
str=str.substring(1,str.length())+c;
g.drawString(str,0,200);
g.setColor(Color.blue);
c1=str1.charAt(0);
str1=str1.substring(1,str1.length())+c1;
g.drawString(str1,0,400);
}} |
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.Power;
public class PowerRecursiveImpl implements Power {
public double pow(double x, int n) {
if (n == 0) return 1;
int exp = Math.abs(n);
double half = pow(x, exp>>1);
double res = half * half;
if ((exp & 1) == 1) res *= x;
return (n > 0) ? res : 1.0/res;
}
}
|
package codeWars.snail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Snail {
public static int[] snail(int[][] array) {
if(array[0].length == 0){
return new int[0];
}
int i = 0, j = 0;
int imin = 0, jmin = 0, imax = array.length-1, jmax = array[0].length-1;
int flagi = 1, flagj = 0;
List<Integer> result = new ArrayList<Integer>();
while(true){
if(imax<imin)
break;
if(flagi == 1){
for(i = imin ; i<=imax ; i++){
result.add(array[j][i]);
}
jmin++;
i--;
flagi = 0;
flagj = 1;
}else if (flagi == -1){
for(i = imax ; i>=imin ; i--){
result.add(array[j][i]);
}
i++;
jmax--;
flagi = 0;
flagj = -1;
}else if (flagj == 1){
for(j = jmin ; j<=jmax ; j++){
result.add(array[j][i]);
}
j--;
imax--;
flagi = -1;
flagj = 0;
}else if (flagj == -1){
for(j = jmax ; j>=jmin ; j--){
result.add(array[j][i]);
}
j++;
imin++;
flagi = 1;
flagj = 0;
}
}
System.out.println(Arrays.toString(result.toArray()));
int[] re = new int[result.size()];
for(int x = 0 ; x<re.length ; x++){
re[x] = result.get(x);
}
return re;
}
} |
/**
* Copyright (C) 2008 Atlassian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.atlassian.theplugin.idea.crucible;
import com.atlassian.connector.cfg.ProjectCfgManager;
import com.atlassian.connector.intellij.crucible.IntelliJCrucibleServerFacade;
import com.atlassian.connector.intellij.crucible.ReviewAdapter;
import com.atlassian.theplugin.commons.crucible.api.model.Review;
import com.atlassian.theplugin.commons.exception.ServerPasswordNotProvidedException;
import com.atlassian.theplugin.commons.remoteapi.RemoteApiException;
import com.atlassian.theplugin.commons.remoteapi.ServerData;
import com.atlassian.theplugin.exception.PatchCreateErrorException;
import com.atlassian.theplugin.idea.IdeaVersionFacade;
import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.ui.MultipleChangeListBrowser;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
public class CrucibleCreatePreCommitUploadReviewForm extends AbstractCrucibleCreatePreCommitReviewForm {
public static final String LOCAL_CHANGES_BROWSER = "theplugin.crucible.localchangesbrowser";
public static final DataKey<CrucibleCreatePostCommitReviewForm> COMMITTED_CHANGES_BROWSER_KEY = DataKey
.create(LOCAL_CHANGES_BROWSER);
private final MultipleChangeListBrowser changesBrowser;
public CrucibleCreatePreCommitUploadReviewForm(final Project project, final IntelliJCrucibleServerFacade crucibleServerFacade,
Collection<Change> changes,
@NotNull final ProjectCfgManager projectCfgManager) {
super(project, crucibleServerFacade, "", projectCfgManager);
ChangeListManager changeListManager = ChangeListManager.getInstance(project);
changesBrowser = IdeaVersionFacade.getInstance().getChangesListBrowser(project, changeListManager, changes);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setCustomComponent(changesBrowser);
setTitle("Create Pre-Commit Review");
pack();
}
});
}
@Override
protected boolean isPatchForm() {
return true;
}
@Override
protected ReviewAdapter createReview(final ServerData server, final Review reviewProvider)
throws RemoteApiException, ServerPasswordNotProvidedException, VcsException, IOException,
PatchCreateErrorException {
List<Change> changes = changesBrowser.getCurrentIncludedChanges();
return createReviewImpl(server, reviewProvider, changes);
}
} |
package domain;
import java.io.Serializable;
import net.sf.json.JSONObject;
public class StaffDTO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int staffId;
private String firstname;
private String lastname;
private String number;
private String status;
public int getStaffId() {
return staffId;
}
public void setStaffId(int staffId) {
this.staffId = staffId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
/*return "Staff{"+
"staffId=" + staffId +
"firstname=" + firstname +
"lastname=" + lastname +
"number=" + number +
"status=" + status +
"}";*/
return JSONObject.fromObject(this).toString();
}
/**
* convert a string into a staffDTO object
* @param s
* @return
*/
public static StaffDTO readString(String s) {
JSONObject json = JSONObject.fromObject(s);
return (StaffDTO) JSONObject.toBean(json, StaffDTO.class);
}
}
|
package com.example.diary.util;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.MainThread;
import java.lang.invoke.MethodHandles;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class AppExecutors {
private static final Object LOCK = new Object();
private static AppExecutors instance;
private final Executor diskIO, mainThread, networkIO;
private AppExecutors(Executor diskIO, Executor networkIO,Executor mainThread) {
this.diskIO = diskIO;
this.mainThread = mainThread;
this.networkIO = networkIO;
}
public Executor getMainThread() {
return mainThread;
}
public Executor getDiskIO() {
return diskIO;
}
public static AppExecutors getInstance(){
if(instance==null){
synchronized (LOCK){
instance=new AppExecutors(Executors.newSingleThreadExecutor(),Executors.newFixedThreadPool(3),new MainThreadExecutor());
}
}
return instance;
}
private static class MainThreadExecutor implements Executor{
private Handler mainThreadHandler=new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
mainThreadHandler.post(command);
}
}
} |
import java.io.*;
import java.util.*;
import edu.stanford.nlp.io.*;
import edu.stanford.nlp.ling.*;
import edu.stanford.nlp.pipeline.*;
import edu.stanford.nlp.trees.*;
import edu.stanford.nlp.util.*;
public class splitmailText {
public static void main(String args[]) throws Exception{
if (args.length != 2){
System.out.println("Usage : splitmailText <input_file_name> <output_file_name> ");
return;
}
BufferedReader input_file = new BufferedReader(new FileReader(new File("./"+args[0])));
BufferedWriter output_file = new BufferedWriter(new FileWriter(new File("./"+args[1])));
String next_line = null;
boolean flag = false;
while((next_line = input_file.readLine())!=null)
{
StringTokenizer st = new StringTokenizer(next_line);
if (st.hasMoreTokens())
{
String first_word = st.nextToken();
if (first_word == ">" && !flag)
{
output_file.write("Separate Structure");
flag = true;
}
while (st.hasMoreTokens())
{
String next_word = st.nextToken();
if (next_word != ">")
output_file.write(next_word+" ");
}
}
output_file.write("\n");
output_file.flush();
}
input_file.close();
output_file.close();
}
}
|
package android.support.constraint.solver;
import android.support.constraint.solver.SolverVariable.Type;
import java.io.PrintStream;
import java.util.Arrays;
public class ArrayLinkedVariables {
private static final boolean DEBUG = false;
private static final int NONE = -1;
private int ROW_SIZE = 8;
private SolverVariable candidate = null;
int currentSize;
private int[] mArrayIndices = new int[this.ROW_SIZE];
private int[] mArrayNextIndices = new int[this.ROW_SIZE];
private float[] mArrayValues = new float[this.ROW_SIZE];
private final Cache mCache;
private boolean mDidFillOnce;
private int mHead;
private int mLast;
private final ArrayRow mRow;
ArrayLinkedVariables(ArrayRow arrayRow, Cache cache) {
boolean z = false;
this.currentSize = z;
int i = -1;
this.mHead = i;
this.mLast = i;
this.mDidFillOnce = z;
this.mRow = arrayRow;
this.mCache = cache;
}
public final void put(SolverVariable solverVariable, float f) {
if (f == 0.0f) {
remove(solverVariable);
return;
}
boolean z = false;
int i = -1;
boolean z2 = true;
if (this.mHead == i) {
this.mHead = z;
this.mArrayValues[this.mHead] = f;
this.mArrayIndices[this.mHead] = solverVariable.id;
this.mArrayNextIndices[this.mHead] = i;
this.currentSize += z2;
if (!this.mDidFillOnce) {
this.mLast += z2;
}
return;
}
int i2 = this.mHead;
int i3 = z;
int i4 = i;
while (i2 != i && i3 < this.currentSize) {
if (this.mArrayIndices[i2] == solverVariable.id) {
this.mArrayValues[i2] = f;
return;
}
if (this.mArrayIndices[i2] < solverVariable.id) {
i4 = i2;
}
i2 = this.mArrayNextIndices[i2];
i3++;
}
i2 = this.mLast + z2;
if (this.mDidFillOnce) {
if (this.mArrayIndices[this.mLast] == i) {
i2 = this.mLast;
} else {
i2 = this.mArrayIndices.length;
}
}
if (i2 >= this.mArrayIndices.length && this.currentSize < this.mArrayIndices.length) {
for (i3 = z; i3 < this.mArrayIndices.length; i3++) {
if (this.mArrayIndices[i3] == i) {
i2 = i3;
break;
}
}
}
if (i2 >= this.mArrayIndices.length) {
i2 = this.mArrayIndices.length;
this.ROW_SIZE *= 2;
this.mDidFillOnce = z;
this.mLast = i2 - 1;
this.mArrayValues = Arrays.copyOf(this.mArrayValues, this.ROW_SIZE);
this.mArrayIndices = Arrays.copyOf(this.mArrayIndices, this.ROW_SIZE);
this.mArrayNextIndices = Arrays.copyOf(this.mArrayNextIndices, this.ROW_SIZE);
}
this.mArrayIndices[i2] = solverVariable.id;
this.mArrayValues[i2] = f;
if (i4 != i) {
this.mArrayNextIndices[i2] = this.mArrayNextIndices[i4];
this.mArrayNextIndices[i4] = i2;
} else {
this.mArrayNextIndices[i2] = this.mHead;
this.mHead = i2;
}
this.currentSize += z2;
if (!this.mDidFillOnce) {
this.mLast += z2;
}
if (this.currentSize >= this.mArrayIndices.length) {
this.mDidFillOnce = z2;
}
}
public final void add(SolverVariable solverVariable, float f) {
float f2 = 0.0f;
if (f != f2) {
boolean z = false;
int i = -1;
boolean z2 = true;
if (this.mHead == i) {
this.mHead = z;
this.mArrayValues[this.mHead] = f;
this.mArrayIndices[this.mHead] = solverVariable.id;
this.mArrayNextIndices[this.mHead] = i;
this.currentSize += z2;
if (!this.mDidFillOnce) {
this.mLast += z2;
}
return;
}
int i2 = this.mHead;
int i3 = z;
int i4 = i;
while (i2 != i && i3 < this.currentSize) {
int i5 = this.mArrayIndices[i2];
if (i5 == solverVariable.id) {
float[] fArr = this.mArrayValues;
fArr[i2] = fArr[i2] + f;
if (this.mArrayValues[i2] == f2) {
if (i2 == this.mHead) {
this.mHead = this.mArrayNextIndices[i2];
} else {
this.mArrayNextIndices[i4] = this.mArrayNextIndices[i2];
}
this.mCache.mIndexedVariables[i5].removeClientEquation(this.mRow);
if (this.mDidFillOnce) {
this.mLast = i2;
}
this.currentSize -= z2;
}
return;
}
if (this.mArrayIndices[i2] < solverVariable.id) {
i4 = i2;
}
i2 = this.mArrayNextIndices[i2];
i3++;
}
int i6 = this.mLast + z2;
if (this.mDidFillOnce) {
if (this.mArrayIndices[this.mLast] == i) {
i6 = this.mLast;
} else {
i6 = this.mArrayIndices.length;
}
}
if (i6 >= this.mArrayIndices.length && this.currentSize < this.mArrayIndices.length) {
for (i2 = z; i2 < this.mArrayIndices.length; i2++) {
if (this.mArrayIndices[i2] == i) {
i6 = i2;
break;
}
}
}
if (i6 >= this.mArrayIndices.length) {
i6 = this.mArrayIndices.length;
this.ROW_SIZE *= 2;
this.mDidFillOnce = z;
this.mLast = i6 - 1;
this.mArrayValues = Arrays.copyOf(this.mArrayValues, this.ROW_SIZE);
this.mArrayIndices = Arrays.copyOf(this.mArrayIndices, this.ROW_SIZE);
this.mArrayNextIndices = Arrays.copyOf(this.mArrayNextIndices, this.ROW_SIZE);
}
this.mArrayIndices[i6] = solverVariable.id;
this.mArrayValues[i6] = f;
if (i4 != i) {
this.mArrayNextIndices[i6] = this.mArrayNextIndices[i4];
this.mArrayNextIndices[i4] = i6;
} else {
this.mArrayNextIndices[i6] = this.mHead;
this.mHead = i6;
}
this.currentSize += z2;
if (!this.mDidFillOnce) {
this.mLast += z2;
}
if (this.mLast >= this.mArrayIndices.length) {
this.mDidFillOnce = z2;
this.mLast = this.mArrayIndices.length - z2;
}
}
}
public final float remove(SolverVariable solverVariable) {
if (this.candidate == solverVariable) {
this.candidate = null;
}
float f = 0.0f;
int i = -1;
if (this.mHead == i) {
return f;
}
int i2 = this.mHead;
int i3 = 0;
int i4 = i;
while (i2 != i && i3 < this.currentSize) {
int i5 = this.mArrayIndices[i2];
if (i5 == solverVariable.id) {
if (i2 == this.mHead) {
this.mHead = this.mArrayNextIndices[i2];
} else {
this.mArrayNextIndices[i4] = this.mArrayNextIndices[i2];
}
this.mCache.mIndexedVariables[i5].removeClientEquation(this.mRow);
this.currentSize--;
this.mArrayIndices[i2] = i;
if (this.mDidFillOnce) {
this.mLast = i2;
}
return this.mArrayValues[i2];
}
i3++;
i4 = i2;
i2 = this.mArrayNextIndices[i2];
}
return f;
}
public final void clear() {
int i = -1;
this.mHead = i;
this.mLast = i;
boolean z = false;
this.mDidFillOnce = z;
this.currentSize = z;
}
final boolean containsKey(SolverVariable solverVariable) {
int i = -1;
boolean z = false;
if (this.mHead == i) {
return z;
}
int i2 = this.mHead;
int i3 = z;
while (i2 != i && i3 < this.currentSize) {
if (this.mArrayIndices[i2] == solverVariable.id) {
return true;
}
i2 = this.mArrayNextIndices[i2];
i3++;
}
return z;
}
boolean hasAtLeastOnePositiveVariable() {
int i = this.mHead;
boolean z = false;
int i2 = z;
while (i != -1 && i2 < this.currentSize) {
if (this.mArrayValues[i] > 0.0f) {
return true;
}
i = this.mArrayNextIndices[i];
i2++;
}
return z;
}
void invert() {
int i = this.mHead;
int i2 = 0;
while (i != -1 && i2 < this.currentSize) {
float[] fArr = this.mArrayValues;
fArr[i] = fArr[i] * -1.0f;
i = this.mArrayNextIndices[i];
i2++;
}
}
void divideByAmount(float f) {
int i = this.mHead;
int i2 = 0;
while (i != -1 && i2 < this.currentSize) {
float[] fArr = this.mArrayValues;
fArr[i] = fArr[i] / f;
i = this.mArrayNextIndices[i];
i2++;
}
}
void updateClientEquations(ArrayRow arrayRow) {
int i = this.mHead;
int i2 = 0;
while (i != -1 && i2 < this.currentSize) {
this.mCache.mIndexedVariables[this.mArrayIndices[i]].addClientEquation(arrayRow);
i = this.mArrayNextIndices[i];
i2++;
}
}
SolverVariable pickPivotCandidate() {
int i = this.mHead;
SolverVariable solverVariable = null;
int i2 = 0;
SolverVariable solverVariable2 = solverVariable;
while (i != -1 && i2 < this.currentSize) {
float f = this.mArrayValues[i];
float f2 = 0.001f;
float f3 = 0.0f;
if (f < f3) {
if (f > -0.001f) {
this.mArrayValues[i] = f3;
}
if (f == f3) {
SolverVariable solverVariable3 = this.mCache.mIndexedVariables[this.mArrayIndices[i]];
if (solverVariable3.mType == Type.UNRESTRICTED) {
if (f < f3) {
return solverVariable3;
}
if (solverVariable == null) {
solverVariable = solverVariable3;
}
} else if (f < f3 && (solverVariable2 == null || solverVariable3.strength < solverVariable2.strength)) {
solverVariable2 = solverVariable3;
}
}
i = this.mArrayNextIndices[i];
i2++;
} else {
if (f < f2) {
this.mArrayValues[i] = f3;
}
if (f == f3) {
SolverVariable solverVariable32 = this.mCache.mIndexedVariables[this.mArrayIndices[i]];
if (solverVariable32.mType == Type.UNRESTRICTED) {
if (f < f3) {
return solverVariable32;
}
if (solverVariable == null) {
solverVariable = solverVariable32;
}
} else if (f < f3 && (solverVariable2 == null || solverVariable32.strength < solverVariable2.strength)) {
solverVariable2 = solverVariable32;
}
}
i = this.mArrayNextIndices[i];
i2++;
}
f = f3;
if (f == f3) {
SolverVariable solverVariable322 = this.mCache.mIndexedVariables[this.mArrayIndices[i]];
if (solverVariable322.mType == Type.UNRESTRICTED) {
if (f < f3) {
return solverVariable322;
}
if (solverVariable == null) {
solverVariable = solverVariable322;
}
} else if (f < f3 && (solverVariable2 == null || solverVariable322.strength < solverVariable2.strength)) {
solverVariable2 = solverVariable322;
}
}
i = this.mArrayNextIndices[i];
i2++;
}
return solverVariable != null ? solverVariable : solverVariable2;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
void updateFromRow(android.support.constraint.solver.ArrayRow r9, android.support.constraint.solver.ArrayRow r10) {
/*
r8 = this;
r0 = r8.mHead;
r1 = 0;
L_0x0003:
r2 = r1;
L_0x0004:
r3 = -1;
if (r0 == r3) goto L_0x0059;
L_0x0007:
r4 = r8.currentSize;
if (r2 >= r4) goto L_0x0059;
L_0x000b:
r4 = r8.mArrayIndices;
r4 = r4[r0];
r5 = r10.variable;
r5 = r5.id;
if (r4 != r5) goto L_0x0052;
L_0x0015:
r2 = r8.mArrayValues;
r0 = r2[r0];
r2 = r10.variable;
r8.remove(r2);
r2 = r10.variables;
r4 = r2.mHead;
r5 = r1;
L_0x0023:
if (r4 == r3) goto L_0x0042;
L_0x0025:
r6 = r2.currentSize;
if (r5 >= r6) goto L_0x0042;
L_0x0029:
r6 = r8.mCache;
r6 = r6.mIndexedVariables;
r7 = r2.mArrayIndices;
r7 = r7[r4];
r6 = r6[r7];
r7 = r2.mArrayValues;
r7 = r7[r4];
r7 = r7 * r0;
r8.add(r6, r7);
r6 = r2.mArrayNextIndices;
r4 = r6[r4];
r5 = r5 + 1;
goto L_0x0023;
L_0x0042:
r2 = r9.constantValue;
r3 = r10.constantValue;
r3 = r3 * r0;
r2 = r2 + r3;
r9.constantValue = r2;
r0 = r10.variable;
r0.removeClientEquation(r9);
r0 = r8.mHead;
goto L_0x0003;
L_0x0052:
r3 = r8.mArrayNextIndices;
r0 = r3[r0];
r2 = r2 + 1;
goto L_0x0004;
L_0x0059:
return;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.constraint.solver.ArrayLinkedVariables.updateFromRow(android.support.constraint.solver.ArrayRow, android.support.constraint.solver.ArrayRow):void");
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
void updateFromSystem(android.support.constraint.solver.ArrayRow r10, android.support.constraint.solver.ArrayRow[] r11) {
/*
r9 = this;
r0 = r9.mHead;
r1 = 0;
L_0x0003:
r2 = r1;
L_0x0004:
r3 = -1;
if (r0 == r3) goto L_0x0063;
L_0x0007:
r4 = r9.currentSize;
if (r2 >= r4) goto L_0x0063;
L_0x000b:
r4 = r9.mCache;
r4 = r4.mIndexedVariables;
r5 = r9.mArrayIndices;
r5 = r5[r0];
r4 = r4[r5];
r5 = r4.definitionId;
if (r5 == r3) goto L_0x005c;
L_0x0019:
r2 = r9.mArrayValues;
r0 = r2[r0];
r9.remove(r4);
r2 = r4.definitionId;
r2 = r11[r2];
r4 = r2.isSimpleDefinition;
if (r4 != 0) goto L_0x004c;
L_0x0028:
r4 = r2.variables;
r5 = r4.mHead;
r6 = r1;
L_0x002d:
if (r5 == r3) goto L_0x004c;
L_0x002f:
r7 = r4.currentSize;
if (r6 >= r7) goto L_0x004c;
L_0x0033:
r7 = r9.mCache;
r7 = r7.mIndexedVariables;
r8 = r4.mArrayIndices;
r8 = r8[r5];
r7 = r7[r8];
r8 = r4.mArrayValues;
r8 = r8[r5];
r8 = r8 * r0;
r9.add(r7, r8);
r7 = r4.mArrayNextIndices;
r5 = r7[r5];
r6 = r6 + 1;
goto L_0x002d;
L_0x004c:
r3 = r10.constantValue;
r4 = r2.constantValue;
r4 = r4 * r0;
r3 = r3 + r4;
r10.constantValue = r3;
r0 = r2.variable;
r0.removeClientEquation(r10);
r0 = r9.mHead;
goto L_0x0003;
L_0x005c:
r3 = r9.mArrayNextIndices;
r0 = r3[r0];
r2 = r2 + 1;
goto L_0x0004;
L_0x0063:
return;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.constraint.solver.ArrayLinkedVariables.updateFromSystem(android.support.constraint.solver.ArrayRow, android.support.constraint.solver.ArrayRow[]):void");
}
SolverVariable getPivotCandidate() {
if (this.candidate != null) {
return this.candidate;
}
int i = this.mHead;
int i2 = 0;
SolverVariable solverVariable = null;
while (i != -1 && i2 < this.currentSize) {
if (this.mArrayValues[i] < 0.0f) {
SolverVariable solverVariable2 = this.mCache.mIndexedVariables[this.mArrayIndices[i]];
if (solverVariable == null || solverVariable.strength < solverVariable2.strength) {
solverVariable = solverVariable2;
}
}
i = this.mArrayNextIndices[i];
i2++;
}
return solverVariable;
}
final SolverVariable getVariable(int i) {
int i2 = this.mHead;
int i3 = 0;
while (i2 != -1 && i3 < this.currentSize) {
if (i3 == i) {
return this.mCache.mIndexedVariables[this.mArrayIndices[i2]];
}
i2 = this.mArrayNextIndices[i2];
i3++;
}
return null;
}
final float getVariableValue(int i) {
int i2 = this.mHead;
int i3 = 0;
while (i2 != -1 && i3 < this.currentSize) {
if (i3 == i) {
return this.mArrayValues[i2];
}
i2 = this.mArrayNextIndices[i2];
i3++;
}
return 0.0f;
}
public final float get(SolverVariable solverVariable) {
int i = this.mHead;
int i2 = 0;
while (i != -1 && i2 < this.currentSize) {
if (this.mArrayIndices[i] == solverVariable.id) {
return this.mArrayValues[i];
}
i = this.mArrayNextIndices[i];
i2++;
}
return 0.0f;
}
int sizeInBytes() {
return (0 + (3 * (this.mArrayIndices.length * 4))) + 36;
}
public void display() {
int i = this.currentSize;
System.out.print("{ ");
for (int i2 = 0; i2 < i; i2++) {
SolverVariable variable = getVariable(i2);
if (variable != null) {
PrintStream printStream = System.out;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(variable);
stringBuilder.append(" = ");
stringBuilder.append(getVariableValue(i2));
stringBuilder.append(" ");
printStream.print(stringBuilder.toString());
}
}
System.out.println(" }");
}
public String toString() {
String str = "";
int i = this.mHead;
int i2 = 0;
while (i != -1 && i2 < this.currentSize) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(" -> ");
str = stringBuilder.toString();
stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(this.mArrayValues[i]);
stringBuilder.append(" : ");
str = stringBuilder.toString();
stringBuilder = new StringBuilder();
stringBuilder.append(str);
stringBuilder.append(this.mCache.mIndexedVariables[this.mArrayIndices[i]]);
str = stringBuilder.toString();
i = this.mArrayNextIndices[i];
i2++;
}
return str;
}
}
|
package DAO;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLDataException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import PO.Cart;
import PO.CartItem;
import PO.Frame;
import PO.Order;
import PO.OrderItem;
public class OrderDaoImpl implements IOrderDao{
final String driver = "com.mysql.jdbc.Driver";
final String url = "jdbc:mysql://115.159.184.185/GlassesOnline";
final String user = "root";
final String password = "admin";
@Override
public List<Order> getOrders(int customerID) throws Exception {
// TODO Auto-generated method stub
List<Order> orders = null;
try{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,user,password);
PreparedStatement sql = conn.prepareStatement("select * from glass_order where customerID = ?");
sql.setObject(1, customerID);
ResultSet rs = sql.executeQuery();
orders = new ArrayList<Order>();
while(rs.next()){
Timestamp date = rs.getTimestamp("orderDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Order order = new Order(customerID, formatter.format(date));
orders.add(order);
}
rs.close();
sql.close();
conn.close();
}catch(Exception e){
throw new Exception(e);
}
return orders;
}
/*
* create a new order and add order items into it.
* The order items are exactly the same as the cart items in the cart with this customerID.
*
* return: @error_code
* 1: ROLLBACK
* 0: COMMIT
*/
@Override
public int newOrder(Order order, Cart cart) throws Exception {
// TODO Auto-generated method stub
int error_code = -1;
try{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,user,password);
PreparedStatement sql = conn.prepareStatement("call cart_to_order(?)");
sql.setObject(1, cart.getCustomerID());
ResultSet rs = sql.executeQuery();
if (rs.next()) {
error_code = rs.getInt(1);
}
rs.close();
sql.close();
conn.close();
}catch(Exception e){
throw new Exception(e);
}
return error_code;
}
}
|
package xPath;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class xPathMain {
public static void main(String[] args) {
Runtime.getRuntime().gc();
long startMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(), endMemory = 0;
long start = System.currentTimeMillis();
xPathMain sr = new xPathMain();
int[] arrayFN = sr.searchBF();
sr.searchSR(arrayFN);
endMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long end = System.currentTimeMillis();
System.out.print("끝난시간!:");
System.out.print((end - start)/1000.0 + "초");
System.out.print(", 메모리 사용량 : " + String.format("%,d", (endMemory - startMemory) / 1000) + " kbyte");
}
/**
* 해당 메소드는 5가지 일을 수행한다
* 1. F로 시작되는 xml 파일에서 SIMILAR_RATE 를 100으로 나누었을 때의 값이 15이상인것을찾는다.
* 2. P로 시작되는 xml 파일에서 ROW에 대한 정보를 모두 추출한다.
* 3. 파일의 경로를 지정해주고, 해당 폴더가 존재하지않으면은 생성하고 그렇지않으면은 이미 폴더가 있다는 메세지 출력
* 4. PID의 content를 찾아 key로 할당하고 ROW태그 전체를 value 로 할당한다.
* 5. P파일에서 PID를 찾고 하위 노드에 LICENSE 번호를 가져와 COMMENT태그에 쓴다
* 6. 작업이 끝나면은 파일을 생성해준다.
*
* 해당 작업이 끝날 때마다 T로 시작되는 파일로 생성한다.
*
* @param array
* @return
*/
private String[] searchSR(int[] array) {
String arraypid[] = new String[146]; //146
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = null;
Document doc1 = null;
XPath xp = XPathFactory.newInstance().newXPath();
//3
String path = "C:\\Users\\meta\\eclipse-workspace\\xPath-backup2\\src\\data\\test";
File Folder = new File(path);
if(!Folder.exists()) {
try {
Folder.mkdir();
System.out.println("폴더가 생성되었습니다.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("이미 폴더가 있습니다.");
}
//end of 3
for(int i=0; i<array.length; i++) {
doc = db.parse("src\\data\\F_"+array[i]+"_TB.xml");
doc1 = db.parse("src\\data\\P_"+array[i]+"_TB.xml");
//1
NodeList nl = (NodeList) xp.compile("//ROWS/ROW[SIMILAR_RATE div 100 > 15]").evaluate(doc, XPathConstants.NODESET);
//end of 1
//2
NodeList nl1 = (NodeList) xp.compile("//ROWS/ROW").evaluate(doc1, XPathConstants.NODESET);
//end of 2
Map<String, Node> pmap = new HashMap<String, Node>();
//4
for(int k=0; k<nl1.getLength(); k++) {
Node xpnode = getNodeByTagName(nl1.item(k),"P_ID");
pmap.put(xpnode.getTextContent(), nl1.item(k));
}
//end of 4
//5
for(int j=0; j<nl.getLength(); j++) {
Node xpnode = getNodeByTagName(nl.item(j),"P_ID");
if(pmap.containsKey(xpnode.getTextContent())) {
Node nodeLIC = getNodeByTagName(pmap.get(xpnode.getTextContent()),"LICENSE_ID");
Node comment = getNodeByTagName(nl.item(j),"COMMENT");
comment.setTextContent(nodeLIC.getTextContent());
}
}
//end of 5
//6
DOMSource xmlDOM = new DOMSource(doc);
StreamResult xmlFile = new StreamResult(new File("src\\data\\test\\T_"+array[i]+"_TB.xml"));
TransformerFactory.newInstance().newTransformer().transform(xmlDOM, xmlFile);
//end of 6
}
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | TransformerException | TransformerFactoryConfigurationError e) {
e.printStackTrace();
}
return arraypid;
}
//basefile에서 파일 숫자 찾기
private int[] searchBF() {
String val = "";
int[] array = new int[112];
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = null;
doc = builder.parse("src\\data\\T_BASEFILE_TB.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression srexpr = xpath.compile("//ROWS/ROW");
Object srresult = (NodeList) srexpr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) srresult;
for(int i=0; i<=nodes.getLength()-1; i++) {
val = nodes.item(i).getChildNodes().item(1).getChildNodes().item(0).getTextContent();
// System.out.println(nodes.item(i).getChildNodes().item(1).getChildNodes().item(0).getNodeValue());
// System.out.println(i + " 값 " +val);
array[i] = Integer.parseInt(val);
}
// System.out.println(Arrays.toString(array));
} catch (NumberFormatException | XPathExpressionException | DOMException | ParserConfigurationException | SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return array;
}
//태그의 이름을 사용하여 노드찾기
private Node getNodeByTagName(Node parent, String tagName)
{
Node result = null;
NodeList nl = parent.getChildNodes();
for(int i=0; i < nl.getLength(); i++)
{
Node node = nl.item(i);
if(node.getNodeType() == Node.ELEMENT_NODE && tagName.compareTo(node.getNodeName()) == 0)
{
result = nl.item(i);
break;
}
}
return result;
}
}
|
package net.awesomekorean.podo.lesson.lessons;
import net.awesomekorean.podo.R;
import java.io.Serializable;
public class Lesson27 extends LessonInit_Lock implements Lesson, LessonItem, Serializable {
private String lessonId = "L_27";
private String lessonTitle = "because, so";
private String lessonSubTitle = "~아/어서";
private LessonItem specialLesson = new S_Lesson08();
private Integer dayCount = 7;
private String[] wordFront = {"살다", "싸다", "비싸다", "사다", "팔다", "하지만"};
private String[] wordBack = {"live in", "cheap", "expensive", "buy", "sell", "however"};
private String[] wordPronunciation = {"-", "-", "-", "-", "-", "-"};
private String[] sentenceFront = {
"저는 살고 있어요.",
"저는 태국에서 살고 있어요.",
"많이 사요.",
"망고가 아주 싸서 많이 사요.",
"태국에는 망고가 아주 싸서 많이 사요.",
"태국 망고를 팔아요.",
"한국에도 태국 망고를 팔아요.",
"못 사요.",
"너무 비싸서 못 사요."
};
private String[] sentenceBack = {
"I live.",
"I live in thailand.",
"I buy it a lot.",
"Mango is very cheap so I buy it a lot.",
"Mango is very cheap in Thailand so I buy it a lot.",
"They sell Thai mango.",
"They sell Thai mango in Korea as well.",
"I can't buy it.",
"It is very expensive so I can't buy."
};
private String[] sentenceExplain = {
"'살다' -> '살' + '고 있다' = '살고 있다'",
"-",
"-",
"Don't be confused.\n'사다 ' -> '사요' (to buy)\n'살다' -> '살아요' (to live)\n\nWhen you want to say the reason, use the '아/어서' form.\n'싸요' -> '싸' + '서' = '싸서'\n\nYou can also use '(으)니까' form in the same way.\n'싸다' -> '싸' + '니까' = '싸니까'",
"-",
"-",
"'도' means 'also'.",
"The Batchim 'ㅅ' of '못' can affect to the consonant 'ㅅ' of '사요' so you may can hear 'ㅆ' sound.",
"'비싸요' -> '비싸' + '서' = '비싸서'\n\n'비싸다' -> '비싸' + '니까' = '비싸니까'"
};
private String[] dialog = {
"저는 태국에서 살고 있어요\n태국에는 망고가 아주 싸서 많이 사요.",
"한국에도 태국 망고를 팔아요.\n하지만 너무 비싸서 못 사요."
};
private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p};
private int[] reviewId = {1,6};
@Override
public String getLessonSubTitle() {
return lessonSubTitle;
}
@Override
public String getLessonId() {
return lessonId;
}
@Override
public String[] getWordFront() {
return wordFront;
}
@Override
public String[] getWordPronunciation() {
return wordPronunciation;
}
@Override
public String[] getSentenceFront() {
return sentenceFront;
}
@Override
public String[] getDialog() {
return dialog;
}
@Override
public int[] getPeopleImage() {
return peopleImage;
}
@Override
public String[] getWordBack() {
return wordBack;
}
@Override
public String[] getSentenceBack() {
return sentenceBack;
}
@Override
public String[] getSentenceExplain() {
return sentenceExplain;
}
@Override
public int[] getReviewId() {
return reviewId;
}
// 레슨어뎁터 아이템
@Override
public String getLessonTitle() {
return lessonTitle;
}
@Override
public LessonItem getSLesson() {
return specialLesson;
}
@Override
public Integer getDayCount() {
return dayCount;
}
}
|
package sch.frog.calculator.util;
import sch.frog.calculator.util.collection.ITraveller;
public class Arrays {
public static <T> String toString(T[] arr){
if(arr == null) return "null";
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean start = true;
for (T t : arr) {
if(start){ start = false; }
else{ builder.append(','); }
builder.append(t);
}
builder.append(']');
return builder.toString();
}
public static String toString(char[] chars){
if(chars == null){ return "null"; }
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean start = true;
for(char c : chars){
if(start){ start = false; }
else{ builder.append(','); }
builder.append(c);
}
builder.append(']');
return builder.toString();
}
public static String toString(int[] arr){
if(arr == null) return "null";
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean start = true;
for (int i : arr) {
if(start){ start = false; }
else{ builder.append(','); }
builder.append(i);
}
builder.append(']');
return builder.toString();
}
public static <T> void copy(T[] source, T[] dest, int start, int end){
checkCopy(source.length, dest.length, start, end);
for(int i = 0, j = start; j <= end; j++, i++){
dest[i] = source[j];
}
}
public static void copy(int[] source, int[] dest, int start, int end){
checkCopy(source.length, dest.length, start, end);
for(int i = 0, j = start; j < end; j++, i++){
dest[i] = source[j];
}
}
public static void copy(char[] source, char[] dest, int start, int end){
checkCopy(source.length, dest.length, start, end);
for(int i = 0, j = start; j < end; j++, i++){
dest[i] = source[j];
}
}
private static void checkCopy(int sourceLen, int destLen, int start, int end){
if(start < 0 || end > sourceLen || start > end){
throw new IllegalArgumentException("start and end index is error. start : " + start + ", end : " + end);
}
if(end - start > destLen){
throw new IllegalArgumentException("desc array is not enough. desc's length : " + destLen + ", will put : " + (end - start + 1));
}
}
public static ITraveller<Integer> traveller(int[] array){
return new IntegerArrayTraveller(array);
}
public static <T> ITraveller<T> traveller(T[] array){
return new ArrayTraveller<>(array);
}
private static class ArrayTraveller<E> implements ITraveller<E> {
private E[] array;
private int i = -1;
public ArrayTraveller(E[] array) {
this.array = array;
}
@Override
public boolean hasNext() {
return i + 1 < array.length;
}
@Override
public E next() {
return this.array[++i];
}
}
private static class IntegerArrayTraveller implements ITraveller<Integer> {
private int[] array;
private int i = -1;
public IntegerArrayTraveller(int[] array) {
this.array = array;
}
@Override
public boolean hasNext() {
return i + 1 < array.length;
}
@Override
public Integer next() {
return this.array[++i];
}
}
}
|
package edu.neu.ccs.cs5010;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.*;
/**
* Created by xwenfei on 10/2/17.
*/
public class RoomTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private Room room1;
private Room room2;
private Room room3;
private MyPriorityQueue<Room> RoomQueue;
@Before
public void setUp() throws Exception {
room1 = new Room();
room2 = new Room();
room3 = new Room();
RoomQueue = new MyPriorityQueue<Room>();
room1.updateTimeOccupied(30);
room2.updateTimeOccupied(20);
room3.updateTimeOccupied(40);
RoomQueue.insert(room1);
RoomQueue.insert(room2);
RoomQueue.insert(room3);
assertEquals(RoomQueue.front(), room2);
}
@Test
public void compareException() throws Exception {
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("room to compare is null");
Room room = new Room();
room.compareTo(null);
}
@Test
public void compareTest() throws Exception {
room1 = new Room();
room2 = new Room();
room1.updateTimeOccupied(30);
room2.updateTimeOccupied(20);
assertEquals(room1.compareTo(room2), room1.timeOccupied - room2.timeOccupied);
assertEquals(room1.compareTo(room2), 10);
}
} |
/*Joshua Palmer Z23280034
* COP 4331 001
* Homework 2 Question 4
*/
package hw2;
import java.util.Scanner;
public class Register {
/**Stores records of all products*/
private Inventory inventory;
/**Stores record of the products currently being purchased*/
private Transaction currentTransaction;
/**Gets UPC number from Products*/
private UPCScanner scanner;
public Register() {
currentTransaction = new Transaction();
scanner = new UPCScanner();
inventory = new Inventory();
}
/**
* Adds a product to the inventory.
* @param newProduct product to be added
*/
public void addToInventory(Product newProduct) {
inventory.addProduct(newProduct);
}
/**
* Uses the UPCScanner to find items from the inventory,
* add them to the current transaction, and display their
* details to the console.
*/
public void scanItems() {
String currentUPC = "";
Product purchasedItem;
while (!currentUPC.equals("p")) {
System.out.println("(Enter 'p' to pay)");
System.out.print("Enter 12-digit UPC: ");
currentUPC = scanner.scan().trim().toLowerCase();
if (inventory.productExists(currentUPC)) {
showProductDetails(currentUPC);
purchasedItem = inventory.getProduct(currentUPC);
currentTransaction.addItem(purchasedItem);
} else if (!currentUPC.equals("p")) {
System.out.println("Item does not exist, or invalid UPC given.");
}
}
}
/**
* Helper function to display a Products details.
* @param upc id of the Product to be displayed.
*/
private void showProductDetails(String upc) {
Product product = inventory.getProduct(upc);
String[] details = product.getDetails();
System.out.println();
System.out.println(String.join("\n", details));
System.out.println();
}
/**
* Displays the current balance, and
* uses a Scanner to get the payment amount.
* @param in Scanner to allow CLI input.
* @return The user's input String.
*/
private String getPayment(Scanner in) {
String amountLabel;
if (currentTransaction.getBalanceDouble() == currentTransaction.getTotalDouble()) {
amountLabel = "\nTotal: $";
} else {
amountLabel = "\nBalance: $";
}
System.out.println(amountLabel + currentTransaction.getBalanceString());
System.out.print("Enter payment: ");
return in.nextLine().trim();
}
/**
* Uses a Scanner to receive payment until payment >= balance.
*/
public void checkOut() {
double payment;
String userInput;
Scanner in = new Scanner(System.in);
while (currentTransaction.isUnpaid()) {
userInput = getPayment(in);
try {
payment = Double.parseDouble(userInput);
} catch (NumberFormatException e) {
System.out.println("Invalid input. Example: enter 1.50 to pay $1.50");
continue;
}
if (payment <= 0.01) {
System.out.println("Invalid input. Must pay >= $0.01");
} else {
currentTransaction.addPayment(payment);
}
}
}
/**
* Prints an itemized receipt, including the total and the change (if any).
*/
public void printReceipt() {
if (currentTransaction.isUnpaid()) {
System.out.println("Items have not been paid for. No receipt available.");
} else {
System.out.println("\n====RECEIPT====");
System.out.println(currentTransaction.getSummary());
}
}
/**
* Begins a new transaction.
*/
public void startNewTransaction() {
currentTransaction = new Transaction();
scanItems();
checkOut();
printReceipt();
}
}
|
package kim.aleksandr.backendless;
import android.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.BackendlessCollection;
import com.backendless.BackendlessUser;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.BackendlessDataQuery;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MakeOrderActivity extends AppCompatActivity {
Date startTime = new Date(), endTime = new Date();
boolean choosingForStart;
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("h:mm a");
Switch switchAllDay;
TextView startDateText, endDateText, startTimeText, endTimeText, setNotification;
Button btnBook;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_order);
switchAllDay = (Switch) findViewById(R.id.switchAllDay);
startDateText = (TextView) findViewById(R.id.dateStartText);
endDateText = (TextView) findViewById(R.id.dateEndText);
startTimeText = (TextView) findViewById(R.id.timeStartText);
endTimeText = (TextView) findViewById(R.id.timeEndText);
setNotification = (TextView) findViewById(R.id.setNotification);
btnBook = (Button) findViewById(R.id.buttonBook);
}
Orders booking;
Orgs myOrg;
Products myProduct;
OrderStates myState;
String whereClause;
BackendlessDataQuery dataQuery;
public void bookItem (View v) {
BackendlessUser thisUser = Backendless.UserService.CurrentUser();
booking = new Orders();
booking.setSingleUser_id(thisUser);
Log.d("Number of users: ", Integer.toString(booking.getUser_id().size()));
Log.d("Users", booking.getUser_id().get(0).getEmail());
booking.setTitle("First test");
booking.setNote("Test note");
whereClause = "name = 'kloop'";
dataQuery = new BackendlessDataQuery();
dataQuery.setWhereClause( whereClause );
Backendless.Persistence.of(Orgs.class).find(dataQuery, new AsyncCallback<BackendlessCollection<Orgs>>() {
public void handleResponse( BackendlessCollection<Orgs> response) {
myOrg = response.getData().get(0);
Log.d("Successful find Orgs", "+");
booking.setSingleOrg_id(myOrg);
Log.d("myOrg", booking.getOrg_id().get(0).getName());
Log.d("myOrg address", booking.getOrg_id().get(0).getAddress());
whereClause = "name = 'Фотоаппарат 44'";
dataQuery = new BackendlessDataQuery();
dataQuery.setWhereClause( whereClause );
Backendless.Persistence.of(Products.class).find(dataQuery, new AsyncCallback<BackendlessCollection<Products>>() {
public void handleResponse( BackendlessCollection<Products> response) {
myProduct = response.getData().get(0);
Log.d("Successful find Product", "+");
booking.setSingleProduct_id(myProduct);
Log.d("myProduct", myProduct.toString());
Log.d("myProduct ", booking.getProduct_id().get(0).getSerial_no());
whereClause = "name = 'завершен'";
dataQuery = new BackendlessDataQuery();
dataQuery.setWhereClause( whereClause );
Backendless.Persistence.of(OrderStates.class).find(dataQuery, new AsyncCallback<BackendlessCollection<OrderStates>>() {
public void handleResponse( BackendlessCollection<OrderStates> response) {
myState = response.getData().get(0);
Log.d("Found OrderStates ", "+");
booking.setSingleState_id(myState);
Log.d("myState", booking.getState_id().get(0).getObjectId());
booking.setStart_time(startTime);
booking.setEnd_time(endTime);
Log.d("Start time", booking.getStartTimeString());
Log.d("End time", booking.getEndTimeString());
if (booking.noConflict()) {
Log.d("before the push", "+");
booking.push();
}
else
Toast.makeText(getApplicationContext(), "This period of time is not available", Toast.LENGTH_SHORT).show();
}
public void handleFault(BackendlessFault fault) {
Log.d("Failed Orgs find", "Error " + fault.getCode() + " "
+ fault.getMessage() + " " + fault.getDetail());
}
});
}
public void handleFault(BackendlessFault fault) {
Log.d("Failed Prod find", "Error " + fault.getCode() + " "
+ fault.getMessage() + " " + fault.getDetail());
}
});
}
public void handleFault(BackendlessFault fault) {
Log.d("Failed Orgs find", "Error " + fault.getCode() + " "
+ fault.getMessage() + " " + fault.getDetail());
}
});
}
public void showStartDatePickerDialog (View v) {
choosingForStart = true;
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "startDatePickerDialog");
}
public void showEndDatePickerDialog (View v) {
choosingForStart = false;
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "endDatePickerDialog");
}
public void showStartTimePickerDialog (View v) {
choosingForStart = true;
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "startTimePickerDialog");
}
public void showEndTimePickerDialog (View v) {
choosingForStart = false;
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "endTimePickerDialog");
}
public void updateDateTime () {
startDateText.setText(dateFormat.format(startTime));
endDateText.setText(dateFormat.format(endTime));
startTimeText.setText(timeFormat.format(startTime));
endTimeText.setText(timeFormat.format(endTime));
setNotification.setText(startTime.toString() + "\n" + endTime.toString());
}
}
|
package com.demo.memento.blog;
import lombok.Data;
/**
* @author: Maniac Wen
* @create: 2020/6/11
* @update: 7:25
* @version: V1.0
* @detail:
**/
@Data
public class Editor {
private String title;
private String content;
private String imgs;
public Editor(String title, String content, String imgs) {
this.title = title;
this.content = content;
this.imgs = imgs;
}
public ArticleMemento saveToMemento(){
ArticleMemento articleMemento = new ArticleMemento(this.title,this.content,this.imgs);
return articleMemento;
}
public void undoFromMemento(ArticleMemento articleMemento){
this.title = articleMemento.getTitle();
this.content = articleMemento.getContent();
this.imgs = articleMemento.getImgs();
}
@Override
public String toString() {
return "Editor{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
", imgs='" + imgs + '\'' +
'}';
}
}
|
package com.cjx.nexwork.fragments.study;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.DatePickerDialog;
import android.content.Context;
import android.net.Uri;
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.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TableRow;
import com.cjx.nexwork.R;
import com.cjx.nexwork.managers.work.WorkDetailCallback;
import com.cjx.nexwork.managers.work.WorkManager;
import com.cjx.nexwork.model.Work;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link FragmentCreateStudy.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FragmentCreateStudy#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentCreateStudy extends Fragment implements View.OnClickListener, CheckBox.OnCheckedChangeListener, WorkDetailCallback {
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
private EditText editPosition;
private EditText editDateStarted;
private EditText editDateEnd;
private CheckBox checkWorking;
private EditText editDescription;
/*DatePickerDialog.OnDateSetListener dateStart = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
startCalendar.set(Calendar.YEAR, year);
startCalendar.set(Calendar.MONTH, monthOfYear);
startCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateStart();
}
};
DatePickerDialog.OnDateSetListener dateEnd = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
endCalendar.set(Calendar.YEAR, year);
endCalendar.set(Calendar.MONTH, monthOfYear);
endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateEnd();
}
};*/
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentCreateStudy() {
// Required empty public constructor
}
// TODO: Rename and change types and number of parameters
public static FragmentCreateStudy newInstance() {
FragmentCreateStudy fragment = new FragmentCreateStudy();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_create_work,container, false);
editPosition = (EditText) view.findViewById(R.id.editPosition);
editDateStarted = (EditText) view.findViewById(R.id.editDateStarted);
editDateEnd = (EditText) view.findViewById(R.id.editDateEnd);
checkWorking = (CheckBox) view.findViewById(R.id.checkWorking);
editDescription = (EditText) view.findViewById(R.id.editDescription);
Button btnAddJob = (Button) view.findViewById(R.id.btn_create_company);
btnAddJob.setOnClickListener(this);
editDateStarted.setFocusable(false);
editDateStarted.setClickable(false);
editDateEnd.setFocusable(false);
editDateEnd.setClickable(false);
editDateStarted.setOnClickListener(this);
editDateEnd.setOnClickListener(this);
checkWorking.setOnCheckedChangeListener(this);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onClick(final View v) {
if(v.getId() == R.id.editPosition){
Log.d("nxw", "position");
}
switch (v.getId())
{
case R.id.btn_create_company:
addJob();
break;
case R.id.editPosition:
Log.d("nxw", "position");
break;
case R.id.editDateStarted:
Log.d("nxw", "start");
new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startCalendar.set(Calendar.YEAR, year);
startCalendar.set(Calendar.MONTH, month);
startCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
EditText editText = (EditText) v;
editText.setText(sdf.format(startCalendar.getTime()));
}
}, startCalendar.get(Calendar.YEAR), startCalendar.get(Calendar.MONTH),
startCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
case R.id.editDateEnd:
Log.d("nxw", "end");
new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
endCalendar.set(Calendar.YEAR, year);
endCalendar.set(Calendar.MONTH, month);
endCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
EditText editText = (EditText) v;
editText.setText(sdf.format(endCalendar.getTime()));
}
}, endCalendar.get(Calendar.YEAR), endCalendar.get(Calendar.MONTH),
endCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
}
}
private void addJob() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
try{
Work work = new Work();
work.setCargo(editPosition.getText().toString());
Date startDate = new Date();
Date endDate = new Date();
if(!checkWorking.isChecked()) {
endDate = dateFormat.parse(editDateEnd.getText().toString());
work.setFechaFin(endDate);
}else work.setActualmente(true);
if(!editDescription.getText().toString().isEmpty()) work.setDescripcionCargo(editDescription.getText().toString());
startDate = dateFormat.parse(editDateStarted.getText().toString());
work.setFechaInicio(startDate);
WorkManager.getInstance().createWork(work, this);
}
catch (Exception e){
e.printStackTrace();
}
/*getActivity()
.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_work, new FragmentListStudy())
.commit();*/
Log.d("nxw", "add job");
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
final TableRow rowEnd = (TableRow) getView().findViewById(R.id.rowEnd);
switch (buttonView.getId()){
case R.id.checkWorking:
if(isChecked){
rowEnd.animate().alpha(0.0f).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
rowEnd.setVisibility(View.GONE);
}
});
}
else {
rowEnd.animate().alpha(1.0f).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
rowEnd.setVisibility(View.VISIBLE);
}
});
}
break;
}
}
@Override
public void onSuccess(Work work) {
Log.d("nxw", work.toString());
getActivity()
.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.swap_in_bottom, R.anim.swap_out_bottom)
.replace(R.id.fragment_work, new FragmentListStudy())
.addToBackStack(null)
.commit();
}
@Override
public void onFailure(Throwable t) {
Log.d("nxw", t.getMessage());
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
|
package demo;
import entity.MarketingUserBehavior;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichSourceFunction;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
/**
* @author douglas
* @create 2021-02-24 21:42
*/
public class Flink04_Project_AppAnalysis_By_Chanel {
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env
.addSource(new AppMarketingDataSource())
.map(behavior-> Tuple2.of(behavior.getChannel()+"_"+behavior.getBehavior(),1L))
.returns(Types.TUPLE(Types.STRING,Types.LONG))
.keyBy(t->t.f0)
.sum(1)
.print();
env.execute();
}
public static class AppMarketingDataSource extends RichSourceFunction<MarketingUserBehavior>{
boolean canRun = true;
Random random =new Random();
List<String> channel=Arrays.asList("huawei","xiaomi","apple","baidu","qq","oppo","vivo");
List<String> behaviors=Arrays.asList("download","install","update","uninstall");
@Override
public void run(SourceContext<MarketingUserBehavior> ctx) throws Exception {
while (canRun){
MarketingUserBehavior marketingUserBehavior = new MarketingUserBehavior(
(long) random.nextInt(1000000),
behaviors.get(random.nextInt(behaviors.size())),
channel.get(random.nextInt(channel.size())),
System.currentTimeMillis()
);
ctx.collect(marketingUserBehavior);
Thread.sleep(2000);
}
}
@Override
public void cancel() {
canRun=false;
}
}
}
|
package by.orion.onlinertasks.di.modules;
import android.support.annotation.NonNull;
import javax.inject.Named;
import javax.inject.Singleton;
import by.orion.onlinertasks.common.network.services.BaseService;
import by.orion.onlinertasks.common.network.services.CredentialsService;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import static by.orion.onlinertasks.di.modules.ApiModule.CREDENTIALS_API;
import static by.orion.onlinertasks.di.modules.ApiModule.TASKS_API;
@Module
public class NetworkServiceModule {
@Singleton
@Provides
@NonNull
BaseService provideBaseService(@NonNull @Named(TASKS_API) Retrofit retrofit) {
return retrofit.create(BaseService.class);
}
@Singleton
@Provides
@NonNull
CredentialsService provideCredentialsService(@NonNull @Named(CREDENTIALS_API) Retrofit retrofit) {
return retrofit.create(CredentialsService.class);
}
}
|
package firstfactor.security.filter;
import com.fasterxml.jackson.databind.ObjectMapper;
import firstfactor.payload.ApiError;
import firstfactor.payload.UserLoginRequest;
import firstfactor.security.authentication.OTPAuthentication;
import firstfactor.security.authentication.UsernamePasswordAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class LoginFilter extends OncePerRequestFilter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
//Extract username/password and OTP
//We should check also the inputstream format and reply accordingly in case of error, for simplicity we don't
UserLoginRequest userLoginRequest = new ObjectMapper()
.readValue(httpServletRequest.getInputStream(), UserLoginRequest.class);
try {
if (userLoginRequest.getOtp() == null) {
authenticationManager.authenticate(
new UsernamePasswordAuthentication(userLoginRequest.getUsername(), userLoginRequest.getPassword()));
// if we reached here the user is validated
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
} else {
// Here we should call the appropriate provider for validating the OTP
authenticationManager.authenticate(
new OTPAuthentication(userLoginRequest.getUsername(), userLoginRequest.getOtp()));
// Here we know for sure that the OTP is valid.
// So we should generate a JWT, for simplicity we don't.
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
}
} catch (AuthenticationException authExc) {
ApiError apiError = new ApiError();
apiError.setErrorResponse(authExc.getMessage());
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
httpServletResponse.setContentType("application/json");
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.getWriter().write(apiError.toString());
}
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
return !request.getServletPath().equals("/login");
}
}
|
/*
* Copyright (C) 2015 grandcentrix GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.grandcentrix.tray.sample;
import net.grandcentrix.tray.TrayAppPreferences;
import net.grandcentrix.tray.migration.SharedPreferencesImport;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by pascalwelsch on 2/7/15.
*/
public class SampleActivity extends Activity implements View.OnClickListener {
public static final String STARTUP_COUNT = "startup_count";
private static final String SHARED_PREF_NAME = "shared_pref";
private static final String SHARED_PREF_KEY = "shared_pref_key";
private static final String TRAY_PREF_KEY = "importedData";
private TrayAppPreferences mAppPrefs;
private ImportTrayPreferences mImportPreference;
private SharedPreferences mSharedPreferences;
@SuppressWarnings("Annotator")
@Override
public void onClick(final View view) {
switch (view.getId()) {
case R.id.reset:
resetAndRestart();
break;
case R.id.write_shared_pref:
writeInSharedPref();
break;
case R.id.import_shared_pref:
importSharedPref();
break;
default:
Toast.makeText(this, "not implemented", Toast.LENGTH_SHORT).show();
break;
}
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
mAppPrefs = new TrayAppPreferences(this);
mImportPreference = new ImportTrayPreferences(this);
mSharedPreferences = getSharedPreferences(SHARED_PREF_NAME,
Context.MODE_MULTI_PROCESS);
int startupCount = mAppPrefs.getInt(STARTUP_COUNT, 0);
if (savedInstanceState == null) {
mAppPrefs.put(STARTUP_COUNT, ++startupCount);
}
final TextView text = (TextView) findViewById(android.R.id.text1);
text.setText(getString(R.string.sample_launched_x_times, startupCount));
final Button resetBtn = (Button) findViewById(R.id.reset);
resetBtn.setOnClickListener(this);
final Button writeSharedPref = (Button) findViewById(R.id.write_shared_pref);
writeSharedPref.setOnClickListener(this);
final Button importInTray = (Button) findViewById(R.id.import_shared_pref);
importInTray.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
updateSharedPrefInfo();
}
private void importSharedPref() {
final SharedPreferencesImport sharedPreferencesImport =
new SharedPreferencesImport(this, SampleActivity.SHARED_PREF_NAME,
SampleActivity.SHARED_PREF_KEY, TRAY_PREF_KEY);
mImportPreference.migrate(sharedPreferencesImport);
updateSharedPrefInfo();
}
/**
* resets the startup count and restarts the activity
*/
private void resetAndRestart() {
mAppPrefs.remove(STARTUP_COUNT);
//restart activity
final Intent intent = new Intent(this, SampleActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void updateSharedPrefInfo() {
final TextView info = (TextView) findViewById(R.id.shared_pref_info);
final String sharedPrefData = mSharedPreferences.getString(SHARED_PREF_KEY, "null");
final String trayData = mImportPreference.getString(TRAY_PREF_KEY, "null");
info.setText(
"SharedPref Data: " + sharedPrefData + "\n"
+ "Tray Data: " + trayData);
}
private void writeInSharedPref() {
final String data = "SOM3 D4T4 " + (System.currentTimeMillis() % 100000);
mSharedPreferences.edit()
.putString(SHARED_PREF_KEY, data)
.apply();
updateSharedPrefInfo();
}
}
|
package service;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Random;
/**
* This will implement functionality needed to have events for the persons generated by register/fill
*/
public class EventGenerator {
private LocationData locationData;
private int[] years = {1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000};
private int[] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
private int[] tens = {40, 50, 60, 70, 80, 90};
public EventGenerator(){
File locations = new File("C:/Users/jacob/IdeaProjects/FamilyMap/fms/json/locations.json");
try (Reader reader = new FileReader(locations)){
Gson gson = new Gson();
locationData = gson.fromJson(reader, LocationData.class);
}
catch (IOException e) {
e.printStackTrace();
}
}
public class Location {
String country;
String city;
float latitude;
float longitude;
public Location(final String country, final String city, final float latitude, final float longitude) {
this.country = country;
this.city = city;
this.latitude = latitude;
this.longitude = longitude;
}
public String getCountry() {
return this.country;
}
public String getCity() {
return this.city;
}
public float getLatitude() {
return this.latitude;
}
public float getLongitude() {
return this.longitude;
}
}
class LocationData {
Location[] data;
}
public Location getLocation(){
return getRandom(locationData.data);
}
private Location getRandom(Location[] array) {
int ran = new Random().nextInt(array.length);
return array[ran];
}
private int getRandomYear(int[] array) {
int ran = new Random().nextInt(array.length);
return array[ran];
}
public int getBirthYear(int generations) {
int ran = new Random().nextInt(years.length);
return (years[ran] - (25 * generations));
}
public int getDeathYear(int birthYear){
int ran = new Random().nextInt(nums.length);
int ranTen = new Random().nextInt(tens.length);
return (birthYear + tens[ranTen] + nums[ran]);
}
public int getMarriageYear(int birthYear) {
int ran = new Random().nextInt(nums.length);
return (birthYear + 18 + nums[ran]);
}
}
|
public class Deadlock {
private String name;
public Deadlock(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void call(Deadlock thread1){
synchronized(this) {
System.out.println(this.name + " first function");
thread1.callBack(this);
}
}
public void callBack(Deadlock thread1){
//synchronized (this) {
System.out.println(thread1.getName() + " second function");
//}
}
}
|
package wsn.b405.console;
import wsn.b405.service.LogStatService;
import wsn.b405.util.BasicSystemInfoUtil;
import wsn.b405.util.JsonStringPrintFormatUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Map;
/**
* Created by @author cdlixu5 on 2017/12/30.
*/
public class Main {
private static LogStatService logStatService = LogStatService.getInstance();
public static void main(String[] args) {
help(System.out);
while(true){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
String argsLine = reader.readLine();
resolveArgs(argsLine);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void resolveArgs(String argsLine){
if(null != argsLine) {
switch (argsLine.trim().toLowerCase()) {
case "exit":
System.exit(0);
break;
case "help":
help(System.out);
break;
case "dy-log list all":
handlerCommand("dy-log list all");
break;
case "sys-info":
handlerCommand("sys-info");
break;
default:
String[] arg = argsLine.split(" ");
if (argsLine.startsWith("dy-log search")) {
if (3 == arg.length && null != arg[2]) {
handlerCommand("dy-log search", arg[2]);
}else {
printHitMsg(System.out,"命令输入参数有误,请按照命令格式输入dy-log search LogName,命令详细信息请用help查看");
}
}
else if(argsLine.startsWith("dy-log page")){
String pageNow = "1";
String pageSize = "15";
if(3 <= arg.length){
pageNow = arg[2];
}if (4 == arg.length){
pageSize = arg[3];
}
handlerCommand("dy-log page",pageNow,pageSize);
}
else if (argsLine.startsWith("dy-log change all")) {
if(4 == arg.length && null != arg[3]){
handlerCommand("dy-log change all",arg[3]);
}else {
printHitMsg(System.out,"命令输入参数有误,请按照命令格式输入dy-log change all level,命令详细信息请用help查看");
}
}
else if (argsLine.startsWith("dy-log change")) {
if(4 == arg.length && null != arg[2] && null != arg[3]) {
handlerCommand("dy-log change", arg[2], arg[3]);
}
else{
printHitMsg(System.out,"命令输入参数有误,请按照命令格式输入dy-log chanage logName level,命令详细信息请用help查看");
}
}
}
}
}
private static void handlerCommand(String command,String ...args){
switch (command){
case "dy-log list all":
print(System.out,logStatService.service("/logList.json"));
break;
case "dy-log search":
print(System.out,logStatService.service("/logList.json?keyWord="+args[0]));
break;
case "dy-log change all":
logStatService.service("/changeLogLevel.json?level="+args[1]+"&logClass="+ args[0]);
print(System.out,logStatService.service("/logList.json"));
break;
case "dy-log change":
logStatService.service("/changeLogLevel.json?level="+args[1]+"&logClass="+ args[0]);
print(System.out,logStatService.service("/logList.json"));
break;
case "sys-info":
print(System.out,BasicSystemInfoUtil.getBasicSystemInfo());
break;
case "dy-log page":
print(System.out, logStatService.service("/logList.json?pageSize=" + args[1] + "&pageNow=" + args[0]));
}
}
private static void print(PrintStream printStream,Object object){
if (object instanceof Map){
((Map)object).entrySet().stream().forEach(E -> {printStream.print(E );printStream.println();});
}else if(object instanceof String){
printStream.print(JsonStringPrintFormatUtil.formatJson((String) object));
}else {
printStream.print(object);
}
}
private static void help(PrintStream printStream){
printStream.print("动态日志帮助工具使用文档,指令格式如下:\n");
printStream.print("dy-log -command args\n");
printStream.print("eg: dy-log list all列出所有的日志\n");
printStream.print(" help 显示帮助文档\n");
printStream.print(" dy-log page pageNumber [pageSize = 15] 分页输出日志对象\n");
printStream.print(" dy-log search Key 查找日志对象对象,精确匹配【慎重使用】\n");
printStream.print(" dy-log change logName level修改指定日志对象的级别[DEBUG,INFO,WARN,ERROR]\n");
printStream.print(" dy-log change all level修改所有日志对象的级别[DEBUG,INFO,WARN,ERROR]\n");
printStream.print(" sys-info 显示操作系统基本信息\n");
printStream.print(" exit 退出\n");
}
/**
* 输入提示信息
* @param printStream
* @param msg
*/
private static void printHitMsg(PrintStream printStream,String msg){
printStream.print(msg);
}
}
|
/**
* Write a description of class Main here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Main
{
public static void main(String[] args)
{
// the array
String array[] ={"AA", "BB", "CC", "DD", "EE", "FF"};
// what you are searching for
String search = "EE";
// binary searching the search
int searchIndex = BinaryStringSearch.binarySearch(array,search);
System.out.println(searchIndex != -1 ? array[searchIndex]+ " - Index is "+searchIndex : "Not found");
}
}
|
package com.yidatec.weixin.util;
import java.net.URLEncoder;
import java.security.Key;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
public class TripleDES {
//定义 加密算法,可用 DES,DESede,Blowfish
private static final String Algorithm = "DESede";
public static final byte[] keyBytes = {
0x21, 0x22, 0x4F, 0x38, (byte)0x78, 0x10, 0x41, 0x28,
0x25, 0x15, 0x69, 0x51, (byte)0xCB, (byte)0xDD, 0x55,
0x56, 0x78, 0x29, 0x74, (byte)0x96, 0x31, 0x40, 0x37, (byte)0xE2}; //24字节的密钥
/**
* @param keybyte 为加密密钥,长度为24字节
* @param src 为被加密的数据缓冲区(源)
* @return
*/
public static byte[] encryptMode(byte[] keybyte, byte[] src) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
KeySpec keySpec = new DESedeKeySpec(keybyte);
Key secretKey = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(src);
// //生成密钥
// SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
// //加密
// Cipher c1 = Cipher.getInstance("DESede/ECB/PKCS5Padding");
// c1.init(Cipher.ENCRYPT_MODE, deskey);
// return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
/**
* @param keybyte 为加密密钥,长度为24字节
* @param src 为加密后的缓冲区
* @return
*/
public static byte[] decryptMode(byte[] keybyte, byte[] src) {
try {
Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
KeySpec keySpec = new DESedeKeySpec(keybyte);
Key secretKey = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(src);
//生成密钥
// SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
// //解密
// Cipher c1 = Cipher.getInstance(Algorithm);
// c1.init(Cipher.DECRYPT_MODE, deskey);
// return c1.doFinal(src);
} catch (java.security.NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (javax.crypto.NoSuchPaddingException e2) {
e2.printStackTrace();
} catch (java.lang.Exception e3) {
e3.printStackTrace();
}
return null;
}
/**
* 转换成十六进制字符串
* @param b
* @return
*/
public static String byte2hex(byte[] b) {
String hs="";
String stmp="";
for (int n=0;n<b.length;n++) {
stmp=(java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length()==1) hs=hs+"0"+stmp;
else hs=hs+stmp;
if (n<b.length-1) hs=hs+":";
}
return hs.toUpperCase();
}
public static void main(String[] args) {
try {
String st = "oEVwAD7Dj6ux/la7P94Frnp/Z7+B0F1r4tFrJQsl97JWB8UkQ572oSoisKEdvEQHWWVuJWrh1PtMENzl/ZM71J5UZR/6hRsAWKDA8GDzmMQhwVa3vW9FUgZe2noZ/qU+Pq4Ber3Vu7hCfWFU2b7jPiFVosbNzqTFnpFV7oRA+QLO/kc2MT1gZRYGo/Fu2sl0uDQDCyLPPlqHNzrJu90FZjw6xAkWsKrW4Qjqx0IPx5E3mZ9J+nU/4rLLG/Subay6jaaQgv5ouK1YoMDwYPOYxHNndSqJC4ZVHN+vGM85E5LeVbY+QcKRp9hCwuGU9Vn7GXcPWxnmERjrvsg8F1yXIIVfo7fe4bLCHOHn8+Mx9ELpY5vKxknojdJKE097zKXfghX/SXoRiDFOWdnEYtAFO/EeBmJKAkkbbQoBobs/PTnYscPlB1ho/+0npGbfZsjbjJFcErcbfd2QPyFImc0vXzSEJA9Rjw9E/1fx659HTulpipkj1/7ayERv+4R4AHGtMoCGU78UmgGonEG84nGp+hqqfjZ+LE+zgo2u6BAWg8gWSsU1ihK0jr+mY+qEZIJn0lf7QekM9rt2AImZxdxHw2PLxKt4qjS6SclRYm9BZ7h6M83GCoWuDD9poc4QluTBXl/hhv0Jmn1vj9ffEDnhfejU0O6vLpJysUNWad3H4xFQk+wqIfJeFnImXIWcuGcQImRJcOuEu4/81ZhWSICFPnl+o0lThwmCfJjwNzb0CkL+YU5bPKABAIVfo7fe4bLCiMDX56fKk6ccfZON0ikjlnOwuaYjyQWL9TdYCG0b9g416imKT/qbqaQLVM4EODNSh7bYHRpCZ2xpAMyZmuzpmhOu7czYlGcFnTHx9q8yFq29cMYVIl/leb9l6IlCyNsMV9k/0A6xZQ1zN2+T3MnQW5Bc7do86UKAvOM3gkGgvkjUbCCXUdWaZ9fp7GQ5X4XsDluYnh5M7XClcWEAI0i/AdhCwuGU9Vn7Li2R0i8+cS948gtZQzI+6o6hKQmQmFNx2XGvyLtT1rZLIdYCqvHS4p/4BsPYIR+Xvoj6LRibzbZCM1Rse8qImb+mY+qEZIJnC8eyVj9uNYjC0VQ7VkD5PMeGU6wwRIYRCRF1h9G99fc=";
System.out.println(URLEncoder.encode(st, "UTF-8"));
String str = "hello world!中国";
String key = "123456789012345678901234";
byte[] raw = encryptMode(key.getBytes(), str.getBytes("UTF-8"));
System.out.println(Base64.encodeString(raw));
byte[] dec = decryptMode(key.getBytes(), Base64.decode("SdHQCpbVRzlzE65M4lMYPAkdwf/q9mTq"));
System.out.println(new String(dec, "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
//添加新安全算法,如果用JCE就要把它添加进去
// Security.addProvider(new com.sun.crypto.provider.SunJCE());
// String szSrc = "This is a 3DES test. 测试";
//
// System.out.println("加密前的字符串:" + szSrc);
//
// byte[] encoded = encryptMode(TripleDES.keyBytes, szSrc.getBytes());
// System.out.println("加密后的字符串:" + new String(encoded));
//
// byte[] srcBytes = decryptMode(TripleDES.keyBytes, encoded);
// System.out.println("解密后的字符串:" + (new String(srcBytes)));
}
}
|
package ldap.password;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class PasswordController {
@GetMapping("/password")
public String greetingForm(Model model) {
model.addAttribute("password", new Password());
return "password";
}
@PostMapping("/password")
public String greetingSubmit(@ModelAttribute Password password) {
Process process = new Process(password);
return "result";
}
}
|
package com.deepakm.archaius.source;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.netflix.config.*;
import java.util.Map;
import java.util.Random;
/**
* Created by dmarathe on 4/29/15.
*/
public class InMemoryRandomConfigSource implements PolledConfigurationSource {
private final Map<String, Object> source;
private final Random random;
private final int LIMIT = 10;
public InMemoryRandomConfigSource() {
source = Maps.newHashMap();
random = new Random();
}
public PollResult poll(boolean b, Object o) throws Exception {
ImmutableMap<String, Object> addMap = null;
ImmutableMap<String, Object> changeMap = null, deleteMap = null;
if (b == true) {
addMap = ImmutableMap.of(String.valueOf(random.nextInt(100)), (Object) Long.valueOf(random.nextInt()));
source.putAll(addMap);
} else {
if (source.keySet().size() > 1) {
//change
int index = random.nextInt(source.keySet().size());
String updateKey = (String) source.keySet().toArray()[index];
source.put(updateKey, random.nextInt());
changeMap = ImmutableMap.of(updateKey, (Object) source.get(updateKey));
//delete
String deleteKey = (String) source.keySet().toArray()[random.nextInt(source.keySet().size())];
Object value = source.remove(deleteKey);
deleteMap = ImmutableMap.of(deleteKey, value);
//add
String addKey = String.valueOf(random.nextInt(100));
Object addValue = String.valueOf(random.nextInt());
source.put(addKey, addValue);
addMap = ImmutableMap.of(addKey, addValue);
}
}
PollResult result = PollResult.createIncremental(addMap, changeMap, deleteMap, o);
return result;
}
}
|
package com.webproject.compro.web.vos;
import java.util.ArrayList;
public class GetBasketItemVo {
private final int startPage;
private final int endPage;
private final int requestPage;
private final ArrayList<BasketItemVo> basketItemVos;
public GetBasketItemVo(int startPage, int endPage, int requestPage, ArrayList<BasketItemVo> basketItemVos) {
this.startPage = startPage;
this.endPage = endPage;
this.requestPage = requestPage;
this.basketItemVos = basketItemVos;
}
public int getStartPage() {
return startPage;
}
public int getEndPage() {
return endPage;
}
public int getRequestPage() {
return requestPage;
}
public ArrayList<BasketItemVo> getBasketItemVos() {
return basketItemVos;
}
}
|
import java.util.Scanner;
import static org.apache.commons.lang3.StringUtils.isNumeric;
public class Menu {
static Scanner scanner = new Scanner(System.in);
static String numericOrText;
static void menu() {
System.out.println("1. Wyświetl liste ksiązek");
System.out.println("2. Wyjdź");
numericOrText = scanner.nextLine();
if (isNumeric(numericOrText)) {
userChoice();
} else {
System.out.println("Wybierz liczbę 1 lub 2");
menu();
}
}
static void userChoice() {
int option = Integer.parseInt(numericOrText);
while (option != 2) {
switch (option) {
case 1:
BookList.readBookList();
break;
case 2:
break;
default:
System.out.println("wybierz 1 lub 2");
menu();
break;
}
}
}
}
|
package demoOn11August2016_Part1;
public class Address {
String streetname;
String cityname;
String statename;
String countryname;
int zipcode;
public Address(String streetname, String cityname, String statename, String countryname, int zipcode) {
super();
this.streetname = streetname;
this.cityname = cityname;
this.statename= statename;
this.countryname = countryname;
this.zipcode = zipcode;
}
public void print() {
// TODO Auto-generated method stub
System.out.println("Street name:" +streetname);
System.out.println("City Name:"+cityname);
System.out.println("statename:" +statename);
System.out.println("Country Name:"+countryname);
System.out.println("Post code:"+zipcode);
}
}
|
package com.jalsalabs.ticklemyphonefull;
import android.app.Activity;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
public class PlaySDCardFile extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onResume() {
super.onResume();
TML_Library.Debug("***********************I AM INSIDE Play file************************");
String FileName = TML_Library.GetAfter1Token(TML_Library.GetParameter("MESSAGE_BODY")).trim();
TML_Library.Debug("File Original File:" + FileName);
String LS_SenderPhone = TML_Library.GetParameter("ORIGINAL_ADDRESS");
if (FileName.startsWith("[")) {
FileName = FileName.substring(1);
}
TML_Library.Debug("First cut File:" + FileName);
if (FileName.endsWith("]")) {
FileName = FileName.substring(1, FileName.length() - 1);
}
TML_Library.Debug("Second cut File:" + FileName);
File file = new File(FileName);
if (!file.exists()) {
TML_Library.Debug("Failure : File doesn't exist [" + FileName + "]");
TML_Library.sendSMSBig(this, LS_SenderPhone, new StringBuilder(String.valueOf("File " + FileName + " Does not exists. Unable Play" + "\n")).append("\n").append(getString(R.string.app_name)).toString());
finish();
}
if (file.isDirectory()) {
TML_Library.Debug("Failure : is a Directory [" + FileName + "]");
TML_Library.sendSMSBig(this, LS_SenderPhone, new StringBuilder(String.valueOf("File " + FileName + " is a Directory. Unable play " + "\n")).append("\n").append(getString(R.string.app_name)).toString());
finish();
}
if (file.exists()) {
try {
TML_Library.PlayFileFromSD(this, FileName);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e2) {
e2.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
} else {
TML_Library.Debug("Failure : File doesn't exist" + FileName);
}
finish();
}
}
|
package io.jee.alaska.sso.ticket.redis;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import io.jee.alaska.sso.TicketService;
import io.jee.alaska.sso.TicketVerify;
@Service
public class RedisTicketService implements TicketService {
protected final Log logger = LogFactory.getLog(getClass());
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public String addTicket(String username) {
String key = UUID.randomUUID().toString();
stringRedisTemplate.boundValueOps(key).set(username, 1, TimeUnit.MINUTES);
return key;
}
@Override
public TicketVerify verifyTicket(String ticket) {
String username = stringRedisTemplate.boundValueOps(ticket).get();
TicketVerify ticketVerify = new TicketVerify();
if(StringUtils.hasLength(username)){
ticketVerify.setSuccess(true);
ticketVerify.setUsername(username);
stringRedisTemplate.delete(ticket);
}else{
logger.warn("TK验证失败:"+ticket);
ticketVerify.setSuccess(false);
}
return ticketVerify;
}
}
|
package com.pro.dong.product.model.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.pro.dong.board.model.vo.Attachment;
import com.pro.dong.member.model.vo.Member;
import com.pro.dong.product.model.vo.Category;
import com.pro.dong.product.model.vo.Like;
import com.pro.dong.product.model.vo.OrderList;
import com.pro.dong.product.model.vo.Product;
import com.pro.dong.product.model.vo.ProductAttachment;
import com.pro.dong.product.model.vo.ProductComment;
import com.pro.dong.shop.model.vo.Shop;
@Repository
public class ProductDAOImpl implements ProductDAO{
@Autowired
SqlSessionTemplate sst;
//민호 시작 ==========================
@Override
public int submitPurchase(OrderList orderList) {
return sst.insert("product.insertOrderList", orderList);
}
@Override
public int updateMemberPoint(OrderList orderList) {
return sst.insert("product.updateMemberPoint", orderList);
}
@Override
public Member selectOneMember(String memberId) {
return sst.selectOne("product.selectOneMember",memberId);
}
//==========================민호 끝
//하진 시작 ==========================
@Override
public List<Map<String, String>> productStatus(Map<String, String> param) {
return sst.selectList("product.productStatus",param);
}
@Override
public int deleteProduct(int productNo) {
return sst.delete("product.deleteProduct",productNo);
}
//========================== 하진 끝
//근호 시작 ==========================
//========================== 근호 끝
@Override
public int incount(int productNo) {
return sst.update("product.updateIncount",productNo);
}
//지은 시작 ==========================
@Override
public Member selectShopMember(int productNo) {
return sst.selectOne("product.selectShopMember", productNo);
}
//========================== 지은 끝
//예찬 시작 ==========================
@Override
public List<Category> selectCategory(Category category) {
return sst.selectList("product.selectCategory1", category);
}
@Override
public Shop selectOneShop(String memberId) {
return sst.selectOne("product.selectOneShop", memberId);
}
@Override
public int insertProduct(Product product) {
return sst.insert("product.insertProduct", product);
}
@Override
public int insertAttachment(ProductAttachment pa) {
return sst.insert("product.insertAttachment", pa);
}
@Override
public List<Map<String, String>> selectProductListTop10(String categoryId) {
RowBounds rowBounds = new RowBounds(0,10);
return sst.selectList("product.selectProductListTop10", categoryId, rowBounds);
}
@Override
public List<Map<String, String>> selectProduct(int cPage, int numPerPage, Map<String, String> param) {
RowBounds rowBounds = new RowBounds((cPage-1)*numPerPage, numPerPage);
return sst.selectList("product.selectProduct", param, rowBounds);
}
@Override
public int countProduct(Map<String, String> param) {
return sst.selectOne("product.countProduct", param);
}
@Override
public Product selectOneProduct(int productNo) {
return sst.selectOne("product.selectOneProduct", productNo);
}
@Override
public List<ProductAttachment> selectAttachment(int productNo) {
return sst.selectList("product.selectAttachment", productNo);
}
@Override
public int countLike(Like like) {
return sst.selectOne("product.countLike2", like);
}
@Override
public int insertLike(Like like) {
return sst.insert("product.insertLike", like);
}
@Override
public int deleteLike(Like like) {
return sst.delete("product.deleteLike", like);
}
@Override
public int insertStatus(Product product) {
return sst.insert("product.insertStatus", product);
}
@Override
public List<Map<String, String>> selectAd(Member member) {
RowBounds rowBounds = new RowBounds(0, 5);
return sst.selectList("product.selectAd", member,rowBounds);
}
@Override
public int insertAttachment(Map<String, String> param) {
return sst.insert("product.insertAttachmentMap", param);
}
@Override
public int updateAttachment(Map<String, String> param) {
return sst.update("product.updateAttachment", param);
}
@Override
public int deleteAttachment(Map<String, String> param) {
return sst.delete("product.deleteAttachment", param);
}
@Override
public int deleteAttachment(String fileName) {
return sst.delete("product.deleteAttachment1", fileName);
}
@Override
public List<Map<String, String>> autocomplete(Map<String, String> param) {
return sst.selectList("product.autocomplete", param);
}
@Override
public List<Map<String, String>> autocompleteShop(Map<String, String> param) {
return sst.selectList("product.autocompleteShop", param);
}
//========================== 예찬 끝
//주영 시작 ==========================
@Override
public List<Map<String, String>> loadProductReportCategory() {
return sst.selectList("product.loadProductReportCategory");
}
@Override
public int insertProductReport(Map<String, String> param) {
return sst.insert("product.insertProductReport", param);
}
@Override
public List<Map<String, String>> selectProductByProductNo(int productNo) {
return sst.selectList("product.selectProductByProductNo", productNo);
}
@Override
public int delImg(String delImgName) {
return sst.delete("product.delImg", delImgName);
}
@Override
public int deleteOldImgName(Map<String, String> param) {
return sst.delete("product.deleteOldImgName", param);
}
@Override
public int insertNewImg(Map<String, String> param) {
return sst.insert("product.insertNewImg", param);
}
@Override
public int productUpdateEnd(Map<String, String> param) {
return sst.update("product.productUpdateEnd", param);
}
@Override
public List<Map<String, String>> selectProductCategory(int productNo) {
return sst.selectList("product.selectProductCategory", productNo);
}
@Override
public List<Category> selectCategoryRef(String categoryRef) {
return sst.selectList("product.selectCategoryRef", categoryRef);
}
//========================== 주영 끝
//현규 시작 ==========================
@Override
public int insertProductComment(ProductComment pc) {
return sst.insert("product.insertProductComment",pc);
}
@Override
public List<Map<String, String>> selectProductCommentList(int productNo, int cPage, int numPerPage) {
RowBounds rowBounds = new RowBounds((cPage-1)*numPerPage,numPerPage);
return sst.selectList("product.selectProductCommentList", productNo, rowBounds);
}
@Override
public int deleteLevel1(int commentNo) {
return sst.delete("product.deleteLevel1",commentNo);
}
@Override
public int countComment(int boardNo) {
return sst.selectOne("product.countComment",boardNo);
}
@Override
public int deleteLevel2(int commentNo) {
return sst.delete("product.deleteLevel2",commentNo);
}
//========================== 현규 끝
}
|
package demos.okan.earthquakes.repository.api;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import demos.okan.earthquakes.repository.model.Earthquake;
import demos.okan.earthquakes.repository.model.Earthquakes;
import demos.okan.earthquakes.repository.model.NetworkState;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
@Singleton
public class EarthquakeApiRepository {
private static final String TAG = EarthquakeApiRepository.class.getName();
/* Service Interface */
private EarthquakeApiService earthquakeApiService;
/* Live Data for Earthquakes */
private MutableLiveData<List<Earthquake>> earthquakesLiveData;
/* Live Data for Network State */
private MutableLiveData<NetworkState> networkStateLiveData;
/* Disposable for Sequential Network Calls */
private final CompositeDisposable disposables = new CompositeDisposable();
@Inject
public EarthquakeApiRepository(EarthquakeApiService earthquakeApiService) {
this.earthquakeApiService = earthquakeApiService;
earthquakesLiveData = new MutableLiveData<>();
networkStateLiveData = new MutableLiveData<>();
/* Start Loading Data when Repository Created */
retrieveEarthquakes();
}
/**
* Called when we need to clean up the disposables.
*/
public void clear() {
disposables.clear();
}
public LiveData<List<Earthquake>> getEarthquakes() {
return earthquakesLiveData;
}
public LiveData<NetworkState> getNetworkState() {
return networkStateLiveData;
}
/**
* Loads Earthquakes from API.
*/
public void retrieveEarthquakes() {
/* Post NetworkState as Loading */
networkStateLiveData.postValue(NetworkState.LOADING);
/* Retrieves the Earthquakes from API */
earthquakeApiService.getEarthquakes().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Earthquakes>() {
@Override
public void onSubscribe(Disposable d) {
/* Add to Disposables so we can clear later on */
disposables.add(d);
}
@Override
public void onNext(Earthquakes earthquakes) {
/* Post the Results to LiveData */
earthquakesLiveData.setValue(earthquakes.getEarthquakes());
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "Error retrieving earthquakes : " + e.getMessage());
/* Update NetworkState as FAILED */
networkStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, e.getMessage()));
}
@Override
public void onComplete() {
Log.d(TAG, "Earthquakes Retrieved");
networkStateLiveData.postValue(NetworkState.LOADED);
/* Once We are done with Loading Data, Clean Disposables */
disposables.clear();
}
});
}
}
|
import java.util.Scanner;
class Program {
public static int Average(int n, int m ) {
Scanner scanner = new Scanner(System.in); //?input array in different function?
int a[][] = new int[n][m];
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = scanner.nextInt();
sum +=a[i][j];
}
}
return sum / (n * m);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int x = scanner.nextInt();
int y = scanner.nextInt();
System.out.println(Average(x, y));
}
}
|
package com.pwq.MQ;
/**
* @Author:WenqiangPu
* @Description
* @Date:Created in 17:55 2017/8/28
* @Modified By:
*/
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Send {
private final static String QUEUE_NAME = "hello1";
public static void main(String[] args) {
try{
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message = "hello world";
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println("[x] sent"+message+"");
channel.close();
connection.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
|
package com.impetus.atmosphere.broadcast;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The Class BroadcasterServlet. This manages PublisherThread's life cycle.
*/
public class BroadcasterServlet extends HttpServlet {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The PublisherThread instance. */
private PublisherThread p;
/* (non-Javadoc)
* @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
p = new PublisherThread(1000);
p.start();
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException {
String millisec = request.getParameter("millisec");
long longMillisec = 1000;
try
{
longMillisec = Long.parseLong(millisec);
}catch(Exception e)
{
e.printStackTrace();
}
p.run = false;
p = new PublisherThread(longMillisec);
p.start();
}
}
|
package com.android.cartloading.adapters;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.android.cartloading.R;
import com.android.cartloading.activities.BaseActivity;
import com.android.cartloading.activities.ILoadCartFinishedListener;
import com.android.cartloading.application.CartApplication;
import com.android.cartloading.models.CartProduct;
import com.android.cartloading.utils.Utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by Toader on 6/6/2015.
*/
public class CartProductAdapter extends GenericAdapter<CartProduct> implements Filterable {
private static final String TAG = CartProductFilter.class.getSimpleName();
protected boolean isFiltering = false;
private CartProductFilter cartProductFilter;
private String oldQuery = "";
private List<ILoadCartFinishedListener> listeners = new ArrayList<>();
public CartProductAdapter(Context context, List<CartProduct> objects) {
super(context, objects);
}
protected CartProductViewHolder createViewHolder(View rowView) {
CartProductViewHolder holder = new CartProductViewHolder();
holder.title = (TextView) rowView.findViewById(R.id.tv_title);
rowView.setTag(holder);
return holder;
}
@Override
protected RowView<CartProduct> createRowView(CartProduct object) {
return new RowView<CartProduct>(object);
}
protected ViewHolder getViewHolder(View rowView) {
if (rowView != null) {
return (ViewHolder) rowView.getTag();
}
return null;
}
@Override
protected void setClickListeners(final View rowView, final RowView<CartProduct> cartRowView) {
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getContext() instanceof Activity) {
if (cartRowView != null) {
((BaseActivity) getContext()).showCartDetailsProduct(cartRowView.getObject());
}
}
}
});
}
@Override
protected void updateView(RowView<CartProduct> convertView, ViewHolder holder) {
CartProductViewHolder productViewHolder = (CartProductViewHolder) holder;
if (convertView != null && productViewHolder != null) {
productViewHolder.title.setText(convertView.getObject().getName());
}
}
public void filter(final String query) {
synchronized (rowViews) {
getFilter().filter(query);
}
}
@Override
protected int getResource() {
return R.layout.list_entry;
}
@Override
public Filter getFilter() {
if (cartProductFilter == null) {
cartProductFilter = new CartProductFilter();
}
return cartProductFilter;
}
@Override
public boolean isFiltering() {
return isFiltering;
}
public void registerListener(final ILoadCartFinishedListener listener) {
synchronized (listeners) {
if (listener != null && !listeners.contains(listener)) {
listeners.add(listener);
}
}
}
protected void notifyFilteringStarted() {
synchronized (listeners) {
for (ILoadCartFinishedListener listener : listeners) {
listener.startProgressLoading();
}
}
}
protected void notifyFilteringDone() {
synchronized (listeners) {
for (ILoadCartFinishedListener listener : listeners) {
listener.stopProgressLoading();
}
}
}
public void unregister(final ILoadCartFinishedListener listener) {
synchronized (listeners) {
if (listener != null && listeners.contains(listener)) {
Iterator<ILoadCartFinishedListener> it = listeners.iterator();
while (it.hasNext()) {
ILoadCartFinishedListener mListener = it.next();
if (mListener.equals(listener)) {
it.remove();
}
}
}
}
}
protected static class CartProductViewHolder extends ViewHolder {
public TextView title;
}
/**
* Custom filter for friend list
* Filter content in friend list according to the search text
*/
private class CartProductFilter extends Filter {
protected Object lock = new Object();
@Override
protected FilterResults performFiltering(CharSequence constraint) {
Log.d(TAG, "filtering");
synchronized (lock) {
FilterResults filterResults = new FilterResults();
notifyFilteringStarted();
Log.d(TAG, "query: " + constraint);
isFiltering = true;
String query = Utils.trimEnd(constraint.toString());
List<CartProduct> cartList = new ArrayList<>();
if (query != null && query.length() > 0) {
List<CartProduct> tempList = new ArrayList<CartProduct>();
if (query.length() < oldQuery.length() || getObjects() == null || getObjects().isEmpty()) {
cartList = CartApplication.getInstance().getDataProvider().getCarts();
} else {
cartList = getObjects();
}
oldQuery = query;
for (CartProduct product : cartList) {
String words = product.getName().toLowerCase();
if (words != null && words.contains(query)) {
String[] allWordsFromQuery = query.split(" ");
if (allWordsFromQuery.length > 1) {
if (words.startsWith(allWordsFromQuery[0])) {
tempList.add(product);
}
} else if (allWordsFromQuery.length == 1) {
if (words.contains(allWordsFromQuery[0])) {
tempList.add(product);
}
}
}
}
Log.d(TAG, "loading: " + tempList.size());
filterResults.count = tempList.size();
filterResults.values = tempList;
} else {
clearAll();
filterResults.count = 0;
filterResults.values = new ArrayList<>();
}
return filterResults;
}
}
/**
* Notify about filtered list to ui
*
* @param constraint text
* @param results filtered result
*/
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, final FilterResults results) {
publishResultsInternal(results);
}
//passwallet
private void publishResultsInternal(FilterResults results) {
Log.d(TAG, "publishing the results");
if (results == null || results.count == 0) {
Log.d(TAG, "publishing the results. empty list." + results);
clearAll();
notifyDataSetInvalidatedOnUiThread();
} else {
Log.d(TAG, "clear all");
clearAll();
notifyDataSetInvalidatedOnUiThread();
Log.d(TAG, "clear all end");
List<CartProduct> products = new ArrayList<>();
if (results.values instanceof List) {
products = (List<CartProduct>) results.values;
}
if (products != null && !products.isEmpty()) {
Log.d(TAG, "add all the products start: " + products.size());
addAll(products);
}
Log.d(TAG, "add all finished:" + products);
}
isFiltering = false;
Log.d(TAG, "notify loading finished from publish results");
notifyFilteringDone();
}
}
}
|
package com.application.ui.activity;
import java.io.File;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.application.beans.MotherHeader;
import com.application.ui.adapter.MotherPagerAdapter;
import com.application.ui.calligraphy.CalligraphyContextWrapper;
import com.application.ui.fragment.IActivityCommunicator;
import com.application.ui.fragment.IFragmentCommunicator;
import com.application.ui.materialdialog.MaterialDialog;
import com.application.ui.service.SyncService;
import com.application.ui.showcaseview.MaterialShowcaseView;
import com.application.ui.view.CircleImageView;
import com.application.ui.view.DrawerArrowDrawable;
import com.application.ui.view.MobcastProgressDialog;
import com.application.ui.view.ScrimInsetsFrameLayout;
import com.application.ui.view.SlidingTabLayout;
import com.application.utils.AndroidUtilities;
import com.application.utils.AppConstants;
import com.application.utils.ApplicationLoader;
import com.application.utils.BuildVars;
import com.application.utils.CheckVersionUpdateAsyncTask;
import com.application.utils.CheckVersionUpdateAsyncTask.OnPostExecuteListener;
import com.application.utils.FileLog;
import com.application.utils.JSONRequestBuilder;
import com.application.utils.NotificationsController;
import com.application.utils.ObservableScrollViewCallbacks;
import com.application.utils.RestClient;
import com.application.utils.RetroFitClient;
import com.application.utils.ScrollState;
import com.application.utils.ScrollUtils;
import com.application.utils.Scrollable;
import com.application.utils.Style;
import com.application.utils.ThemeUtils;
import com.application.utils.Utilities;
import com.apprater.AppRater;
import com.google.analytics.tracking.android.EasyTracker;
import com.mobcast.R;
import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.permission.OnPermissionCallback;
import com.permission.PermissionHelper;
import com.squareup.okhttp.OkHttpClient;
/**
*
* @author Vikalp Patel(VikalpPatelCE)
*
*/
@SuppressLint("InlinedApi")
public class MotherActivity extends BaseActivity implements ObservableScrollViewCallbacks,IActivityCommunicator, OnPermissionCallback {
public static final String SLIDINGTABACTION = "com.application.ui.activity.MotherActivity";
/*
* Drawer
*/
private ScrimInsetsFrameLayout mScrimInsetsFrameLayout;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private FrameLayout mDrawerProfileBgLayout;
private CircleImageView mDrawerProfileIv;
private ImageView mDrawerProfileCoverIv;
private AppCompatTextView mDrawerUserNameTv;
private AppCompatTextView mDrawerUserEmailTv;
private AppCompatTextView mDrawerSyncTv;
private ImageView mDrawerSyncIv;
private LinearLayout mDrawerSyncLayout;
private DrawerArrowDrawable drawerArrowDrawable;
private DrawerArrayAdapter mDrawerAdapter;
private float offset;
private boolean flipped;
private Resources mResources;
private RotateAnimation animSyncDrawer;
private Toolbar mToolBar;
private View mHeaderView;
private View mToolbarView;
private View mMenuAwardView;
private View mMenuBirthdayView;
private View mMenuEventView;
private View mMenuSearchView;
private FrameLayout mCroutonViewGroup;
private SlidingTabLayout mSlidingTabLayout;
private ViewPager mPager;
private int mBaseTranslationY;
private MotherPagerAdapter mPagerAdapter;
private ArrayList<MotherHeader> mArrayListMotherHeader;
public IFragmentCommunicator mFragmentCommunicator;
private ImageLoader mImageLoader;
private int whichTheme = 0;
private static final String TAG = MotherActivity.class.getSimpleName();
private PermissionHelper mPermissionHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
setSecurity();
initToolBar();
initUi();
checkPermissionModel();
setSlidingTabPagerAdapter();
setUiListener();
propagateToolbarState(toolbarIsShown());
setDrawerLayout();
applyTheme();
getIntentData();
apiCheckVersionUpdate();
showCaseView();
whichTheme = ApplicationLoader.getPreferences().getAppTheme();
showAppRate();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(mBroadCastReceiver);
unregisterReceiver(mSyncBroadCastReceiver);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(mBroadCastReceiver, new IntentFilter(NotificationsController.BROADCAST_ACTION));
registerReceiver(mSyncBroadCastReceiver, new IntentFilter(SyncService.BROADCAST_ACTION));
notifySlidingTabLayoutChange();
supportInvalidateOptionsMenu();
Utilities.showBadgeNotification(MotherActivity.this);
checkAppVersionOnResume();
checkMobcastForNewDataAvail();
}
@SuppressLint("NewApi")
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_mother, menu);
MenuItem menuItemEvent = menu.findItem(R.id.action_event);
MenuItem menuItemAward = menu.findItem(R.id.action_award);
MenuItem menuItemBirthday = menu.findItem(R.id.action_birthday);
try{
if(Utilities.getUnreadOfEvent(MotherActivity.this) != 0){
menuItemEvent.setIcon(buildCounterDrawableWithPNG(AppConstants.TYPE.EVENT, whichTheme));
}
if(Utilities.getUnreadOfAward(MotherActivity.this) != 0){
menuItemAward.setIcon(buildCounterDrawableWithPNG(AppConstants.TYPE.AWARD, whichTheme));
}
if(Utilities.getUnreadOfBirthday(MotherActivity.this) != 0){
menuItemBirthday.setIcon(buildCounterDrawableWithPNG(AppConstants.TYPE.BIRTHDAY, whichTheme));
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
menuItemEvent.setIcon(buildCounterDrawable(Utilities.getUnreadOfEvent(MotherActivity.this),R.drawable.ic_toolbar_event));
menuItemAward.setIcon(buildCounterDrawable(Utilities.getUnreadOfAward(MotherActivity.this),R.drawable.ic_toolbar_award));
menuItemBirthday.setIcon(buildCounterDrawable(Utilities.getUnreadOfBirthday(MotherActivity.this),R.drawable.ic_toolbar_birthday));
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_search:
Intent mIntentSearch = new Intent(MotherActivity.this, SearchActivity.class);
switch(mPager.getCurrentItem()){
case 0:
mIntentSearch.putExtra(AppConstants.INTENTCONSTANTS.CATEGORY, AppConstants.INTENTCONSTANTS.MOBCAST);
break;
/*case 2:
mIntentSearch.putExtra(AppConstants.INTENTCONSTANTS.CATEGORY, AppConstants.INTENTCONSTANTS.CHAT);
break;*/
case 1:
mIntentSearch.putExtra(AppConstants.INTENTCONSTANTS.CATEGORY, AppConstants.INTENTCONSTANTS.TRAINING);
break;
}
startActivity(mIntentSearch);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
return true;
case R.id.action_award:
Intent mIntent = new Intent(MotherActivity.this,
AwardRecyclerActivity.class);
startActivity(mIntent);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
return true;
case R.id.action_birthday:
Intent mIntentBirthday = new Intent(MotherActivity.this,
BirthdayRecyclerActivity.class);
startActivity(mIntentBirthday);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
return true;
case R.id.action_event:
Intent mIntentEvent = new Intent(MotherActivity.this,
EventRecyclerActivity.class);
startActivity(mIntentEvent);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
return true;
case R.id.action_report:
Intent mIntentReport = new Intent(MotherActivity.this,
ReportActivity.class);
startActivity(mIntentReport);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void attachBaseContext(Context newBase) {
try{
if(AndroidUtilities.isAppLanguageIsEnglish()){
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}else{
super.attachBaseContext(newBase);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description:</b></br> Initialise Ui Elements from XML
*
* @author Vikalp Patel(VikalpPatelCE)
*/
private void initUi() {
mHeaderView = findViewById(R.id.header);
ViewCompat.setElevation(mHeaderView,
getResources().getDimension(R.dimen.toolbar_elevation));
mToolbarView = findViewById(R.id.toolbarLayout);
mPager = (ViewPager) findViewById(R.id.pager);
mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
mCroutonViewGroup = (FrameLayout) findViewById(R.id.croutonViewGroup);
}
/**
* <b>Description: </b></br>Initialize ToolBar</br></br>
*
* @author Vikalp Patel(VikalpPatelCE)
*/
private void initToolBar() {
mToolBar = (Toolbar) findViewById(R.id.toolbarLayout);
mToolBar.setNavigationIcon(R.drawable.ic_back_shadow);
mToolBar.setTitle("");
setSupportActionBar(mToolBar);
}
/**
* <b>Description:</b></br> Sets Listener on Ui Elements</br></br>
*
* @author Vikalp Patel(VikalpPatelCE)
*/
private void setUiListener() {
mSlidingTabLayout
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i2) {
}
@Override
public void onPageSelected(int i) {
propagateToolbarState(toolbarIsShown());
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
/**
* <b>Description: </b></br>Apply Theme</br></br>
*
* @author Vikalp Patel(VikalpPatelCE)
*/
private void applyTheme(){
try{
ThemeUtils.getInstance(MotherActivity.this).applyThemeMother(MotherActivity.this, MotherActivity.this, mToolBar, mSlidingTabLayout);
ThemeUtils.getInstance(MotherActivity.this).applyThemeDrawer(MotherActivity.this, MotherActivity.this, mDrawerProfileBgLayout, mDrawerUserNameTv);
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
private void getIntentData(){
try{
int isTrainingTab = getIntent().getIntExtra(AppConstants.INTENTCONSTANTS.CATEGORY, 0);
if(isTrainingTab == 1){
mPager.setCurrentItem(1, true);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description: </b></br>Notify PagerSlidingTabStrip on New Data Added</br></br>
*
* @author Vikalp Patel(VikalpPatelCE)
*/
private BroadcastReceiver mBroadCastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent mIntent) {
refreshMotherActivity(mIntent);
}
};
/**
* <b>Description: </b></br>Notify PagerSlidingTabStrip, Fragments & MenuItem Counts</br></br>
*
* @author Vikalp Patel(VikalpPatelCE)
*/
private void refreshMotherActivity(Intent mIntent){
try{
String mCategory = mIntent.getStringExtra(AppConstants.INTENTCONSTANTS.CATEGORY);
if (mCategory
.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.MOBCAST)
|| mCategory
.equalsIgnoreCase(AppConstants.INTENTCONSTANTS.TRAINING)) {
notifySlidingTabLayoutChange();
notifyFragmentWithIdAndCategory(mIntent.getIntExtra(AppConstants.INTENTCONSTANTS.ID, -1), mCategory);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description: </b></br>Broadcast Receiver : Syncing</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private BroadcastReceiver mSyncBroadCastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent mIntent) {
try{
mDrawerSyncLayout.setEnabled(true);
mDrawerSyncLayout.setClickable(true);
mDrawerSyncIv.clearAnimation();
mDrawerSyncTv.setText(ApplicationLoader.getPreferences().getLastSyncTimeStampMessage());
onResume();
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
};
/**
* <b>Description: </b></br>Notify MotherPagerAdapter : PagerSlidingTabStrip</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void notifySlidingTabLayoutChange(){
mArrayListMotherHeader.get(0).setmIsUnread(Utilities.getUnreadOfMobcast(MotherActivity.this) > 0 ? true : false);
mArrayListMotherHeader.get(1).setmIsUnread(Utilities.getUnreadOfTraining(MotherActivity.this) > 0 ? true : false);
mArrayListMotherHeader.get(0).setmUnreadCount(String.valueOf(Utilities.getUnreadOfMobcast(MotherActivity.this)));
mArrayListMotherHeader.get(1).setmUnreadCount(String.valueOf(Utilities.getUnreadOfTraining(MotherActivity.this)));
mPagerAdapter.notifyDataSetChanged(mArrayListMotherHeader);
mSlidingTabLayout.notifyDataSetChanged(mPager);
notifyDrawerUnreadCount();
}
/**
* <b>Description: </b></br>Notify Drawer List Item and ProfileImage</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void notifyDrawerUnreadCount(){
try{
mDrawerAdapter.notifyDataSetChanged();
setDrawerProfileInfo(mDrawerUserNameTv, mDrawerUserEmailTv, mDrawerProfileIv, mDrawerProfileCoverIv);
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description: </b></br>Notify Fragment</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void notifyFragmentWithIdAndCategory(int mId, String mCategory){
if (mId != -1) {
mFragmentCommunicator.passDataToFragment(mId, mCategory);
}
}
/**
* <b>Description: </b></br>Set MenuIcon According to Theme</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
@SuppressWarnings("deprecation")
private Drawable buildCounterDrawableWithPNG(int mType, int whichTheme){
Drawable mDrawable = null;
try{
Resources mResources = getResources();
switch(mType){
case AppConstants.TYPE.BIRTHDAY:
switch (whichTheme) {
case 0:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_dblue);
break;
case 1:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_purple);
break;
case 2:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_green);
break;
case 3:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_pink);
break;
case 4:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_dblue);
break;
case 5:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_brown);
break;
case 6:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_purple);
break;
case 7:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_purple);
break;
case 8:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_pink);
break;
case 9:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_dblue);
break;
case 10:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_pink);
break;
case 11:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_purple);
break;
default:
mDrawable =mResources.getDrawable(R.drawable.ic_toolbar_birthday_unread_dblue);
break;
}
break;
case AppConstants.TYPE.AWARD:
switch (whichTheme) {
case 0:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_dblue);
break;
case 1:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_purple);
break;
case 2:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_green);
break;
case 3:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_pink);
break;
case 4:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_dblue);
break;
case 5:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_brown);
break;
case 6:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_purple);
break;
case 7:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_purple);
break;
case 8:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_pink);
break;
case 9:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_dblue);
break;
case 10:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_pink);
break;
case 11:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_purple);
break;
default:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_award_unread_dblue);
break;
}
break;
case AppConstants.TYPE.EVENT:
switch (whichTheme) {
case 0:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_dblue);
break;
case 1:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_purple);
break;
case 2:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_green);
break;
case 3:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_pink);
break;
case 4:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_dblue);
break;
case 5:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_brown);
break;
case 6:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_purple);
break;
case 7:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_purple);
break;
case 8:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_pink);
break;
case 9:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_dblue);
break;
case 10:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_pink);
break;
case 11:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_purple);
break;
default:
mDrawable = mResources.getDrawable(R.drawable.ic_toolbar_event_unread_dblue);
break;
}
break;
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
return mDrawable;
}
/**
* <b>Description: </b></br>Set Counter to MenuItem</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
@SuppressLint("InflateParams")
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.include_toolbar_action_layout,
null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view
.findViewById(R.id.actionItemCounterPanelLayout);
counterTextPanel.setVisibility(View.GONE);
} else {
AppCompatTextView textView = (AppCompatTextView) view
.findViewById(R.id.actionItemCounter);
textView.setText("" + count);
}
view.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
/**
* <b>Description: </b></br>Set Adapter to PagerSlidingTabStrip</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void setSlidingTabPagerAdapter() {
mArrayListMotherHeader = getMotherPagerHeader();
// mPagerAdapter = new NavigationAdapter(getSupportFragmentManager());
mPagerAdapter = new MotherPagerAdapter(getSupportFragmentManager(),
mArrayListMotherHeader);
mPager.setAdapter(mPagerAdapter);
mSlidingTabLayout.setDistributeEvenly(true);
mSlidingTabLayout.setViewPager(mPager);
}
/**
* <b>Description: </b></br>Set No of Tabs to PagerSlidingTabStrip</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private ArrayList<MotherHeader> getMotherPagerHeader() {
mArrayListMotherHeader = new ArrayList<MotherHeader>();
MotherHeader obj1 = new MotherHeader();
int mUnreadCountMobcast = Utilities.getUnreadOfMobcast(MotherActivity.this);
if(mUnreadCountMobcast > 0){
obj1.setmIsUnread(true);
}else{
obj1.setmIsUnread(false);
}
obj1.setmTitle(getResources().getString(R.string.layout_mother_mobcast));
obj1.setmUnreadCount(String.valueOf(mUnreadCountMobcast));
mArrayListMotherHeader.add(obj1);
/* MotherHeader obj2 = new MotherHeader();
obj2.setmIsUnread(false);
obj2.setmTitle(getResources().getString(R.string.layout_mother_chat));
obj2.setmUnreadCount("0");
mArrayListMotherHeader.add(obj2);*/
MotherHeader obj3 = new MotherHeader();
int mUnreadCountTraining = Utilities.getUnreadOfTraining(MotherActivity.this);
if(mUnreadCountTraining > 0){
obj3.setmIsUnread(true);
}else{
obj3.setmIsUnread(false);
}
obj3.setmTitle(getResources().getString(R.string.layout_mother_training));
obj3.setmUnreadCount(String.valueOf(mUnreadCountTraining));
mArrayListMotherHeader.add(obj3);
return mArrayListMotherHeader;
}
/**
* <b>Description: </b></br>ObservableView</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
@Override
public void onScrollChanged(int scrollY, boolean firstScroll,
boolean dragging) {
if (dragging) {
int toolbarHeight = mToolbarView.getHeight();
float currentHeaderTranslationY = ViewHelper
.getTranslationY(mHeaderView);
if (firstScroll) {
if (-toolbarHeight < currentHeaderTranslationY) {
mBaseTranslationY = scrollY;
}
}
float headerTranslationY = ScrollUtils.getFloat(
-(scrollY - mBaseTranslationY), -toolbarHeight, 0);
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewHelper.setTranslationY(mHeaderView, headerTranslationY);
}
}
@Override
public void onDownMotionEvent() {
}
@Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
mBaseTranslationY = 0;
Fragment fragment = getCurrentFragment();
if (fragment == null) {
return;
}
View view = fragment.getView();
if (view == null) {
return;
}
// ObservableXxxViews have same API
// but currently they don't have any common interfaces.
adjustToolbar(scrollState, view);
}
private void adjustToolbar(ScrollState scrollState, View view) {
int toolbarHeight = mToolbarView.getHeight();
final Scrollable scrollView = (Scrollable) view
.findViewById(R.id.scroll);
if (scrollView == null) {
return;
}
int scrollY = scrollView.getCurrentScrollY();
if (scrollState == ScrollState.DOWN) {
showToolbar();
} else if (scrollState == ScrollState.UP) {
if (toolbarHeight <= scrollY) {
hideToolbar();
} else {
showToolbar();
}
} else {
// Even if onScrollChanged occurs without scrollY changing, toolbar
// should be adjusted
if (toolbarIsShown() || toolbarIsHidden()) {
// Toolbar is completely moved, so just keep its state
// and propagate it to other pages
propagateToolbarState(toolbarIsShown());
} else {
// Toolbar is moving but doesn't know which to move:
// you can change this to hideToolbar()
showToolbar();
}
}
}
private Fragment getCurrentFragment() {
return mPagerAdapter.getItemAt(mPager.getCurrentItem());
}
/**
* <b>Description: </b></br>When the page is selected, other fragments'
* scrollY should be adjusted according to the toolbar
* status(shown/hidden)</br></br> <b>Referenced
* :</b></br>com.github.ksoichiro
* .android.observablescrollview.samples</br></br>
*
* @param isShown
*/
private void propagateToolbarState(boolean isShown) {
int toolbarHeight = mToolbarView.getHeight();
// Set scrollY for the fragments that are not created yet
mPagerAdapter.setScrollY(isShown ? 0 : toolbarHeight);
// Set scrollY for the active fragments
for (int i = 0; i < mPagerAdapter.getCount(); i++) {
// Skip current item
if (i == mPager.getCurrentItem()) {
continue;
}
// Skip destroyed or not created item
Fragment f = mPagerAdapter.getItemAt(i);
if (f == null) {
continue;
}
View view = f.getView();
if (view == null) {
continue;
}
propagateToolbarState(isShown, view, toolbarHeight);
}
}
/**
* <b>Description:</b></br>propogateToolbarState
*
* @param isShown
* @param view
* @param toolbarHeight
*/
private void propagateToolbarState(boolean isShown, View view,
int toolbarHeight) {
Scrollable scrollView = (Scrollable) view.findViewById(R.id.scroll);
if (scrollView == null) {
return;
}
if (isShown) {
// Scroll up
if (0 < scrollView.getCurrentScrollY()) {
scrollView.scrollVerticallyTo(0);
}
} else {
// Scroll down (to hide padding)
if (scrollView.getCurrentScrollY() < toolbarHeight) {
scrollView.scrollVerticallyTo(toolbarHeight);
}
}
}
private boolean toolbarIsShown() {
return ViewHelper.getTranslationY(mHeaderView) == 0;
}
private boolean toolbarIsHidden() {
return ViewHelper.getTranslationY(mHeaderView) == -mToolbarView
.getHeight();
}
private void showToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
if (headerTranslationY != 0) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView).translationY(0)
.setDuration(200).start();
}
propagateToolbarState(true);
}
private void hideToolbar() {
float headerTranslationY = ViewHelper.getTranslationY(mHeaderView);
int toolbarHeight = mToolbarView.getHeight();
if (headerTranslationY != -toolbarHeight) {
ViewPropertyAnimator.animate(mHeaderView).cancel();
ViewPropertyAnimator.animate(mHeaderView)
.translationY(-toolbarHeight).setDuration(200).start();
}
propagateToolbarState(false);
}
/**
* <b>Description: </b></br>Activity : Fragment Communicator</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
@Override
public void passDataToActivity(int mId, String mCategory) {
// TODO Auto-generated method stub
notifySlidingTabLayoutChange();
}
/**
* <b>Description: </b></br>AppRater : Show App Rate</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void showAppRate(){
try{
AppRater.app_launched(MotherActivity.this, 7, 20, 21, 40);
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description: </b></br>ShowCaseView : Starts for the first time</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void showCaseView(){
if(!ApplicationLoader.getPreferences().isAppShowCaseViewMother()){
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
mMenuAwardView = getWindow().getDecorView().findViewById(android.R.id.content).findViewById(R.id.action_award);
mMenuSearchView = getWindow().getDecorView().findViewById(android.R.id.content).findViewById(R.id.action_search);
mMenuBirthdayView = getWindow().getDecorView().findViewById(android.R.id.content).findViewById(R.id.action_birthday);
mMenuEventView = getWindow().getDecorView().findViewById(android.R.id.content).findViewById(R.id.action_event);
ApplicationLoader.getPreferences().setAppShowCaseViewMother(true);
if (mMenuAwardView != null && mMenuBirthdayView != null
&& mMenuEventView != null && mMenuSearchView != null) {
startSequenceShowCaseView(2000, 250);
}
}
}, 1000);
}
}
/**
* <b>Description: </b></br>Sequence ShowCaseView</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void startSequenceShowCaseView(int mDelay, int mSequenceDelay){
try{
MaterialShowcaseView.Builder mMaterialShowcaseViewBuilder1 = new MaterialShowcaseView.Builder(MotherActivity.this);
final MaterialShowcaseView mShowCaseView1 = mMaterialShowcaseViewBuilder1.setTarget(mToolBar.getChildAt(0))
.setDismissText(getResources().getString(R.string.showcase_next))
.setContentText(getResources().getString(R.string.showcase_content1))
.setContentTextColor(getResources().getColor(R.color.white))
.setMaskColour(getResources().getColor(R.color.mobcast_red))
.setDelay(mSequenceDelay) // optional but starting animations immediately in onCreate can make them choppy
.show();
mMaterialShowcaseViewBuilder1.getSkipTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView1.hide();
}
});
mMaterialShowcaseViewBuilder1.getDismissTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
mShowCaseView1.hide();
MaterialShowcaseView.Builder mMaterialShowcaseViewBuilder2 = new MaterialShowcaseView.Builder(MotherActivity.this);
final MaterialShowcaseView mShowCaseView2 = mMaterialShowcaseViewBuilder2.setTarget(mMenuEventView)
.setDismissText(getResources().getString(R.string.showcase_next))
.setContentText(getResources().getString(R.string.showcase_content2))
.setContentTextColor(getResources().getColor(R.color.black_shade_light))
.setMaskColour(getResources().getColor(R.color.mobcast_yellow))
.setDelay(250) // optional but starting animations immediately in onCreate can make them choppy
.show();
mMaterialShowcaseViewBuilder2.getSkipTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView2.hide();
}
});
mMaterialShowcaseViewBuilder2.getDismissTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView2.hide();
MaterialShowcaseView.Builder mMaterialShowcaseViewBuilder3 = new MaterialShowcaseView.Builder(MotherActivity.this);
final MaterialShowcaseView mShowCaseView3 = mMaterialShowcaseViewBuilder3.setTarget(mMenuAwardView)
.setDismissText(getResources().getString(R.string.showcase_next))
.setContentText(getResources().getString(R.string.showcase_content3))
.setContentTextColor(getResources().getColor(R.color.white))
.setMaskColour(getResources().getColor(R.color.mobcast_purple))
.setDelay(250) // optional but starting animations immediately in onCreate can make them choppy
.show();
mMaterialShowcaseViewBuilder3.getSkipTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView3.hide();
}
});
mMaterialShowcaseViewBuilder3.getDismissTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView3.hide();
MaterialShowcaseView.Builder mMaterialShowcaseViewBuilder4 = new MaterialShowcaseView.Builder(MotherActivity.this);
final MaterialShowcaseView mShowCaseView4 = mMaterialShowcaseViewBuilder4.setTarget(mMenuBirthdayView)
.setDismissText(getResources().getString(R.string.showcase_next))
.setContentText(getResources().getString(R.string.showcase_content4))
.setContentTextColor(getResources().getColor(R.color.white))
.setMaskColour(getResources().getColor(R.color.mobcast_green))
.setDelay(250) // optional but starting animations immediately in onCreate can make them choppy
.show();
mMaterialShowcaseViewBuilder4.getSkipTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView4.hide();
}
});
mMaterialShowcaseViewBuilder4.getDismissTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView4.hide();
MaterialShowcaseView.Builder mMaterialShowcaseViewBuilder5 = new MaterialShowcaseView.Builder(MotherActivity.this);
final MaterialShowcaseView mShowCaseView5 = mMaterialShowcaseViewBuilder5.setTarget(mMenuSearchView)
.setDismissText(getResources().getString(R.string.showcase_gotit))
.setContentText(getResources().getString(R.string.showcase_content5))
.setContentTextColor(getResources().getColor(R.color.white))
.setMaskColour(getResources().getColor(R.color.mobcast_blue))
.setDelay(250) // optional but starting animations immediately in onCreate can make them choppy
.show();
mMaterialShowcaseViewBuilder5.getSkipTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView5.hide();
}
});
mMaterialShowcaseViewBuilder5.getDismissTextView().setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mShowCaseView5.hide();
}
});
}
});
}
});
}
});
}
});
}catch(Exception e){
FileLog.e("showCaseView", e.toString());
}
}
/**
* <b>Description: </b></br>LogOut : Clear Preferences, Truncate Database, Delete Files, Update Api</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void logOutFromApp(){
if(Utilities.isInternetConnected()){
if (AndroidUtilities.isAboveHoneyComb()) {
new AsyncLogOutTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
} else {
new AsyncLogOutTask().execute();
}
}else{
Utilities.showCrouton(MotherActivity.this, mCroutonViewGroup, getResources().getString(R.string.internet_unavailable), Style.ALERT);
}
}
/**
* <b>Description: </b></br>AsyncTask : LogOut</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
public class AsyncLogOutTask extends AsyncTask<Void, Void, Void>{
private MobcastProgressDialog mProgressDialog;
private String mResponseFromApi;
private boolean isSuccess;
private String mErrorMessage;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog = new MobcastProgressDialog(MotherActivity.this);
mProgressDialog.setMessage(getResources().getString(R.string.logging_out));
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
mResponseFromApi = apiUserAppLogOut();
isSuccess = Utilities.isSuccessFromApi(mResponseFromApi);
if(isSuccess){
ApplicationLoader.getPreferences().clearPreferences();
Utilities.deleteTables();
Utilities.deleteAppFolder(new File(AppConstants.FOLDER.BUILD_FOLDER));
ApplicationLoader.cancelSyncServiceAlarm();
ApplicationLoader.cancelAppOpenRemindServiceAlarm();
Utilities.showBadgeNotification(MotherActivity.this);
}else{
mErrorMessage = Utilities.getErrorMessageFromApi(mResponseFromApi);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try{
if(mProgressDialog!=null){
mProgressDialog.dismiss();
}
if(isSuccess){
Toast.makeText(MotherActivity.this, Utilities.getSuccessMessageFromApi(mResponseFromApi), Toast.LENGTH_SHORT).show();
MotherActivity.this.finish();
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
}
/**
* <b>Description: </b></br>Api : LogOut</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private String apiUserAppLogOut() {
try {
JSONObject jsonObj = JSONRequestBuilder.getPostAppLogOutData();
if(BuildVars.USE_OKHTTP){
return RetroFitClient.postJSON(new OkHttpClient(), AppConstants.API.API_LOGOUT_USER, jsonObj.toString(), TAG);
}else{
return RestClient.postJSON(AppConstants.API.API_LOGOUT_USER, jsonObj, TAG);
}
} catch (Exception e) {
// TODO Auto-generated catch block
FileLog.e(TAG, e.toString());
}
return null;
}
/**
* <b>Description: </b></br>Dialog : Logout Confirmation</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void showLogOutConfirmationMaterialDialog(){
MaterialDialog mMaterialDialog = new MaterialDialog.Builder(MotherActivity.this)
.title(getResources().getString(R.string.logout_title_message))
.titleColor(Utilities.getAppColor())
.content(getResources().getString(R.string.logout_content_message))
.contentColor(Utilities.getAppColor())
.positiveText(getResources().getString(R.string.sample_fragment_settings_dialog_language_positive))
.positiveColor(Utilities.getAppColor())
.negativeText(getResources().getString(R.string.sample_fragment_settings_dialog_language_negative))
.negativeColor(Utilities.getAppColor())
.callback(new MaterialDialog.ButtonCallback() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public void onPositive(MaterialDialog dialog) {
logOutFromApp();
dialog.dismiss();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public void onNegative(MaterialDialog dialog) {
dialog.dismiss();
}
})
.show();
}
/**
* <b>Description: </b></br>Api : Check Version Update + Update Reg Id</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void apiCheckVersionUpdate(){
try{
ApplicationLoader.getPreferences().setAppUpdateAvail(false);
if(Utilities.isInternetConnected()){
CheckVersionUpdateAsyncTask mCheckVersionUpdateAsyncTask = new CheckVersionUpdateAsyncTask();
if (AndroidUtilities.isAboveHoneyComb()) {
mCheckVersionUpdateAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null, null, null);
} else {
mCheckVersionUpdateAsyncTask.execute();
}
mCheckVersionUpdateAsyncTask.setOnPostExecuteListener(new OnPostExecuteListener() {
@Override
public void onPostExecute(String mResponseFromApi) {
// TODO Auto-generated method stub
try{
if(Utilities.isSuccessFromApi(mResponseFromApi)){
try {
JSONObject mJSONObj = new JSONObject(mResponseFromApi);
if(mJSONObj.getBoolean(AppConstants.API_KEY_PARAMETER.updateAvailable)){
ApplicationLoader.getPreferences().setAppUpdateAvail(true);
showUpdateAvailConfirmationMaterialDialog();
}
ApplicationLoader.getPreferences().setToCallFromNodeJS(mJSONObj.getBoolean(AppConstants.API_KEY_PARAMETER.isToCallNodeJS));
} catch (JSONException e) {
// TODO Auto-generated catch block
FileLog.e(TAG, e.toString());
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
});
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description: </b></br>New Data Bubble : Like Facebook - New Stores</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void checkMobcastForNewDataAvail(){
try{
if(ApplicationLoader.getPreferences().isRefreshMobcastWithNewDataAvail()){
Intent mIntent = new Intent();
mIntent.putExtra(AppConstants.INTENTCONSTANTS.CATEGORY, AppConstants.INTENTCONSTANTS.MOBCAST);
refreshMotherActivity(mIntent);
}
if(ApplicationLoader.getPreferences().isRefreshTrainingWithNewDataAvail()){
Intent mTrainIntent = new Intent();
mTrainIntent.putExtra(AppConstants.INTENTCONSTANTS.CATEGORY, AppConstants.INTENTCONSTANTS.TRAINING);
refreshMotherActivity(mTrainIntent);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* <b>Description: </b></br>onResume : CheckAppVersion - ForceUpdate</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void checkAppVersionOnResume(){
if(ApplicationLoader.getPreferences().isAppUpdateAvail()){
showUpdateAvailConfirmationMaterialDialog();
}
}
/**
* <b>Description: </b></br>Dialog : Update Available</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void showUpdateAvailConfirmationMaterialDialog(){
MaterialDialog mMaterialDialog = new MaterialDialog.Builder(MotherActivity.this)
.title(getResources().getString(R.string.update_title_message))
.titleColor(Utilities.getAppColor())
.content(getResources().getString(R.string.update_delete_message))
.contentColor(Utilities.getAppColor())
.positiveText(getResources().getString(R.string.update))
.positiveColor(Utilities.getAppColor())
.cancelable(false)
.callback(new MaterialDialog.ButtonCallback() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public void onPositive(MaterialDialog dialog) {
dialog.dismiss();
Intent mIntent = new Intent(Intent.ACTION_VIEW);
mIntent.setData(Uri.parse(AppConstants.mStoreLink));
startActivity(mIntent);
}
})
.show();
}
/**
* Drawer Initilization
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void setDrawerLayout() {
mResources = getResources();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_listview);
mScrimInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(R.id.drawerRootLayout);
mDrawerProfileBgLayout = (FrameLayout)findViewById(R.id.drawerProfileBgLayout);
mDrawerProfileIv = (CircleImageView) findViewById(R.id.drawerProfileIv);
mDrawerProfileCoverIv = (ImageView) findViewById(R.id.drawerProfileCoverIv);
mDrawerUserNameTv = (AppCompatTextView) findViewById(R.id.drawerUserNameTv);
mDrawerUserEmailTv = (AppCompatTextView) findViewById(R.id.drawerUserEmailTv);
mDrawerSyncTv = (AppCompatTextView) findViewById(R.id.drawerSyncContentTv);
mDrawerSyncIv = (ImageView) findViewById(R.id.drawerSyncIv);
mDrawerSyncLayout = (LinearLayout) findViewById(R.id.drawerSyncLayout);
String[] mDrawerItemArray = getResources().getStringArray(
R.array.drawer_array);
int[] mDrawableResId = new int[] { R.drawable.ic_drawer_profile,
R.drawable.ic_drawer_capture, R.drawable.ic_drawer_recruitment,
R.drawable.ic_drawer_recruitment,
R.drawable.ic_drawer_settings, R.drawable.ic_drawer_help,
R.drawable.ic_drawer_report, R.drawable.ic_drawer_feedback,
R.drawable.ic_drawer_logout, R.drawable.ic_drawer_invite, R.drawable.ic_drawer_about };
mDrawerAdapter = new DrawerArrayAdapter(MotherActivity.this,
mDrawerItemArray, mDrawableResId);
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
setDrawerProfileInfo(mDrawerUserNameTv, mDrawerUserEmailTv, mDrawerProfileIv, mDrawerProfileCoverIv);
drawerArrowDrawable = new DrawerArrowDrawable(mResources);
drawerArrowDrawable.setStrokeColor(mResources
.getColor(android.R.color.white));
mToolBar.setNavigationIcon(drawerArrowDrawable);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mToolBar.setNavigationOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (mDrawerLayout.isDrawerVisible(Gravity.START)) {
mDrawerLayout.closeDrawer(Gravity.START);
} else {
mDrawerLayout.openDrawer(Gravity.START);
}
}
});
mDrawerLayout
.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
offset = slideOffset;
// Sometimes slideOffset ends up so close to but not
// quite 1 or 0.
if (slideOffset >= .995) {
flipped = true;
drawerArrowDrawable.setFlip(flipped);
} else if (slideOffset <= .005) {
flipped = false;
drawerArrowDrawable.setFlip(flipped);
}
try {
drawerArrowDrawable.setParameter(offset);
} catch (IllegalArgumentException e) {
Log.i(TAG, e.toString());
}
}
});
mDrawerSyncLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
animSyncDrawer = (RotateAnimation) AnimationUtils.loadAnimation(getApplicationContext(),R.anim.anim_sync);
mDrawerSyncIv.startAnimation(animSyncDrawer);
mDrawerSyncLayout.setClickable(false);
mDrawerSyncLayout.setEnabled(false);
Intent mSyncServiceIntent = new Intent(MotherActivity.this, SyncService.class);
mSyncServiceIntent.putExtra(AppConstants.INTENTCONSTANTS.ISFROMAPP, true);
startService(mSyncServiceIntent);
}
});
try {
if (AndroidUtilities.isAboveLollyPop()) {
mDrawerLayout.setStatusBarBackgroundColor(getResources()
.getColor(R.color.toolbar_background_statusbar));
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(
android.R.color.transparent));
}
mDrawerSyncTv.setText(ApplicationLoader.getPreferences().getLastSyncTimeStampMessage());
} catch (Exception e) {
}
try{
mDrawerProfileBgLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent drawerIntent = new Intent(MotherActivity.this, EditProfileActivity.class);
mDrawerLayout.closeDrawer(mScrimInsetsFrameLayout);
if (drawerIntent != null){
startActivity(drawerIntent);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
}
}
});
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
try{
Fragment fragment = null;
Bundle args = new Bundle();
Intent drawerIntent = null;
switch (position) {
case 0:
drawerIntent = new Intent(MotherActivity.this, EditProfileActivity.class);
break;
case 1:
drawerIntent = new Intent(MotherActivity.this, CaptureActivity.class);
break;
case 2:
drawerIntent = new Intent(MotherActivity.this, ParichayActivity.class);
break;
case 3:
drawerIntent = new Intent(MotherActivity.this, RecruitmentRecyclerActivity.class);
break;
case 4:
drawerIntent = new Intent(MotherActivity.this, SettingsActivity.class);
break;
case 5:
drawerIntent = new Intent(MotherActivity.this, TutorialActivity.class);
drawerIntent.putExtra(AppConstants.INTENTCONSTANTS.HELP, true);
break;
case 6:
drawerIntent = new Intent(MotherActivity.this, ReportActivity.class);
break;
case 7:
drawerIntent = new Intent(MotherActivity.this, FeedbackAppActivity.class);
break;
case 8:
showLogOutConfirmationMaterialDialog();
break;
case 9:
drawerIntent = new Intent(MotherActivity.this, InviteActivity.class);
drawerIntent.putExtra(AppConstants.INTENTCONSTANTS.ISFROMAPP, true);
break;
/*case 10:
drawerIntent = new Intent(MotherActivity.this, NotificationGeneralRecyclerActivity.class);
drawerIntent.putExtra(AppConstants.INTENTCONSTANTS.ISFROMNOTIFICATION, false);
drawerIntent.putExtra(AppConstants.INTENTCONSTANTS.ISFROMAPP, true);
break;*/
case 10:
drawerIntent = new Intent(MotherActivity.this, AboutActivity.class);
break;
default:
break;
}
mDrawerLayout.closeDrawer(mScrimInsetsFrameLayout);
if (drawerIntent != null){
startActivity(drawerIntent);
AndroidUtilities.enterWindowAnimation(MotherActivity.this);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
public class DrawerArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
private final int[] drawableResId;
public DrawerArrayAdapter(Context context, String[] values,
int[] drawableResId) {
super(context, R.layout.include_layout_drawer, values);
this.context = context;
this.values = values;
this.drawableResId = drawableResId;
}
@SuppressWarnings("deprecation")
@SuppressLint("ViewHolder")
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater
.inflate(R.layout.item_drawer, parent, false);
RelativeLayout mDrawerItemLayout = (RelativeLayout) rowView
.findViewById(R.id.drawerItemLayout);
AppCompatTextView mDrawerItemTextView = (AppCompatTextView) rowView
.findViewById(R.id.drawerItemTitleTv);
ImageView mDrawerItemImageView = (ImageView) rowView
.findViewById(R.id.drawerItemIv);
AppCompatTextView mDrawerItemUnreadTextView = (AppCompatTextView)rowView.findViewById(R.id.drawerItemReadCountTv);
mDrawerItemTextView.setText(values[position]);
mDrawerItemImageView.setImageDrawable(getResources().getDrawable(
drawableResId[position]));
if (position != AppConstants.DRAWER_RECRUITMENT_POS) {
mDrawerItemUnreadTextView.setVisibility(View.GONE);
}else{
if(!(ApplicationLoader.getPreferences().getUnreadRecruitment()<=0)){
mDrawerItemUnreadTextView.setVisibility(View.VISIBLE);
mDrawerItemUnreadTextView.setText(String.valueOf(ApplicationLoader.getPreferences().getUnreadRecruitment()));
}else{
mDrawerItemUnreadTextView.setVisibility(View.GONE);
}
}
return rowView;
}
}
/**
* <b>Description: </b></br>Drawer : Set Profile</br></br>
* @author Vikalp Patel(VikalpPatelCE)
*/
private void setDrawerProfileInfo(AppCompatTextView mNameTextView, AppCompatTextView mEmailTextView, CircleImageView mCircleImageView, final ImageView mImageView){
try{
if(!TextUtils.isEmpty(ApplicationLoader.getPreferences().getUserDisplayName())){
mNameTextView.setText(ApplicationLoader.getPreferences().getUserDisplayName());
}
if(!TextUtils.isEmpty(ApplicationLoader.getPreferences().getUserEmailAddress())){
mEmailTextView.setText(ApplicationLoader.getPreferences().getUserEmailAddress());
}
final String mProfileImagePath = Utilities.getFilePath(AppConstants.TYPE.PROFILE, false, Utilities.getFileName(ApplicationLoader.getPreferences().getUserProfileImageLink()));
if(!TextUtils.isEmpty(ApplicationLoader.getPreferences().getUserProfileImageLink())){
ApplicationLoader.getPreferences().setUserProfileImagePath(mProfileImagePath);
if(Utilities.checkIfFileExists(mProfileImagePath)){
mCircleImageView.setImageURI(Uri.parse(mProfileImagePath));
/*BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mProfileImagePath,bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,Utilities.dpToPx(240, getResources()), Utilities.dpToPx(240, getResources()), true);
mImageView.setImageBitmap(Utilities.blurBitmap(bitmap));*/
}else{
mImageLoader = ApplicationLoader.getUILImageLoader();
mImageLoader.displayImage(ApplicationLoader.getPreferences().getUserProfileImageLink(), mCircleImageView, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
@Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
@Override
public void onLoadingComplete(String arg0, View arg1, Bitmap mBitmap) {
// TODO Auto-generated method stub
Utilities.writeBitmapToSDCard(mBitmap, mProfileImagePath);
/*BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mProfileImagePath,bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,Utilities.dpToPx(240, getResources()), Utilities.dpToPx(240, getResources()), true);
mImageView.setImageBitmap(Utilities.blurBitmap(bitmap));*/
}
@Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
});
}
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
/**
* AndroidM: Permission Model
*/
private void checkPermissionModel() {
try{
if (AndroidUtilities.isAboveMarshMallow()) {
mPermissionHelper = PermissionHelper.getInstance(this);
mPermissionHelper.setForceAccepting(false)
.request(AppConstants.PERMISSION.STORAGE);
}
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mPermissionHelper.onActivityForResult(requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions, @NonNull int[] grantResults) {
mPermissionHelper.onRequestPermissionsResult(requestCode, permissions,
grantResults);
}
@SuppressLint("NewApi") @Override
public void onPermissionGranted(String[] permissionName) {
try{
recreate();
}catch(Exception e){
FileLog.e(TAG, e.toString());
}
}
@Override
public void onPermissionDeclined(String[] permissionName) {
AndroidUtilities.showSnackBar(this, getString(R.string.permission_message_denied));
}
@Override
public void onPermissionPreGranted(String permissionName) {
}
@Override
public void onPermissionNeedExplanation(String permissionName) {
getAlertDialog(permissionName).show();
}
@Override
public void onPermissionReallyDeclined(String permissionName) {
AndroidUtilities.showSnackBar(this, getString(R.string.permission_message_denied));
}
@Override
public void onNoPermissionNeeded() {
}
public AlertDialog getAlertDialog(final String permission) {
AlertDialog builder = null;
if (builder == null) {
builder = new AlertDialog.Builder(this).setTitle(
getResources().getString(R.string.app_name)+ " requires " + permission + " permission").create();
}
builder.setButton(DialogInterface.BUTTON_POSITIVE, "Request",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mPermissionHelper.requestAfterExplanation(permission);
}
});
builder.setMessage(getResources().getString(R.string.permission_message_externalstorage));
return builder;
}
/**
* Google Analytics v3
*/
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance(this).activityStop(this);
}
}
|
package jp.ac.kyushu_u.csce.modeltool.base.constant;
/**
* プリファレンス用定数定義クラス
* @author KBK yoshimura
*/
public class BasePreferenceConstants {
private BasePreferenceConstants() {};
// // 検査設定
// /** key マーク付き仕様書出力フォルダの指定方法 */
// public static final String PK_MARK_FOLDER_SETTING = "mark_folder_setting";
// /** key マーク付き仕様書の出力先 */
// public static final String PK_MARK_FIXED_PATH = "mark_fixed_path";
// /** value マーク付き仕様書出力フォルダの指定方法:既定フォルダ */
// public static final int PV_MARK_FIXED = 1;
// /** value マーク付き仕様書出力フォルダの指定方法:出力時選択 */
// public static final int PV_MARK_SELECT = 2;
/** key マーク色:名詞句(初回) */
public static final String PK_COLOR_NOUN = "color_noun"; //$NON-NLS-1$
/** key マーク色:名詞句 */
public static final String PK_COLOR_NOUN_FIRST = "color_noun_first"; //$NON-NLS-1$
/** key マーク色:動詞句(初回) */
public static final String PK_COLOR_VERB = "color_verb"; //$NON-NLS-1$
/** key マーク色:動詞句 */
public static final String PK_COLOR_VERB_FIRST = "color_verb_first"; //$NON-NLS-1$
/** key マーク色:状態(初回) */
public static final String PK_COLOR_STATE = "color_state"; //$NON-NLS-1$
/** key マーク色:状態 */
public static final String PK_COLOR_STATE_FIRST = "color_state_first"; //$NON-NLS-1$
// /** key 検査モード */
// public static final String PK_INSPECT_MODE = "inspect_mode";
// /** value 検査モード:モード1 */
// public static final int PV_INSPECT_MODE_1 = 1;
// /** value 検査モード:モード2 */
// public static final int PV_INSPECT_MODE_2 = 2;
//
// /** key 正規表現モード */
// public static final String PK_USE_REGULAR_EXPRESSION = "use_regular_expression";
//
//
// // 要求仕様書設定
// /** key 仕様書エディターの折り返し有無 */
// public static final String PK_SPECEDITOR_WORDWRAP = "speceditor_wordwrap";
//
//
// // 辞書設定
// /** key 登録辞書の指定方法 */
// public static final String PK_REGISTER_DICTIONARY = "register_dictionary";
// /** key 既定の登録先辞書 */
// public static final String PK_REGISTER_FIXED_PATH = "register_fixed_path";
// /** value 登録辞書の指定方法:既定辞書へ登録 */
// public static final int PV_REGISTER_FIXED = 1;
// /** value 登録辞書の指定方法:登録時に選択 */
// public static final int PV_REGISTER_SELECT = 2;
// /** value 登録辞書の指定方法:アクティブな辞書へ登録 */
// public static final int PV_REGISTER_ACTIVE = 3;
//
// /** key 抽出・追加位置(下に追加)*/
// public static final String PK_ENTRY_ADD_UNDER = "entry_add_under";
//
// /** key モデル出力フォルダの指定方法 */
// public static final String PK_OUTPUT_FOLDER_SETTING = "output_folder_setting";
// /** key 既定の出力フォルダ */
// public static final String PK_OUTPUT_FIXED_PATH = "output_fixed_path";
// /** value モデル出力フォルダの指定方法:既定フォルダ */
// public static final int PV_OUTPUT_FIXED = 1;
// /** value モデル出力フォルダの指定方法:出力時指定 */
// public static final int PV_OUTPUT_SELECT = 2;
}
|
package com.myvodafone.android.service;
/**
* Created by kakaso on 4/24/2015.
*/
import android.app.Activity;
import android.content.Context;
import com.myvodafone.android.utils.StaticTools;
import com.myvodafone.android.utils.VFPreferences;
import com.worklight.wlclient.WLCookieManager;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLRequestOptions;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;
public class WorklightClientManager {
private static int wlTimeout = 60000;
private static final String LogTag = "WorklightClient";
public static void initializeConnection(WLResponseListener listener, Context context) {
//wlTimeout = VFPreferences.getHOLClientLoginTimeout() * 1000;
wlTimeout = 60 * 1000;//TODO: remove
WLCookieManager.clearCookies();
WLClient.createInstance(context);
WLClient wlClient = WLClient.getInstance();
wlClient.addGlobalHeader("Content-Encoding", "UTF-8");
// Added in 4.0.0
// TODO: check if this fixes WLClient failures
wlClient.addGlobalHeader("Connection", "close");
/// Added in 3.2.0
wlClient.setHeartBeatInterval(-1);
wlClient.init(listener);
}
public static boolean isInitialized() {
try {
return WLClient.getInstance() != null;
} catch (RuntimeException ex) {
return false;
}
}
private static void buildRequest(final Object[] parameters, final FXLWLResponseListenerImpl listener, final String adapterName, final String procedureName, final Activity activity) {
WLClient wlClient = null;
try {
int loginTimeout = VFPreferences.getHOLClientLoginTimeout() * 60 * 1000;
long timeSinceLastRequest = Math.abs(System.currentTimeMillis() - StaticTools.getLastFXLRequestTimestamp());
if (listener != null
&& !adapterName.equals("AuthenticationAdapter")
&& (timeSinceLastRequest >= loginTimeout)) {
listener.onSessionTimeout();
return;
}
wlClient = WLClient.getInstance();
WLProcedureInvocationData invocationData = new WLProcedureInvocationData(adapterName, procedureName);
if (parameters != null) {
invocationData.setParameters(parameters);
}
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(wlTimeout);
StaticTools.setLastFXLRequestTimestamp(System.currentTimeMillis());
wlClient.invokeProcedure(invocationData, listener, options);
if (parameters != null)
for (Object obj : parameters) {
if (obj != null)
StaticTools.Log(obj.toString());
}
} catch (Exception e) {
StaticTools.Log(e);
}
}
public static void submitAuthentication(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "AuthenticationAdapter";
String procedureName = "submitAuthentication";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void submitAuthenticationByCookieId(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "AuthenticationAdapter";
String procedureName = "submitAuthenticationByCookieId";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void deleteUserByCookieId(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "deleteUserByCookieId";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void submitUserConsent(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "submitUserConsent";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getSecretData(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "AuthenticationAdapter";
String procedureName = "getSecretData";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getSingleBillingAccountInfo(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getSingleBillingAccountInfo";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getSingleBillingAccountInfoNoDialog(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getSingleBillingAccountInfo";
WLClient wlClient = WLClient.getInstance();
WLProcedureInvocationData invocationData = new WLProcedureInvocationData(adapterName, procedureName);
if (parameters != null) {
invocationData.setParameters(parameters);
}
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(wlTimeout);
wlClient.invokeProcedure(invocationData, listener, options);
}
public static void getRemainingValue(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getRemainingValue";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void retrieveBillingHistory(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "retrieveBillingHistory";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getPdf(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getPdf";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getOpenAmountDue(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getOpenAmountDue";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getEncryptQueryStringDataResponse(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "encryptQueryStringData";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
//////////////////////////
public static void getProductList(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getProductListByCustomerId";
buildRequest(parameters, listener, adapterName, procedureName, activity);
// Params: customerId, Customer Id
}
public static void getWifiSettings(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "retrieveWiFiSettings";
buildRequest(parameters, listener, adapterName, procedureName, activity);
// Params: uId, Curbas User id
}
public static void setWifiSettings(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "changeWifiSettings";
buildRequest(parameters, listener, adapterName, procedureName, activity);
// Params:
// cid, Cpe identifier
// ssid, Wifi name
// encryption, “wpa” or “wpa2” or “wep128”
// password, Cpe Password
// channel, Channel of wifi (1-13)
}
public static void getSpeedTest(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getAdslStats";
buildRequest(parameters, listener, adapterName, procedureName, activity);
// Params:
// uId, Curbas User id
}
public static void getTroubleShooting(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "GetTroubleshootingQuestions";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void createTicket(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "submitTroubleTicket";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getConfigurationInfo(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "GetConfigurationInfo";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getClaimedCoupon(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "claimCoupon";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getCoupons(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getCoupons";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
public static void getUserHistory(Object[] parameters, Activity activity, FXLWLResponseListenerImpl listener) {
String adapterName = "ClientAdapter";
String procedureName = "getUserHistory";
buildRequest(parameters, listener, adapterName, procedureName, activity);
}
/////////////////////////
public static void logResponse(WLResponse resposne) {
if (resposne != null && resposne.getResponseText() != null) {
StaticTools.Log(LogTag, resposne.getResponseText().toString());
} else {
StaticTools.Log(LogTag, "NULL");
}
}
public static void logResponse(WLFailResponse response) {
if (response != null && response.getResponseText() != null) {
StaticTools.Log(LogTag, response.getResponseText().toString());
} else {
StaticTools.Log(LogTag, "NULL");
}
}
public static void getWrappedProducts(Activity activity, FXLWLResponseListenerImpl listener){
String adapterName = "ClientAdapter";
String procedureName = "getWrappedProducts";
buildRequest(null, listener, adapterName, procedureName, activity);
}
}
|
package io.github.jitinsharma.insplore.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by jitin on 26/06/16.
*/
public class LocationObject implements Parcelable{
double latitude;
double longitude;
String airportCode;
String cityName;
String date;
int tabNumber;
boolean tripSwitch;
String tabSelection;
public LocationObject() {
}
protected LocationObject(Parcel in) {
latitude = in.readDouble();
longitude = in.readDouble();
airportCode = in.readString();
cityName = in.readString();
date = in.readString();
tabNumber = in.readInt();
tripSwitch = in.readByte() != 0;
tabSelection = in.readString();
}
public static final Creator<LocationObject> CREATOR = new Creator<LocationObject>() {
@Override
public LocationObject createFromParcel(Parcel in) {
return new LocationObject(in);
}
@Override
public LocationObject[] newArray(int size) {
return new LocationObject[size];
}
};
public String getTabSelection() {
return tabSelection;
}
public void setTabSelection(String tabSelection) {
this.tabSelection = tabSelection;
}
public String getAirportCode() {
return airportCode;
}
public void setAirportCode(String airportCode) {
this.airportCode = airportCode;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getTabNumber() {
return tabNumber;
}
public void setTabNumber(int tabNumber) {
this.tabNumber = tabNumber;
}
public boolean isTripSwitch() {
return tripSwitch;
}
public void setTripSwitch(boolean tripSwitch) {
this.tripSwitch = tripSwitch;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeDouble(latitude);
parcel.writeDouble(longitude);
parcel.writeString(airportCode);
parcel.writeString(cityName);
parcel.writeString(date);
parcel.writeInt(tabNumber);
parcel.writeByte((byte) (tripSwitch ? 1 : 0));
parcel.writeString(tabSelection);
}
}
|
package com.applitools.hackathon.VisualAIRockStar.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Rectangle;
import org.testng.Reporter;
import org.testng.asserts.SoftAssert;
import org.testng.log4testng.Logger;
import com.applitools.hackathon.VisualAIRockStar.common.CommonActions;
import com.applitools.hackathon.VisualAIRockStar.test.BaseTests;
public class FlashSales extends BaseTests{
private static final Logger LOGGER = Logger.getLogger(FlashSales.class);
public static By LOC_LOGO1 = By.cssSelector("div[id='flashSale']");
public static By LOC_LOGO2 = By.cssSelector("div[id='flashSale2']");
static Dimension dimension = null;
static int wlogo1=170;
static int hlogo1=124;
static int wlogo2=181;
static int hlogo2=124;
public static void checkGif1Dimensions(SoftAssert asrt) {
Reporter.log("Check if gif exists or not. Also check the dimensions.", true);
if(CommonActions.checkElementExist(driver, LOC_LOGO1)) {
Reporter.log("Check the dimensions of gif.", true);
Rectangle logo = driver.findElement(LOC_LOGO1).getRect();
dimension = logo.getDimension();
CommonActions.verifyNumbers(wlogo1, dimension.getWidth(),asrt);
CommonActions.verifyNumbers(hlogo1, dimension.getHeight(),asrt);
}else {
LOGGER.fatal("FlashSale.gif does not exist.");
Reporter.log("FlashSale.gif does not exist.", true);
}
}
public static void checkGif2Dimensions(SoftAssert asrt) {
Reporter.log("Check if gif exists or not. Also check the dimensions.", true);
if(CommonActions.checkElementExist(driver, LOC_LOGO2)) {
Reporter.log("Check the dimensions of gif.", true);
Rectangle logo = driver.findElement(LOC_LOGO2).getRect();
dimension = logo.getDimension();
CommonActions.verifyNumbers(wlogo2, dimension.getWidth(),asrt);
CommonActions.verifyNumbers(hlogo2, dimension.getHeight(),asrt);
}else {
LOGGER.fatal("FlashSale2.gif does not exist.");
Reporter.log("FlashSale2.gif does not exist.", true);
}
}
}
|
/**
*/
package iso20022;
import java.lang.String;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Semantic Markup</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Enables modelers to markup elements of the Repository with semantic metadata. Each semanticMarkup string is a TupleValue.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link iso20022.SemanticMarkup#getType <em>Type</em>}</li>
* <li>{@link iso20022.SemanticMarkup#getElements <em>Elements</em>}</li>
* </ul>
*
* @see iso20022.Iso20022Package#getSemanticMarkup()
* @model annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='Semantic Markup represented as a structured meta class instead of as a textual value'"
* @generated
*/
public interface SemanticMarkup extends ModelEntity {
/**
* Returns the value of the '<em><b>Type</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The type of semantic mark-up e.g. "synonym".
* <!-- end-model-doc -->
* @return the value of the '<em>Type</em>' attribute.
* @see #setType(String)
* @see iso20022.Iso20022Package#getSemanticMarkup_Type()
* @model ordered="false"
* annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='Semantic Markup represented as a structured meta class instead of as a textual value'"
* @generated
*/
String getType();
/**
* Sets the value of the '{@link iso20022.SemanticMarkup#getType <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Type</em>' attribute.
* @see #getType()
* @generated
*/
void setType(String value);
/**
* Returns the value of the '<em><b>Elements</b></em>' containment reference list.
* The list contents are of type {@link iso20022.SemanticMarkupElement}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* The elements of semantic markup.
* <!-- end-model-doc -->
* @return the value of the '<em>Elements</em>' containment reference list.
* @see iso20022.Iso20022Package#getSemanticMarkup_Elements()
* @model containment="true" ordered="false"
* annotation="urn:iso:std:iso:20022:2013:ecore:extension basis='IMPLEMENTATION_ENHANCEMENT' description='Semantic Markup represented as a structured meta class instead of as a textual value'"
* @generated
*/
EList<SemanticMarkupElement> getElements();
} // SemanticMarkup
|
/*
* Copyright 2013 Himanshu Bhardwaj
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.himanshu.poc.h2.springboot;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleWebStarter.class)
@WebAppConfiguration
@IntegrationTest(value="server.port:0")
public class H2SpringBootTestIT {
private Logger logger = LoggerFactory.getLogger(H2SpringBootTestIT.class);
@Value("${local.server.port}")
private int port;
private String url = null;
@Before
public void setup() {
url = "http://localhost:"+this.port;
}
@Test
public void testSimpleGet() {
HttpEntity<String> response = new TestRestTemplate().getForEntity(url.concat("/sample/echo/all"), String.class);
logger.info("Response is :->"+response);
}
}
|
package com.datalinks.rsstool.model;
import java.util.List;
import com.datalinks.rsstool.model.xml.Channel;
import com.datalinks.rsstool.model.xml.Item;
import com.datalinks.rsstool.model.xml.Rss;
public class RssFileModel {
private List<RssFile> rssFilez;
private RssFile selectedRssFile;
private Rss selectedRssXmlFile;
private boolean doDelete;
private String fileName;
private List<Item> rssItems;
private Channel channel;
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public List<Item> getRssItems() {
return rssItems;
}
public void setRssItems(List<Item> rssItems) {
this.rssItems = rssItems;
}
public Rss getSelectedRssXmlFile() {
return selectedRssXmlFile;
}
public void setSelectedRssXmlFile(Rss selectedRssXmlFile) {
this.selectedRssXmlFile = selectedRssXmlFile;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public RssFile getSelectedRssFile() {
return selectedRssFile;
}
public void setSelectedRssFile(RssFile selectedRssFile) {
this.selectedRssFile = selectedRssFile;
}
public boolean isDoDelete() {
return doDelete;
}
public void setDoDelete(boolean doDelete) {
this.doDelete = doDelete;
}
public List<RssFile> getRssFilez() {
return rssFilez;
}
public void setRssFilez(List<RssFile> rssFilez) {
this.rssFilez = rssFilez;
}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String time1 = scanner.nextLine();
String[] lineVector = time1.split(":");
int hh1 = Integer.parseInt(lineVector[0]);
int mm1 = Integer.parseInt(lineVector[1]);
String time2 = scanner.nextLine();
lineVector = time2.split(":");
int hh2 = Integer.parseInt(lineVector[0]);
int mm2 = Integer.parseInt(lineVector[1]);
String result = calculateMiddleTime(hh1, mm1, hh2, mm2);
System.out.println(result);
}
static String calculateMiddleTime(int hh1, int mm1, int hh2, int mm2) {
int minute1 = convertToMinute(hh1, mm1);
int minute2 = convertToMinute(hh2, mm2);
int middleTime = minute1 + (minute2 - minute1) / 2;
return minuteToString(middleTime);
}
static int convertToMinute(int h, int m) {
return h * 60 + m;
}
static String minuteToString(int minute) {
int h = minute / 60;
int m = minute % 60;
String hh = h < 10 ? prependZero(Integer.toString(h)) : Integer.toString(h);
String mm = m < 10 ? prependZero(Integer.toString(m)) : Integer.toString(m);
return hh + ":" + mm;
}
static String prependZero(String x) {
return "0" + x;
}
} |
package net.sourceforge.jFuzzyLogic.ruleConnection;
/**
* Methods used to connect rule's antecedents
*
* Connection type: OR
* Connection Method: Maximum
*
* @author pcingola@users.sourceforge.net
*/
public class RuleConnectionMethodOrMax extends RuleConnectionMethod {
public RuleConnectionMethodOrMax() {
super();
name = "or";
}
@Override
public double connect(double antecedent1, double antecedent2) {
return Math.max(antecedent1, antecedent2);
}
@Override
public String toStringFCL() {
return "OR: MAX;";
}
}
|
package com.bjpowernode.bean;
import javax.validation.constraints.*;
public class User {
@NotEmpty(message = "名字不能为空")
@NotNull(message = "名字不能为null")
@Size(max = 20,min = 1,message = "名字长度为{min}-{max}之间")
private String name;
@Min(value = 0,message = "年龄不能小于{value}")
@Max(value = 130,message = "年龄不能大于{value}")
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
package HakerRank.SpecialStringAgain;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the substrCount function below.
static long substrCount2(int n, String s) {
char[] textArr = s.toCharArray();
long count = textArr.length;
// 7
// abcbaba
//10
//갯수 for문
for(int i = 2; i <= textArr.length; i++ ) {
//짝수일때는 모두다 같아야 한다
//이동 인덱스
for(int j = 0; j<textArr.length - i + 1; j++) {
HashSet<Character> tmpStack = new HashSet<Character>();
//검색 부분
for(int k = j; k < j + i; k++) {
//홀수
if( i % 2 == 1) {
int mid = (i + 1) / 2;
if(k == mid + j-1) {
continue;
} else {
tmpStack.add(textArr[k]);
}
//짝수
} else {
tmpStack.add(textArr[k]);
}
}
if(tmpStack.size() == 1) {
count++;
}
}
}
return count;
}
/**
* 풀이
* @param n
* @param s
* @return
*/
public static long substrCount(int n, String s) {
int result = 0;
// it will store the count
// of continues same char
int[] sameChar = new int[n];
int i = 0;
// traverse string character
// from left to right
while (i < n) {
// store same character count
int sameCharCount = 1;
int j = i + 1;
// count smiler character
while (j < n &&
s.charAt(i) == s.charAt(j))
{
sameCharCount++;
j++;
}
// Case : 1
// so total number of
// substring that we can
// generate are : K *( K + 1 ) / 2
// here K is sameCharCount
result += (sameCharCount *
(sameCharCount + 1) / 2);
// store current same char
// count in sameChar[] array
sameChar[i] = sameCharCount;
// increment i
i = j;
}
// Case 2: Count all odd length
// Special Palindromic
// substring
for (int j = 1; j < n; j++) {
// if current character is
// equal to previous one
// then we assign Previous
// same character count to
// current one
if (s.charAt(j) == s.charAt(j - 1))
sameChar[j] = sameChar[j - 1];
// case 2: odd length
if (j > 0 && j < (n - 1) &&
(s.charAt(j - 1) == s.charAt(j + 1) &&
s.charAt(j) != s.charAt(j - 1)))
result += Math.min(sameChar[j - 1],
sameChar[j + 1]);
}
// subtract all single
// length substring
return result;
}
////
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
String s = scanner.nextLine();
long result = substrCount(n, s);
System.out.println(result);
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();
//
// bufferedWriter.close();
scanner.close();
}
}
|
package ViewModel;
import Model.IModel;
import Model.MazeCharacter;
import javafx.scene.input.KeyCode;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.util.Duration;
import java.io.File;
import java.util.Observable;
import java.util.Observer;
public class MyViewModel extends Observable implements Observer {
private IModel model;
private MediaPlayer gameSoundTrack;
private boolean isPlayed = true;
private MazeCharacter mainCharacter = new MazeCharacter("Crash_",0,0);
private MazeCharacter secondCharacter = new MazeCharacter("Crash_Second_",0,0);
public MyViewModel(IModel model) {
this.model = model;
}
@Override
public void update(Observable o, Object arg) {
if(o == model){
if(arg != null) {
String argument = (String) arg;
if(argument == "Maze Load") {
secondCharacter.setCharacterName(model.getLoadedCharacter().getCharacterName() + "Second_");
secondCharacter.setCharacterRow(model.getMainCharacterPositionRow());
secondCharacter.setCharacterCol(model.getMainCharacterPositionColumn());
startSoundTrack(model.getLoadedCharacter().getCharacterName());
}
}
setChanged();
notifyObservers(arg);
}
}
public boolean isPlayed(){
return isPlayed;
}
public void setMainCharacterName(String character){
mainCharacter.setCharacterName(character);
}
public void moveCharacter(KeyCode movement){
model.moveCharacter(movement);
}
public void generateMaze(int row, int col){
model.generateMaze(row, col);
}
public char[][] getMaze() {
return model.getMaze();
}
public int getMainCharacterPositionRow() {
return model.getMainCharacterPositionRow();
}
public int getMainCharacterPositionColumn() {
return model.getMainCharacterPositionColumn();
}
public String getMainCharacterDirection() {
return model.getMainCharacterDirection();
}
public String getMainCharacterName(){ return mainCharacter.getCharacterName();}
public int getSecondCharacterPositionRow() {
return model.getSecondCharacterPositionRow();
}
public int getSecondCharacterPositionColumn() {
return model.getSecondCharacterPositionColumn();
}
public String getSecondCharacterDirection() {
return model.getSecondCharacterDirection();
}
public String getSecondCharacterName(){ return secondCharacter.getCharacterName();}
public boolean isAtTheEnd() {
return model.isAtTheEnd();
}
public int[][] getSolution(){
return model.getSolution();
}
public int[][] getMazeSolutionArr(){
return model.getMazeSolutionArr();
}
public void generateSolution(){
model.generateSolution();
}
public void saveOriginalMaze(File file){
model.saveOriginalMaze(file,mainCharacter.getCharacterName());
}
public void saveCurrentMaze(File file){
model.saveCurrentMaze(file,mainCharacter.getCharacterName());
}
public void loadFile(File file){
model.loadMaze(file);
}
public void closeModel(){
model.closeModel();
}
public void startSoundTrack(String character){
if (gameSoundTrack != null)
gameSoundTrack.stop();
String musicFile = "Resources/Music/" + character + "gameSoundTrack.mp3";
Media sound = new Media(new File(musicFile).toURI().toString());
gameSoundTrack = new MediaPlayer(sound);
gameSoundTrack.setOnEndOfMedia(new Runnable() {
@Override
public void run() {
gameSoundTrack.seek(Duration.ZERO);
}
});
if(isPlayed){
gameSoundTrack.play();
}
/*gameSoundTrack.play();
isPlayed = true;*/
}
public boolean setSound(){
if (gameSoundTrack == null)
isPlayed = !isPlayed;
else {
gameSoundTrack.play();
if (isPlayed) {
/*gameSoundTrack.stop();*/
gameSoundTrack.setMute(true);
isPlayed = false;
} else {
/*gameSoundTrack.play();*/
gameSoundTrack.setMute(false);
isPlayed = true;
}
}
return isPlayed;
}
public void setSecondCharacterName(String secondCharacterName) {
this.secondCharacter.setCharacterName(secondCharacterName);
}
public MazeCharacter getLoadedCharacter() {
mainCharacter = model.getLoadedCharacter();
return mainCharacter;
}
public void setMultiPlayerMode(boolean setMode){
model.setMultiPlayerMode(setMode);
}
}
|
package co.bucketstargram.command.library;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import co.bucketstargram.common.Command;
import co.bucketstargram.common.HttpRes;
import co.bucketstargram.common.Primary;
import co.bucketstargram.dao.LibraryDao;
import co.bucketstargram.dto.LibraryDto;
public class LibInsert implements Command {
private File directory = null;
private File[] deleteFolderList = null;
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("\n=============library입력.java==============");
LibraryDto library = new LibraryDto();
LibraryDao dao = new LibraryDao();
boolean success = false;
HttpSession session = request.getSession(true);
String serverPath = request.getServletContext().getRealPath("images");
System.out.println(serverPath);
// 라이브러리 아이디 생성
String libraryId = Primary.create();
String libraryTitle = null;
String libraryContent = null;
String libraryType = null;
String libraryImagePath = null;
// 파일 사이즈 제한
int sizeLimit = 1024 * 1024 * 15;
String savePath = serverPath + "\\library\\" + libraryId ;
System.out.println("이미지 저장경로: " + savePath);
// 아래와 같이 MultipartRequest를 생성만 해주면 파일이 업로드 된다.(파일 자체의 업로드 완료)
makeDrectory(savePath);
// 파일 업로드 완료
MultipartRequest multi = new MultipartRequest(request, savePath, sizeLimit, "utf-8",
new DefaultFileRenamePolicy());
System.out.println("Image File 생성");
// //업로드된 파일의 이름을 반환한다
Enumeration files = multi.getFileNames();
// while( files.hasMoreElements() ) {
String file = (String) files.nextElement();
String upFileName = multi.getFilesystemName(file);
System.out.println("upFileName = " + upFileName);
libraryTitle = multi.getParameter("libraryTitle");
libraryContent = multi.getParameter("libraryContent");
libraryType = multi.getParameter("libraryType");
libraryImagePath = "images" + "\\library\\" + libraryId + "\\" + upFileName;
System.out.println("libraryTitle = " + libraryTitle);
System.out.println("libraryContent = " + libraryContent);
System.out.println("libraryImagePath = " + libraryImagePath);
System.out.println("libraryType = " + libraryType);
library.setLibId(libraryId);
library.setLibTitle(libraryTitle);
library.setLibContents(libraryContent);
library.setLibType(libraryType);
library.setLibImagePath(libraryImagePath);
success = dao.libInsert(library);
System.out.println("dao결과 : " + success);
//DB에러 났을 경우 생성된 파일을 자동 삭제 해주는 로직
if(success) { //성공하면
System.out.println("BucketPost.java | DB저장 성공");
//이동할 페이지
String viewPage = "LibraryForm.do";
HttpRes.forward(request, response, viewPage);
}else { //실패하면
System.out.println("BucketPost.java | DB저장 실패");
deleteFolderList = directory.listFiles();
boolean dirDelFlag = true;
while(true) {
if(dirDelFlag) {
for (int i = 0; i < deleteFolderList.length; i++ ) {
dirDelFlag = deleteFolderList[i].delete();
System.out.println("Image File 삭제");
}
}else {
directory.delete();
System.out.println("BuckId Folder 삭제");
break;
}
}
String viewPage = "LibInsertForm.do";
HttpRes.forward(request, response, viewPage);
}
}
private void makeDrectory(String libraryImagePath) {
// TODO Auto-generated method stub
directory = new File(libraryImagePath);
deleteFolderList = directory.listFiles();
if (directory.mkdirs()) {
System.out.println("Bucket Id Folder 생성");
} else {
System.out.println("Bucket Id Folder 생성 실패");
}
}
}
|
package com.zs.ui.channel;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import com.huaiye.sdk.logger.Logger;
import com.huaiye.sdk.sdpmsgs.talk.trunkchannel.TrunkChannelUserBean;
import java.util.List;
import butterknife.BindView;
import com.zs.R;
import com.zs.common.recycle.LiteViewHolder;
public class ChannelDetailItemHolder extends LiteViewHolder {
@BindView(R.id.tv_name)
public TextView tvName;
@BindView(R.id.tv_id)
public TextView tvID;
@BindView(R.id.divider)
View divider;
public ChannelDetailItemHolder(Context context, View view, View.OnClickListener ocl, Object obj) {
super(context, view, ocl, obj);
}
@Override
public void bindData(Object holder, int position, Object data, int size, List datas, Object extr) {
if (position > datas.size()){
divider.setVisibility(View.INVISIBLE);
return;
}
divider.setVisibility(View.VISIBLE);
TrunkChannelUserBean userBean = (TrunkChannelUserBean) data;
tvName.setText(userBean.strTcUserName);
tvID.setText("ID: " + userBean.strTcUserID);
}
}
|
package com.extnds.competitive.problems.gasstation.data;
import com.extnds.competitive.datastructures.CircularList;
import java.util.Iterator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CircularRouteDetails {
private final CircularList<StationDetails> stationDetailsCircularList;
private final int stationCount;
public CircularRouteDetails(final int[] gasAtStationArray, final int[] gasToReachNextStationArray) {
if (gasAtStationArray.length != gasToReachNextStationArray.length) {
throw new IllegalArgumentException("Route data is corrupt. Gas At Station Count != Gas To Reach Next Station Count");
}
stationCount = gasAtStationArray.length;
stationDetailsCircularList = new CircularList<>(
IntStream.range(0, stationCount)
.boxed()
.map(stationIndex -> new StationDetails(gasAtStationArray[stationIndex], gasToReachNextStationArray[stationIndex]))
.collect(Collectors.toList())
);
}
public int getStationCount() {
return stationCount;
}
public Iterator<StationDetails> getSingleLoopIterator(final int startAt) {
if (!stationDetailsCircularList.containsNodeAt(startAt)) {
throw new IllegalArgumentException("Cannot Start Stream. Invalid Station Id.");
}
return stationDetailsCircularList.getSingleLoopIterator(startAt);
}
}
|
package io.github.jitinsharma.insplore.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import java.util.ArrayList;
import io.github.jitinsharma.insplore.R;
import io.github.jitinsharma.insplore.activities.SearchActivity;
import io.github.jitinsharma.insplore.adapter.InspireSearchAdapter;
import io.github.jitinsharma.insplore.model.Constants;
import io.github.jitinsharma.insplore.model.InspireSearchObject;
import io.github.jitinsharma.insplore.model.OnPlacesClick;
import io.github.jitinsharma.insplore.service.InService;
/**
* A simple {@link Fragment} subclass.
* Use the {@link InspirationSearchFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class InspirationSearchFragment extends Fragment {
private String airportCode;
private RecyclerView searchResults;
private ArrayList<InspireSearchObject> inspireSearchObjects;
InBroadcastReceiver inBroadcastReceiver;
ProgressBar progressBar;
String tripType;
SearchActivity searchActivity;
public InspirationSearchFragment() {
// Required empty public constructor
}
public static InspirationSearchFragment newInstance(String airportCode, String tripType) {
InspirationSearchFragment fragment = new InspirationSearchFragment();
Bundle args = new Bundle();
args.putString(Constants.DEP_AIRPORT, airportCode);
args.putString(Constants.TRIP_TYPE, tripType);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
airportCode = getArguments().getString(Constants.DEP_AIRPORT);
tripType = getArguments().getString(Constants.TRIP_TYPE);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList(Constants.INSPIRE_OBJ, inspireSearchObjects);
super.onSaveInstanceState(outState);
}
@Override
public void onDestroy() {
if (inBroadcastReceiver!=null) {
getContext().unregisterReceiver(inBroadcastReceiver);
}
super.onDestroy();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
searchActivity = (SearchActivity) getActivity();
View root = inflater.inflate(R.layout.fragment_inspiration_search, container, false);
searchActivity.updateImage(ContextCompat.getDrawable(getContext(), R.drawable.inspire));
searchActivity.getSupportActionBar().setTitle(getContext().getString(R.string.inspire_search));
if (savedInstanceState!=null){
inspireSearchObjects = savedInstanceState.getParcelableArrayList(Constants.INSPIRE_OBJ);
searchActivity.updateImage(ContextCompat.getDrawable(getContext(), R.drawable.inspire));
searchActivity.getSupportActionBar().setTitle(getContext().getString(R.string.inspire_search));
}
searchResults = (RecyclerView)root.findViewById(R.id.inspire_search_results);
progressBar = (ProgressBar)root.findViewById(R.id.inspire_progress);
searchResults.setLayoutManager(new LinearLayoutManager(getContext()));
initializeReceiver();
if (inspireSearchObjects!=null){
progressBar.setVisibility(View.GONE);
setAdapterWithData();
}
else {
initializeService();
}
return root;
}
class InBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
progressBar.setVisibility(View.GONE);
if (intent.getStringExtra(Constants.NETWORK_ERROR)!=null){
Snackbar.make(getView(), getContext().getString(R.string.server_error), Snackbar.LENGTH_LONG).show();
}
else {
inspireSearchObjects = intent.getParcelableArrayListExtra("KEY");
if (inspireSearchObjects!=null && inspireSearchObjects.size()>0) {
setAdapterWithData();
}
else{
Snackbar.make(getView(), getContext().getString(R.string.no_result_error), Snackbar.LENGTH_LONG).show();
}
}
}
}
public void setAdapterWithData(){
InspireSearchAdapter inspireSearchAdapter = new InspireSearchAdapter(getContext(), inspireSearchObjects, new OnPlacesClick() {
@Override
public void onClick(int position) {
displayPlacesOfInterest(inspireSearchObjects.get(position).getDestinationCity());
}
});
searchResults.setAdapter(inspireSearchAdapter);
}
public void displayPlacesOfInterest(String city){
searchActivity.updateTitle(getContext().getString(R.string.places_of_interest));
PlaceOfInterestFragment fragment = PlaceOfInterestFragment.newInstance(city);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit();
}
public void initializeReceiver(){
inBroadcastReceiver = new InBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter(InService.ACTION_InService);
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
getContext().registerReceiver(inBroadcastReceiver, intentFilter);
}
public void initializeService(){
Intent inService = new Intent(getActivity(), InService.class);
inService.putExtra(Constants.DEP_AIRPORT, airportCode);
inService.putExtra(Constants.TRIP_TYPE, tripType);
getActivity().startService(inService);
}
}
|
package com.nanyin.entity.DTO;
import com.nanyin.entity.Unit;
import com.nanyin.entity.User;
import lombok.Data;
import java.util.Set;
@Data
public class UnitDto {
private Integer id;
private String name;
private String address;
private String comment;
Set<User> users;
}
|
/**
* Created with IntelliJ IDEA.
* User: daixing
* Date: 12-11-26
* Time: 上午12:04
* To change this template use File | Settings | File Templates.
*/
public class ErdosRenyi {
public static void main(String[] args)
{
StdDraw.setXscale(0, 100);
StdDraw.setYscale(0, 100);
for(int N = 10; true; N += N)
StdDraw.point(Math.log(N), Math.log(count(N)));
}
public static int count(int N)
{
WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N);
int count = 0;
while (uf.count() > 1)
{
int p = StdRandom.uniform(0, N);
int q = StdRandom.uniform(0, N);
count++;
if(uf.connected(p, q))
continue;
uf.union(p, q);
}
return count;
}
}
|
package com.javarush.task.task08.task0822;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/*
Минимальное из N чисел
*/
public class Solution {
public static void main(String[] args) throws Exception {
List<Integer> integerList = getIntegerList();
System.out.println(getMinimum(integerList));
}
public static int getMinimum(List<Integer> array) {
int min = Integer.MAX_VALUE ;
for(Integer i : array){
if(i < min){
min = i;
}
}
return min;
}
public static List<Integer> getIntegerList() throws IOException {
List<Integer> list = new ArrayList<>();
InputStream stream = System.in;
Reader reader = new InputStreamReader(stream);
BufferedReader bf = new BufferedReader(reader);
int N = Integer.parseInt(bf.readLine());
for (int i = 0; i < N; i++) {
list.add(Integer.parseInt(bf.readLine()));
}
return list;
}
}
|
package com.lucianoscilletta.battleship.graphics;
import com.lucianoscilletta.battleship.*;
import java.awt.*;
import java.awt.geom.*;
/**
* This class has been automatically generated using <a
* href="https://flamingo.dev.java.net">Flamingo SVG transcoder</a>.
*/
public class ButtonWarRoomDisable implements GameGraphics {
float scaleFactor = BattleshipGame.getScaleFactor();
AffineTransform atScale = null;
/**
* Paints the transcoded SVG image on the specified com.lucianoscilletta.battleship.graphics context. You
* can install a custom transformation on the com.lucianoscilletta.battleship.graphics context to scale the
* image.
*
* @param g
* Graphics context.
*/
public void paint(Graphics2D g) {
Shape shape = null;
Paint paint = null;
Stroke stroke = null;
float origAlpha = 1.0f;
Composite origComposite = ((Graphics2D)g).getComposite();
if (origComposite instanceof AlphaComposite) {
AlphaComposite origAlphaComposite =
(AlphaComposite)origComposite;
if (origAlphaComposite.getRule() == AlphaComposite.SRC_OVER) {
origAlpha = origAlphaComposite.getAlpha();
}
}
atScale = g.getTransform();
atScale.scale(GraphicsEngine.getScaleFactor(), GraphicsEngine.getScaleFactor());
g.setTransform(atScale);
AffineTransform defaultTransform_ = g.getTransform();
//
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0
g.setComposite(AlphaComposite.getInstance(3, 1.0f * origAlpha));
AffineTransform defaultTransform__0_0_0 = g.getTransform();
g.transform(new AffineTransform(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f));
// _0_0_0
paint = new Color(242, 242, 242, 150);
shape = new Rectangle2D.Double(43.3399772644043, 33.13520050048828, 309.0718688964844, 86.386962890625);
g.setPaint(paint);
g.fill(shape);
g.setTransform(defaultTransform__0_0_0);
g.setTransform(defaultTransform__0_0);
g.setTransform(defaultTransform__0);
g.setTransform(defaultTransform_);
}
/**
* Returns the X of the bounding box of the original SVG image.
*
* @return The X of the bounding box of the original SVG image.
*/
public int getOrigX() {
return Math.round(44 * GraphicsEngine.getScaleFactor());
}
/**
* Returns the Y of the bounding box of the original SVG image.
*
* @return The Y of the bounding box of the original SVG image.
*/
public int getOrigY() {
return Math.round(34 * GraphicsEngine.getScaleFactor());
}
/**
* Returns the width of the bounding box of the original SVG image.
*
* @return The width of the bounding box of the original SVG image.
*/
public int getOrigWidth() {
return Math.round(310 * GraphicsEngine.getScaleFactor());
}
/**
* Returns the height of the bounding box of the original SVG image.
*
* @return The height of the bounding box of the original SVG image.
*/
public int getOrigHeight() {
return Math.round(87 * GraphicsEngine.getScaleFactor());
}
}
|
package com.beans;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jboss.resteasy.util.FindAnnotation;
import com.classes.DeliveryOrder;
import com.classes.SupplierOrder;
import com.classes.SupplierProduct;
import com.entities.Drugstore;
import com.entities.Product;
import com.entities.ProductFromDrugstore;
import com.google.gson.Gson;
import com.utils.DeliveryProduct;
import com.utils.ProductAdapter;
/**
* Session Bean implementation class StockService
*/
@Stateless
@LocalBean
public class StockService implements StockServiceRemote, StockServiceLocal {
public boolean post(String url, StringEntity entity) throws Exception {
HttpPost post = new HttpPost(url);
post.setEntity(entity);
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
int code = response.getStatusLine().getStatusCode();
if (code >= 200 && code < 300) {
return true;
}
}
return false;
}
/**
* Default constructor.
*/
private static String DELIVERY_URL="http://127.0.0.1:8080/deliverymicroservice-web-0.0.1-SNAPSHOT/DeliverOrder";
private static String SUPPLYPRODUCT_URL="http://127.0.0.1:8080/suppliermicroservice-web-0.0.1-SNAPSHOT/OrderFromSupplier";
public StockService() {
}
@Override
public List<Product> getProducts() {
System.out.println("Servicio obtener la lista de productos de stock");
return Product.getProducts();
}
@Override
public boolean addProduct( String name, String description, String location, String image, float price, int threshold, int amount ,String keyword) {
System.out.println("Servicio de añadir un producto al stock");
boolean succesfulltransaction = false;
try {
Product product = new Product();
product.setName(name);
product.setDescription(description);
product.setAmount(amount);
product.setPrice(price);
product.setImage(image);
product.setThreshold(threshold);
product.setLocation(location);
product.setKeywords(keyword);
product.save();
succesfulltransaction = true;
} catch (Exception e) {
e.printStackTrace();
}
return succesfulltransaction;
}
@Override
public boolean removeProduct( int id ) {
System.out.println("Sacando remover un producto de stock");
boolean succesfulltransaction = false;
try {
Product product = Product.getProduct(id);
product.removeProduct();
succesfulltransaction=true;
} catch (Exception e) {
e.printStackTrace();
}
return succesfulltransaction;
}
@Override
public List<Product> checkRunningOut() {
System.out.println("Servicio de checkeo de que se acabo algun producto");
ArrayList<Product> productsRunningOut = new ArrayList<Product>();
SupplierOrder supplierOrder = new SupplierOrder();
try {
List<Product> products = Product.getProducts();
for (Product product : products) {
if (product.getAmount() < product.getThreshold()) {
productsRunningOut.add(product);
SupplierProduct supplierProduct = new SupplierProduct();
supplierProduct.setName(product.getName());
supplierProduct.setKeywords(product.getKeywords());
supplierProduct.setAmount(product.getThreshold());
supplierOrder.addProduct(supplierProduct);
}
}
} catch (Exception e) {
e.printStackTrace();
}
Gson gson = new Gson();
String supplierOrderJson = gson.toJson(supplierOrder);
try {
StringEntity entity = new StringEntity(supplierOrderJson);
boolean state = post(SUPPLYPRODUCT_URL, entity);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return productsRunningOut;
}
@Override
public boolean addDrugstore(String address, String email, String name, String phone, String uri) {
System.out.println("Servicio de añadir una droguería ");
Drugstore drugstore=new Drugstore();
drugstore.setAddress(address);
drugstore.setEmail(email);
drugstore.setName(name);
drugstore.setPhone(phone);
drugstore.setUri(uri);
return drugstore.save();
}
@Override
public List<Drugstore> getDrugstores() {
System.out.println("Servicio obtener lista de droguerias");
return Drugstore.getDrugstores();
}
@Override
public boolean modifyDrugstore(int id, String address, String email, String name, String phone, String uri) {
System.out.println("Servicio modificar info de alguna drogueria");
return Drugstore.UpdateDrugstoreById(id, address, email, name, phone, uri);
}
@Override
public boolean deleteDrugstore(int id) {
System.out.println("Sacando remover una droguria");
return Drugstore.deleteById(id);
}
@Override
public List<ProductAdapter> getCatalog(String keywords, int page) {
System.out.println("Servicio obtener un catalogo de todos los productos(incluyendo los de las droguerias)");
List<ProductAdapter> products=new ArrayList<ProductAdapter>();
List<Product> prds=this.getProducts();
List<ProductFromDrugstore> prdsfd=this.getProductsFromDrugstore();
for(Product p:prds) {
if(keywords==null||(p.getKeywords()!=null&&p.getKeywords().contains(keywords))) {
products.add(new ProductAdapter(p));
}
}
for(ProductFromDrugstore p:prdsfd) {
if(keywords==null||(p.getKeywords()!=null&&p.getKeywords().contains(keywords))) {
products.add(new ProductAdapter(p));
}
}
final int PAGE_SIZE = 15;
page-= 1;
if(page == 0 && products.size() < PAGE_SIZE) {
return products;
}
if(products.size()>page*PAGE_SIZE) {
if(products.size() > page*PAGE_SIZE+PAGE_SIZE) {
return products.subList(page*PAGE_SIZE, page*15+15);
}
else {
return products.subList(page*PAGE_SIZE, products.size());
}
}
return new ArrayList<ProductAdapter>();
}
@Override
public List<ProductFromDrugstore> getProductsFromDrugstore() {
System.out.println("Servicio obtener productos de la drogueria");
return ProductFromDrugstore.getProducts();
}
@Override
public boolean addProductFromDrugstore(String name, String description, String keywords, float price,int drugstore_id) {
System.out.println("Servicio que añade los productos que son de las droguerias");
boolean succesfulltransaction = false;
try {
ProductFromDrugstore product = new ProductFromDrugstore();
Drugstore drugstore=Drugstore.getDrugstore(drugstore_id);
product.setDrugstore(drugstore);
product.setName(name);
product.setDescription(description);
product.setPrice(price);
product.setKeywords(keywords);
succesfulltransaction = product.save();;
} catch (Exception e) {
e.printStackTrace();
}
return succesfulltransaction;
}
@Override
public boolean modifyProduct(int id, String name, String description, String location, String image, Float price,
Integer threshold, Integer amount, String keyword) {
System.out.println("Servicio modificar algún aspecto de algun producto");
return Product.UpdateProductById(id, name, description, location, image, price,threshold, amount,keyword);
}
@Override
public boolean removeProductFromDrugstore(int id) {
System.out.println("Servicio de remover lagún producto que venga de alguna drogueria");
boolean succesfulltransaction = false;
try {
ProductFromDrugstore product = ProductFromDrugstore.getProduct(id);
succesfulltransaction=product.removeProduct();
} catch (Exception e) {
e.printStackTrace();
}
return succesfulltransaction;
}
@Override
public boolean modifyProductFromDrugstore(int id, String name, String description, Float price, String keywords) {
System.out.println("Servicio de remover");
return ProductFromDrugstore.UpdateProductById(id, name, description,price,keywords);
}
@Override
public boolean consumeProducts(List<ProductAdapter> products,String destiny_address) {
List<DeliveryProduct> deliveryProducts=new ArrayList<DeliveryProduct>();
ProductAdapter pa;
for(ProductAdapter p:products) {
if(p.getType().equals("drugstore")) {
ProductFromDrugstore product = ProductFromDrugstore.getProduct(p.getId());
if(product==null) {
return false;
}
pa=new ProductAdapter(product);
pa.setAmount(p.getAmount());
deliveryProducts.add(new DeliveryProduct(pa));
}else {
Product product=Product.getProduct(p.getId());
if(product==null) {
return false;
}
int amount=product.getAmount()-p.getAmount();
if(amount<0) {
System.out.println("No hay suficiente producto con id "+p.getId());
return false;
}
pa=new ProductAdapter(product);
pa.setAmount(p.getAmount());
deliveryProducts.add(new DeliveryProduct(pa));
}
}
DeliveryOrder deliveryOrder = new DeliveryOrder();
deliveryOrder.setProducts(deliveryProducts);
deliveryOrder.setDestin_address(destiny_address);
Gson gson = new Gson();
String deliveryOrderJson = gson.toJson(deliveryOrder);
try {
StringEntity entity = new StringEntity(deliveryOrderJson);
post(DELIVERY_URL, entity);
} catch (Exception e) {
e.printStackTrace();
return false;
}
for(ProductAdapter p:products) {
if(p.getType().equals(ProductAdapter.INVENTARY)) {
Product product=Product.getProduct(p.getId());
int amount=product.getAmount()-p.getAmount();
product.setAmount((amount>=0)?amount:0);
product.save();
}
}
return true;
}
public Integer getPrice(List<ProductAdapter> products) {
System.out.println("Se obtiene el precio de algún producto");
double total=0;
for(ProductAdapter p:products) {
if(p.getType().equals("drugstore")) {
ProductFromDrugstore product = ProductFromDrugstore.getProduct(p.getId());
if(product!=null) {
total+=(product.getPrice()*p.getAmount());
}
}else {
Product product=Product.getProduct(p.getId());
if(product!=null) {
total+=(product.getPrice()*p.getAmount());
}
}
}
return (int)total;
}
}
|
public class RotateMatrix {
public static void rotate(int[][] matrix, int n) {
for(int p = 0; p < n; p++) {
int tmp, end, bc;
for(int c = p + 1; c < n - p; c++) {
end = n - p - 1;
bc = n - c - 1;
System.out.println("c:p:bc:end => " + c + ":" + p + ":" + bc + ":" + end);
tmp = matrix[c][p];
matrix[c][p] = matrix[p][bc];
matrix[p][bc] = matrix[bc][end];
matrix[bc][end] = matrix[end][c];
matrix[end][c] = tmp;
}
}
}
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int n = 3;
for(int y = 0; y < n; y++) {
for(int x = 0; x < n; x++)
System.out.print(matrix[y][x] + " ");
System.out.println();
}
rotate(matrix, n);
System.out.println();
for(int y = 0; y < n; y++) {
for(int x = 0; x < n; x++)
System.out.print(matrix[y][x] + " ");
System.out.println();
}
}
}
|
package exercises.chapter3.ex14;
import static net.mindview.util.Print.print;
/**
* @author Volodymyr Portianko
* @date.created 02.03.2016
*/
public class Excercise14 {
static void stringTest(String s1, String s2) {
print(s1 == s2);
print(s1 != s2);
print(s1.equals(s2));
}
public static void main(String[] args) {
stringTest("text1", "text2");
}
}
|
package cl.sportapp.evaluation.dto;
import cl.sportapp.evaluation.entitie.Paciente;
import cl.sportapp.evaluation.entitie.SubtipoMedicion;
import cl.sportapp.evaluation.entitie.TipoEvaluacion;
import lombok.Data;
@Data
public class EvaluacionDto {
private Long id;
private int medicion1;
private int medicion2;
private int medicion3;
private int medicion4;
private int medicion5;
private int mediana;
private int scoreZ;
private SubtipoMedicion subtipoMedicion;
private TipoEvaluacion tipoEvaluacion;
private Paciente paciente;
}
|
package com.meetingapp.android.model;
public class Participant {
private String name;
private String phone;
private String status;
public Participant(String name, String phone, String status) {
this.name = name;
this.phone = phone;
this.status = status;
}
public Participant(String phone, String status) {
this.phone = phone;
this.status = status;
}
public Participant() {
}
@Override
public int hashCode() {
return phone.hashCode();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Participant){
return ((Participant) obj).getPhone().equals(phone);
} else {
return false;
}
}
}
|
package com.pro.dong.common.util;
public class Utils {
public static String getPageBar(int totalContents, int cPage, int numPerPage, String url) {
String pageBar = "";
final int pageBarSize = 5;
// 총페이지
final int totalPage = (int) Math.ceil((double) totalContents / numPerPage);
final int pageStart = ((cPage - 1) / pageBarSize) * pageBarSize + 1;
final int pageEnd = pageStart + pageBarSize - 1;
// 페이지바 순회용 증감변수
int pageNo = pageStart;
pageBar += "<ul class=\"pagination justify-content-center\">";
// [이전] previous
if (pageNo == 1) {
pageBar += "<li class=\"page-item disabled\">\r\n"
+ " <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">이전</a>\r\n"
+ " </li>";
} else {
pageBar += "<li class=\"page-item\">" + "<a class=\"page-link\" href=\"" + url + "?cPage=" + (pageNo - 1)
+ "\">이전</a>" + "</li>";
}
// [pageNo]
while (!(pageNo > pageEnd || pageNo > totalPage)) {
if (cPage == pageNo) {
pageBar += "<li class=\"page-item active\">" + "<a class=\"page-link\">" + pageNo + "</a>" + "</li>";
} else {
pageBar += "<li class=\"page-item\">" + "<a class=\"page-link\" href=\"" + url + "?cPage=" + (pageNo)
+ "\">" + pageNo + "</a>" + "</li>";
}
pageNo++;
}
// [다음] next
if (pageNo > totalPage) {
pageBar += "<li class=\"page-item disabled\">\r\n"
+ " <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">다음</a>\r\n"
+ " </li>";
} else {
pageBar += "<li class=\"page-item\">" + "<a class=\"page-link\" href=\"" + url + "?cPage=" + (pageNo)
+ "\">다음</a>" + "</li>";
}
pageBar += "</ul>";
return pageBar;
}
public String getOneClickPageBar(int totalContents, int cPage, int numPerPage) {
String pageBar = "";
final int pageBarSize = 5;
final int totalPage = (int) Math.ceil((double) totalContents / numPerPage);
final int pageStart = ((cPage - 1) / pageBarSize) * pageBarSize + 1;
final int pageEnd = pageStart + pageBarSize - 1;
int pageNo = pageStart;
pageBar += "<ul class=\"pagination justify-content-center\">";
if (pageNo != 1)
pageBar += "<li class=\"page-item\"><input type='hidden' value='"+(pageNo-1)+"'><a class=\"page-link\">《</a></li>";
while (!(pageNo > pageEnd || pageNo > totalPage)) {
if (cPage == pageNo) {
pageBar += "<li class=\"page-item active\">" + "<a class=\"page-link\">" + pageNo + "</a>" + "</li>";
} else {
pageBar += "<li class=\"page-item\"><input type='hidden' value='"+pageNo+"'><a class=\"page-link\" >" + pageNo + "</a></li>";
}
pageNo++;
}
// [다음] next
if (pageNo <= totalPage)
pageBar += "<li class=\"page-item\"><input type='hidden' value='"+pageNo+"'><a class=\"page-link\" >》</a></li>";
pageBar += "</ul>";
return pageBar;
}
public static String getAjaxPageBar(int totalContents, int cPage, int numPerPage, String function) {
String pageBar = "";
final int pageBarSize = 5;
// 총페이지
final int totalPage = (int) Math.ceil((double) totalContents / numPerPage);
final int pageStart = ((cPage - 1) / pageBarSize) * pageBarSize + 1;
final int pageEnd = pageStart + pageBarSize - 1;
// 페이지바 순회용 증감변수
int pageNo = pageStart;
pageBar += "<ul class=\"pagination justify-content-center\">";
// [이전] previous
if (pageNo == 1) {
pageBar += "<li class=\"page-item disabled\">\r\n"
+ " <button class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">이전</button>\r\n"
+ " </li>";
} else {
pageBar += "<li class=\"page-item\">" + "<button class=\"page-link\" onclick=\"" + function + (pageNo-1)+");\">이전</button>" + "</li>";
}
// [pageNo]
while (!(pageNo > pageEnd || pageNo > totalPage)) {
if (cPage == pageNo) {
pageBar += "<li class=\"page-item active\">" + "<button class=\"page-link\">" + pageNo + "</button>" + "</li>";
} else {
pageBar += "<li class=\"page-item\">" + "<button class=\"page-link\" onclick=\"" + function + pageNo+");\">" + pageNo + "</button>" + "</li>";
}
pageNo++;
}
// [다음] next
if (pageNo > totalPage) {
pageBar += "<li class=\"page-item disabled\">\r\n"
+ " <button class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">다음</button>\r\n"
+ " </li>";
} else {
pageBar += "<li class=\"page-item\">" + "<button class=\"page-link\" onclick=\"" + function + pageNo+");\">다음</button>" + "</li>";
}
pageBar += "</ul>";
return pageBar;
}
public static String getMemberIdPageBar(int totalContents, int cPage, int numPerPage, String url) {
String pageBar = "";
final int pageBarSize = 5;
// 총페이지
final int totalPage = (int) Math.ceil((double) totalContents / numPerPage);
final int pageStart = ((cPage - 1) / pageBarSize) * pageBarSize + 1;
final int pageEnd = pageStart + pageBarSize - 1;
// 페이지바 순회용 증감변수
int pageNo = pageStart;
pageBar += "<ul class=\"pagination justify-content-center\">";
// [이전] previous
if (pageNo == 1) {
pageBar += "<li class=\"page-item disabled\">\r\n"
+ " <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">이전</a>\r\n"
+ " </li>";
} else {
pageBar += "<li class=\"page-item\">" + "<a class=\"page-link\" href=\"" + url + "cPage=" + (pageNo - 1)
+ "\">이전</a>" + "</li>";
}
// [pageNo]
while (!(pageNo > pageEnd || pageNo > totalPage)) {
if (cPage == pageNo) {
pageBar += "<li class=\"page-item active\">" + "<a class=\"page-link\">" + pageNo + "</a>" + "</li>";
} else {
pageBar += "<li class=\"page-item\">" + "<a class=\"page-link\" href=\"" + url + "cPage=" + (pageNo)
+ "\">" + pageNo + "</a>" + "</li>";
}
pageNo++;
}
// [다음] next
if (pageNo > totalPage) {
pageBar += "<li class=\"page-item disabled\">\r\n"
+ " <a class=\"page-link\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">다음</a>\r\n"
+ " </li>";
} else {
pageBar += "<li class=\"page-item\">" + "<a class=\"page-link\" href=\"" + url + "cPage=" + (pageNo)
+ "\">다음</a>" + "</li>";
}
pageBar += "</ul>";
return pageBar;
}
}
|
class TriangleExercises {
void easiestExerciseEver() {
System.out.println("*");
}
void drawAHorizonalLine(int n) {
String asterisks = "";
for (int i = 0; i < n; i++) {
asterisks += "*";
}
System.out.println(asterisks);
}
void drawAVerticalLine(int n) {
String asterisks = "";
for (int i = 0; i < n; i++) {
asterisks += ("*\n");
}
System.out.println(asterisks);
}
void drawARightAngle(int n) {
String asterisks = "";
for (int x = 0; x < n; x++) {
for (int i = 0; i <= x; i++)
asterisks +=("*");
asterisks +=("\n");
}
System.out.println(asterisks);
}
}
class TriangleExercisesTestDrive {
public static void main(String[] args) {
TriangleExercises triangle = new TriangleExercises();
System.out.println("Print one asterisk to the console");
triangle.easiestExerciseEver();
System.out.println("Given Given a number n, print n asterisks on one line.");
triangle.drawAHorizonalLine(8);
System.out.println("Given a number n, print n lines, each with one asterisks");
triangle.drawAVerticalLine(3);
System.out.println("Given a number n, print n lines, each with one more asterisk than the last");
triangle.drawARightAngle(3);
}
}
|
package cn.tedu.inter;
//本类用于运行测试接口实现类
public class InterTests {
public static void main(String[] args) {
/*接口是否可以实例化?--不可以!!*/
//Inter i=new Inter
//定义多态对象进行测试--不常用
Inter i=new InterImpl();
i.eat();
i.play();
//创建纯纯的接口实现类对象进行测试--推荐使用
InterImpl i1=new InterImpl();
i1.eat();
i1.play();
}
}
|
package model;
/**
* Created by Ольга on 09.10.2016.
*/
public enum TypeOfSegment {
BEGIN,
END,
MIDDLE,
INCORRECT
}
|
package org.juxtasoftware.resource;
import java.io.Reader;
import java.util.Map;
import org.juxtasoftware.Constants;
import org.juxtasoftware.JuxtaWS;
import org.juxtasoftware.JuxtaWsApplication;
import org.juxtasoftware.dao.WorkspaceDao;
import org.juxtasoftware.model.Workspace;
import org.juxtasoftware.model.WorkspaceMember;
import org.restlet.Request;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Preference;
import org.restlet.data.Status;
import org.restlet.engine.application.EncodeRepresentation;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.representation.ReaderRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import freemarker.template.Configuration;
/**
* Base class for all JuxtaWS resources. It defines the DB transaction
* boundary to be one request. To do som it must override the default
* handle method and annotate it as transactional. It is the only external
* call that is mave via the cglib proxy during the request so here is where
* the transaction must be made. Also must
* override the default doCatch behavior and rethrow the exception in order
* for the transaction to be rolled back.
*
* @author loufoster
*
*/
public class BaseResource extends ServerResource {
private static final String FTL_ROOT = "clap://class/templates/ftl/";
private static final Configuration FTL_CONFIG;
protected static final Logger LOG = LoggerFactory.getLogger( Constants.WS_LOGGER_NAME );
private boolean zipSupported = false;
protected boolean embedded = false;
protected Workspace workspace;
@Autowired protected WorkspaceDao workspaceDao;
static {
FTL_CONFIG = new Configuration();
FTL_CONFIG.setClassForTemplateLoading(JuxtaWS.class, "/templates/ftl");
FTL_CONFIG.setNumberFormat("computer");
}
@Override
protected void doInit() throws ResourceException {
if (getQuery().getValuesMap().containsKey("embed") ) {
this.embedded = true;
}
if ( getRequestAttributes().containsKey("workspace") ) {
String name = (String) getRequestAttributes().get("workspace");
this.workspace = this.workspaceDao.find( name );
if ( this.workspace == null ) {
setStatus(Status.CLIENT_ERROR_NOT_FOUND, "Workspace not found");
return;
}
} else {
this.workspace = this.workspaceDao.getPublic();
}
JuxtaWsApplication app = (JuxtaWsApplication) getApplication();
if ( app.authenticate(getRequest(), getResponse()) == false ) {
setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return;
}
// See if this client can handle zipped responses
Request r = getRequest();
for ( Preference<Encoding> enc : r.getClientInfo().getAcceptedEncodings() ) {
if ( enc.getMetadata().equals( Encoding.GZIP ) ) {
this.zipSupported = true;
break;
}
}
super.doInit();
}
protected Long getIdFromAttributes( final String name ) {
Long val = null;
if ( getRequestAttributes().containsKey(name) ) {
String strVal = (String)getRequestAttributes().get(name);
try {
val = Long.parseLong(strVal);
} catch (NumberFormatException e) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid identifier specified");
}
} else {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Missing required "+name+" parameter");
}
return val;
}
protected boolean isZipSupported() {
return this.zipSupported;
}
/**
* Ensure that any model data used by this resource exists
* and is accessible within the specified workspace
*
* @param model
*/
protected boolean validateModel( final WorkspaceMember model ) {
if ( model == null ) {
LOG.error("Resource is null");
setStatus(Status.CLIENT_ERROR_NOT_FOUND,
"Invalid resource identifier specified");
return false;
} else if ( model.isMemberOf( this.workspace) == false ) {
LOG.error("Resource "+model.getId()+" is not a member of workspace "+this.workspace.getName());
setStatus(Status.CLIENT_ERROR_NOT_FOUND,
"Resource "+model.getId()+" does not exist in workspace " +
this.workspace.getName());
return false;
}
return true;
}
/**
* Override and append transactional annotation. This defines DB
* trasaction boundary.
*/
@Override
@Transactional
public Representation handle() {
return super.handle();
}
/**
* Must override here re-throw exceptions. This allows transactions
* to be rolled back on errors
*/
@Override
protected void doCatch(Throwable throwable) {
super.doCatch(throwable);
LOG.error("Request Failed", throwable);
throw new RuntimeException(throwable);
}
/**
* Get the trimmed and lowercased workspace name to be used in URLs
* @return
*/
public String getWorkspace() {
return this.workspace.getName().toLowerCase().trim();
}
/**
* Convert the data in msg to a plain text, UTF-8 representation
* @param msg string message to convert
* @return
*/
public Representation toTextRepresentation( final String msg ) {
return new StringRepresentation(msg,
MediaType.TEXT_PLAIN,
Language.DEFAULT,
CharacterSet.UTF_8);
}
/**
* Convert the Reader into an HTML representation, zipping if possible
* @param reader Reader containing the html data
* @return
*/
public Representation toHtmlRepresentation( final Reader reader) {
Representation r = new ReaderRepresentation(reader, MediaType.TEXT_HTML);
if ( this.zipSupported ) {
return new EncodeRepresentation(Encoding.GZIP, r);
}
return r;
}
/**
* Convert the Reader into an XML representation, zipping if possible
* @param reader Reader containing the html data
* @return
*/
public Representation toXmlRepresentation( final String content ) {
Representation r = new StringRepresentation(content,
MediaType.TEXT_PLAIN,
Language.DEFAULT,
CharacterSet.UTF_8);
if ( this.zipSupported ) {
return new EncodeRepresentation(Encoding.GZIP, r);
}
return r;
}
/**
* Convert the JSON data in jsonString to aa application/json,
* UTF-8 representation
* @param jsonString JSON data in string format
* @return
*/
public Representation toJsonRepresentation( final String jsonString ) {
Representation r = new StringRepresentation(jsonString,
MediaType.APPLICATION_JSON,
Language.DEFAULT,
CharacterSet.UTF_8);
if ( this.zipSupported ) {
return new EncodeRepresentation(Encoding.GZIP, r);
}
return r;
}
/**
* Using the freemarker template <code>ftlName</code> and the supporting data
* found in <code>map</code>, generate a UTF-8 encoded HTML represenation.
* using a standard juxta layout as the base template.
*
* @param ftlName name of the content template
* @param map map of name-value pairs that will be used to fill in the template
* @return
*/
public Representation toHtmlRepresentation( final String ftlName, Map<String,Object> map) {
return toHtmlRepresentation(ftlName, map, true);
}
/**
* Using the freemarker template <code>ftlName</code> and the supporting data
* found in <code>map</code>, generate a UTF-8 encoded HTML represenation.
* If the <code>useLayout</code> flag is true, this representation will be
* embedded as content within the base juxta layout. If false, it will
* stand on its own.
*
* @param ftlName name of the content template
* @param map map of name-value pairs that will be used to fill in the template
* @param useLayout Flag to indicate if this template will be embeddded within
* the standard juxta layout.
* @return
*/
public Representation toHtmlRepresentation( final String ftlName, Map<String,Object> map, boolean useLayout ) {
return toHtmlRepresentation(ftlName, map, useLayout, true);
}
public Representation toHtmlRepresentation( final String ftlName, Map<String,Object> map, boolean useLayout, boolean gzip ) {
Representation ftlRepresentation = null;
if ( useLayout == false ) {
ftlRepresentation = getTemplate(ftlName);
} else {
ftlRepresentation = getTemplate("layout.ftl");
map.put("content", "/"+ftlName);
map.put("embedded", this.embedded);
if ( map.containsKey("workspace") == false) {
map.put("workspace", this.workspace.getName().toLowerCase().trim());
map.put("workspaceId", this.workspace.getId());
map.put("workspaceCount", this.workspaceDao.getWorkspaceCount());
map.put("workspaces", this.workspaceDao.list());
}
}
map.put("baseUrl", getRequest().getHostRef().toString()+"/juxta");
Representation r = new TemplateRepresentation(ftlRepresentation, FTL_CONFIG, map, MediaType.TEXT_HTML);
if ( this.zipSupported && gzip ) {
return new EncodeRepresentation(Encoding.GZIP, r);
}
return r;
}
private final Representation getTemplate( String ftlName ) {
return new ClientResource(FTL_ROOT+ftlName).get();
}
}
|
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations;
import org.giddap.dreamfactory.leetcode.onlinejudge.MinStack;
import java.util.ArrayDeque;
import java.util.Deque;
/**
*
*/
public class MinStackImpl implements MinStack {
private Deque<IntergerAndMin> nums = new ArrayDeque<IntergerAndMin>();
public void push(int x) {
if (nums.size() > 0) {
nums.offerFirst(new IntergerAndMin(x, Math.min(x, nums.peekFirst().min)));
} else {
nums.offerFirst(new IntergerAndMin(x, x));
}
}
public void pop() {
verifyNotEmpty();
nums.pollFirst();
}
public int top() {
verifyNotEmpty();
return nums.peekFirst().num;
}
public int getMin() {
verifyNotEmpty();
return nums.peekFirst().min;
}
private void verifyNotEmpty() {
if (nums.size() == 0) {
throw new IllegalStateException("stack is empty.");
}
}
public static class IntergerAndMin {
int num;
int min;
public IntergerAndMin(final int num, final int min) {
this.num = num;
this.min = min;
}
}
}
|
/** Victor Hugo Vimos T
* victor.vimos@epn.edu.ec
* victor.vimos@wmoos.com **/
package masterWeekThreeAC;
public class LinealSearch {
public void search(int [] arr, int target,boolean goPrint){
for (int guess = 0; guess <arr.length ; guess++) {
if(arr[ guess]==target) {
if(goPrint == true)System.out.println("Element " + target + " is found at pos: " + guess);
return;
}
}
//if here means target is not found
if(goPrint == true)System.out.println("Element " + target + " is not found in array");
}
}
|
package com.mcl.mancala.beans;
import com.mcl.mancala.game.Mechanics;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class GameStateTest {
@Test
public void gameStateBeanTest() {
Mancala mancala = new Mechanics().start();
GameState gameState = new GameState(1L,mancala, false, 2);
assertEquals(1L, gameState.getId());
assertEquals(mancala, gameState.getMancala());
assertEquals(2, gameState.getWinner());
assertFalse(gameState.isGameEnded());
}
}
|
package Chess;
import Chess.Pieces.Piece;
public class Box {
private int row;
private int col;
private Piece piece;
Box(int row, int col, Piece piece) {
this.row = row;
this.col = col;
this.piece = piece;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
public Piece getPiece() {
return piece;
}
public void setPiece(Piece piece) {
this.piece = piece;
}
}
|
package com.github.trang.druid.example.mybatis.model;
import java.io.Serializable;
import lombok.Data;
/**
* City
*
* @author trang
*/
@Data
public class City implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String state;
private String country;
} |
package com.snakeladdersimulator;
public class SnakeLadderSimulator {
public static void main(String[] args) {
int position1 = 0, position2 = 0, role1=0, role2=0;
while(position1<100 && position2<100)
{
int roll1 = (int)(Math.random()*(6-1))+1;
int roll2 = (int)(Math.random()*(6-1))+1;
//System.out.println("\nNumber after rolling die: " + roll);
int turn1 = (int)(Math.random() * 10 ) % 3;
int turn2 = (int)(Math.random() * 10 ) % 3;
switch (turn1)
{
case 1:
System.out.println("Ladder!!");
if(!((position1+roll1)>100))
{ position1 += roll1;
while(turn1 == 1)
{
turn1 = (int)(Math.random() * 10 ) % 3;
switch (turn1)
{
case 1:
System.out.println("Ladder!!");
if(!((position1+roll1)>100))
position1 +=roll1;
else
System.out.println("No turn");
break;
case 2:
System.out.println("Snake!!");
position1 -=roll1;
if(position1<0)
position1 = 0;
break;
default:
System.out.println("No Play!!");
}
}
}
else
System.out.println("No turn");
break;
case 2:
System.out.println("Snake!!");
position1 -=roll1;
if(position1<0)
position1 = 0;
break;
default:
System.out.println("No Play!!");
}
role1++;
System.out.println("Position of the player1: " + position1);
switch (turn2) {
case 1:
System.out.println("Ladder!!");
if(!((position2+roll2)>100))
{position2 +=roll2;
while(turn2 == 1)
{
turn2 = (int)(Math.random() * 10 ) % 3;
switch (turn2) {
case 1:
System.out.println("Ladder!!");
if(!((position2+roll2)>100))
position2 +=roll2;
else
System.out.println("No turn");
break;
case 2:
System.out.println("Snake!!");
position2 -=roll2;
if(position2<0)
position2 = 0;
break;
default:
System.out.println("No Play!!");
}
}
}
else
System.out.println("No turn");
break;
case 2:
System.out.println("Snake!!");
position2 -=roll2;
if(position2<0)
position2 = 0;
break;
default:
System.out.println("No Play!!");
}
role2++;
System.out.println("Position of the player2: " + position2);
}
if (position1<position2)
{
System.out.println("\n Player2 wins the game!!!");
System.out.println(" \n Number of roles to win: " + role2);
}
else
{
System.out.println("\n Player1 wins the game!!!");
System.out.println(" \n Number of roles to win: " + role1);
}
}
}
|
package com.mustafayuksel.notificationapplication.service;
import com.mustafayuksel.notificationapplication.request.PushNotificationRequest;
import com.mustafayuksel.notificationapplication.response.BaseResponse;
public interface PushService {
BaseResponse pushNotificationToAllUsers(PushNotificationRequest request);
} |
// Decompiled by Jad v1.5.7d. Copyright 2000 Pavel Kouznetsov.
// Jad home page: http:// www.geocities.com/SiliconValley/Bridge/8617/jad.html
// Decompiler options: packimports(3)
// Source File Name: MultipartParser.java
package com.ziaan.scorm.multi.multipart;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
// Referenced classes of package com.ziaan.scorm.multi.multipart:
// BufferedServletInputStream, LimitedServletInputStream, ParamPart, FilePart,
// Part
public class MultipartParser
{
public MultipartParser(HttpServletRequest httpservletrequest, int i)
throws IOException
{
this(httpservletrequest, i, true, true);
}
public MultipartParser(HttpServletRequest httpservletrequest, int i, boolean flag, boolean flag1)
throws IOException
{
buf = new byte[8192];
encoding = DEFAULT_ENCODING;
String s = null;
String s1 = httpservletrequest.getHeader("Content-Type");
String s2 = httpservletrequest.getContentType();
if ( s1 == null && s2 != null )
s = s2;
else
if ( s2 == null && s1 != null )
s = s1;
else
if ( s1 != null && s2 != null )
s = s1.length() <= s2.length() ? s2 : s1;
if ( s == null || !s.toLowerCase().startsWith("multipart/form-data"))
throw new IOException("Posted content type isn't multipart/form-data");
int j = httpservletrequest.getContentLength();
if ( j > i)
throw new IOException("Posted content length of " + j + " exceeds limit of " + i);
String s3 = extractBoundary(s);
if ( s3 == null )
throw new IOException("Separation boundary was not specified");
Object obj = httpservletrequest.getInputStream();
if ( flag)
obj = new BufferedServletInputStream(((ServletInputStream) (obj)));
if ( flag1)
obj = new LimitedServletInputStream(((ServletInputStream) (obj)), j);
in = ((ServletInputStream) (obj));
boundary = s3;
String s4 = readLine();
if ( s4 == null )
throw new IOException("Corrupt form data: premature ending");
if ( !s4.startsWith(s3))
throw new IOException("Corrupt form data: no leading boundary: " + s4 + " != " + s3);
else
return;
}
public void setEncoding(String s)
{
encoding = s;
}
public Part readNextPart()
throws IOException
{
if ( lastFilePart != null )
{
lastFilePart.getInputStream().close();
lastFilePart = null;
}
Vector vector = new Vector();
String s = readLine();
if ( s == null )
return null;
if ( s.length() == 0)
return null;
String s1;
for ( ; s != null && s.length() > 0; s = s1)
{
s1 = null;
boolean flag = true;
while ( flag)
{
s1 = readLine();
if ( s1 != null && (s1.startsWith(" ") || s1.startsWith("\t")))
s = s + s1;
else
flag = false;
}
vector.addElement(s);
}
if ( s == null )
return null;
String s2 = null;
String s3 = null;
String s4 = null;
String s5 = "text/plain";
for ( Enumeration enumeration = vector.elements(); enumeration.hasMoreElements();)
{
String s6 = (String)enumeration.nextElement();
if ( s6.toLowerCase().startsWith("content-disposition:"))
{
String as[] = extractDispositionInfo(s6);
s2 = as[1];
s3 = as[2];
s4 = as[3];
} else
if ( s6.toLowerCase().startsWith("content-type:"))
{
String s7 = extractContentType(s6);
if ( s7 != null )
s5 = s7;
}
}
if ( s3 == null )
return new ParamPart(s2, in, boundary, encoding);
if ( s3.equals(""))
s3 = null;
lastFilePart = new FilePart(s2, in, boundary, s5, s3, s4);
return lastFilePart;
}
private String extractBoundary(String s)
{
int i = s.lastIndexOf("boundary=");
if ( i == -1)
return null;
String s1 = s.substring(i + 9);
if ( s1.charAt(0) == '"')
{
int j = s1.lastIndexOf(34);
s1 = s1.substring(1, j);
}
s1 = "--" + s1;
return s1;
}
private String[] extractDispositionInfo(String s)
throws IOException
{
String as[] = new String[4];
String s1 = s;
s = s1.toLowerCase();
int i = s.indexOf("content-disposition: ");
int j = s.indexOf(";");
if ( i == -1 || j == -1)
throw new IOException("Content disposition corrupt: " + s1);
String s2 = s.substring(i + 21, j);
if ( !s2.equals("form-data"))
throw new IOException("Invalid content disposition: " + s2);
i = s.indexOf("name=\"", j);
j = s.indexOf("\"", i + 7);
if ( i == -1 || j == -1)
throw new IOException("Content disposition corrupt: " + s1);
String s3 = s1.substring(i + 6, j);
String s4 = null;
String s5 = null;
i = s.indexOf("filename=\"", j + 2);
j = s.indexOf("\"", i + 10);
if ( i != -1 && j != -1)
{
s4 = s1.substring(i + 10, j);
s5 = s4;
int k = Math.max(s4.lastIndexOf(47), s4.lastIndexOf(92));
if ( k > -1)
s4 = s4.substring(k + 1);
}
as[0] = s2;
as[1] = s3;
as[2] = s4;
as[3] = s5;
return as;
}
private String extractContentType(String s)
throws IOException
{
String s1 = null;
String s2 = s;
s = s2.toLowerCase();
if ( s.startsWith("content-type"))
{
int i = s.indexOf(" ");
if ( i == -1)
throw new IOException("Content type corrupt: " + s2);
s1 = s.substring(i + 1);
} else
if ( s.length() != 0)
throw new IOException("Malformed line after disposition: " + s2);
return s1;
}
private String readLine()
throws IOException
{
StringBuffer stringbuffer = new StringBuffer();
int i;
do
{
i = in.readLine(buf, 0, buf.length);
if ( i != -1)
stringbuffer.append(new String(buf, 0, i, encoding));
} while ( i == buf.length);
if ( stringbuffer.length() == 0)
return null;
int j = stringbuffer.length();
if ( j >= 2 && stringbuffer.charAt(j - 2) == '\r')
stringbuffer.setLength(j - 2);
else
if ( j >= 1 && stringbuffer.charAt(j - 1) == '\n')
stringbuffer.setLength(j - 1);
return stringbuffer.toString();
}
private ServletInputStream in;
private String boundary;
private FilePart lastFilePart;
private byte buf[];
private static String DEFAULT_ENCODING = "ISO-8859-1";
private String encoding;
}
|
/*
* 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 soritng;
import java.util.Random;
/**
*
* @author eliot
*/
public class BubbleSort {
public static long startTime;
public static long endTime;
public static long timeElapsed;
public static void starter() {
int[] list= numberMaker();
System.out.println("Sorted List");
bubbleSort(list);
for (int i=0; i<list.length; i++)
System.out.println(list[i]);
measureTime();
}// cloes main
public static void bubbleSort(int[] list) {
boolean needNextPass=true;
for(int k=1; k<list.length && needNextPass; k++) {
needNextPass = false;
for (int i=0; i< list.length -k; i++)
if (list[i] > list[i+1]) {
int temp =list[i];
list[i] = list[i+1];
list[i+1] = temp;
needNextPass =true;
}// close if
}//close for
endTime=System.currentTimeMillis();
}// close bubble sort
public static int[] numberMaker() {
Random r = new Random();
int sortList[] = new int[10000];
startTime= System.currentTimeMillis();
for (int i=0; i<sortList.length; i++) {
sortList[i]= r.nextInt(100000);
}// close for
return sortList;
}// close numberMaker
public static void measureTime() {
timeElapsed = (endTime - startTime);
if (timeElapsed < 1000) {
System.out.println("Time Taken " + timeElapsed + " Milliseconds");
} else if (timeElapsed < 60000) {
timeElapsed= timeElapsed/1000;
System.out.println("Time Taken " + timeElapsed + "Seconds");
}else if (timeElapsed < 3600000) {
timeElapsed = timeElapsed /1000 /60;
System.out.println("Time Taken " + timeElapsed + "Minutes ");
}// close if
}// close measure
}// close class
|
package com.cloubiot.buddyWAPI.rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.cloubiot.buddyWAPI.base.SuccessResponse;
import com.cloubiot.buddyWAPI.common.CloubiotLogging;
import com.cloubiot.buddyWAPI.model.dbentity.User;
import com.cloubiot.buddyWAPI.model.user.ExistsValueRequest;
import com.cloubiot.buddyWAPI.model.user.LoginRequest;
import com.cloubiot.buddyWAPI.model.user.UserResponse;
import com.cloubiot.buddyWAPI.service.UserService;
import com.cloubiot.buddyWAPI.util.JSONUtil;
import com.cloubiot.buddyWAPI.util.SecureData;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(method = RequestMethod.POST, value="/addUpdateUser")
public SuccessResponse addUpdateUser(@RequestBody User request) {
SuccessResponse response = new SuccessResponse();
try {
if(request.getFirstName() != null && request.getLanguageId() != null && request.getLastName() != null
&& request.getUserName() != null && request.getEmail() != null) {
SecureData sd = new SecureData();
String encryptedPassword = sd.encrypt(request.getPassword());
request.setPassword(encryptedPassword);
userService.saveUser(request);
}
else {
response.setSuccess(false);
response.setStatusMessage("Invalid Data");
}
CloubiotLogging.logInfo(getClass(), "Add Update User");
}
catch(Exception e) {
response.setSuccess(false);
CloubiotLogging.logError(getClass(), "AddUpdate User Fails", e);
}
return response;
}
@RequestMapping(method = RequestMethod.POST, value="/login")
public UserResponse accessLogin(@RequestBody LoginRequest request) {
UserResponse response = new UserResponse();
try {
SecureData sd = new SecureData();
String decryptPassword = sd.encrypt(request.getPassword());
User user = userService.accessLogin(request.getUserName(), decryptPassword);
System.out.println("User "+JSONUtil.toJson(user));
if(user == null) {
response.setSuccess(false);
response.setStatusMessage("Login Failed");
}
CloubiotLogging.logInfo(getClass(), "Login Success");
}
catch(Exception e) {
response.setSuccess(false);
CloubiotLogging.logError(getClass(), "Login Fails", e);
}
return response;
}
@RequestMapping(method = RequestMethod.POST, value="/emailExists")
public SuccessResponse emailExists(@RequestBody ExistsValueRequest request) {
SuccessResponse response = new SuccessResponse();
try {
User user = userService.emailIdExists(request.getEmail());
if(user == null) {
response.setSuccess(false);
response.setStatusMessage("Email Not Exist");
}
else
response.setStatusMessage("Email Exists");
CloubiotLogging.logInfo(getClass(), "Email Exists");
}
catch(Exception e) {
response.setSuccess(false);
CloubiotLogging.logError(getClass(), "Email Exists Fails", e);
}
return response;
}
}
|
package com.touchtrip.admin.controller;
import java.io.IOException;
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 com.touchtrip.admin.model.service.AdminService;
import com.touchtrip.admin.model.vo.Admin;
/**
* Servlet implementation class AdminHome
*/
@WebServlet("/countMember.ad")
public class AdminHome extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AdminHome() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AdminService service = new AdminService();
Admin a = service.countMemberJoin();
int result = service.countMemberWeek();
System.out.println(result);
request.setAttribute("countMember", a);
request.setAttribute("weekJoin", result);
// response.sendRedirect("views/admin/admin.jsp");
request.getRequestDispatcher("views/admin/admin.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Scanner;
public class Exercise6 {
private SimpleDateFormat dateFormat;
private Calendar calendar;
public Exercise6()
{
dateFormat = new SimpleDateFormat ("dd.MM.yyyy");
Calendar calendar = Calendar.getInstance();
}
public void calc()
{
Calendar calendar = Calendar.getInstance();
System.out.println("Today: " + dateFormat.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("Tomorrow: " + dateFormat.format(calendar.getTime()));
calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -1);
System.out.println("Yesterday: " + dateFormat.format(calendar.getTime()));
}
}
|
package com.beike.dao.unionpage;
import java.util.List;
import java.util.Map;
public interface UnionKWDao {
/**
*
* janwen
* @param begin
* @return seo关键字(使用中)
*
*/
public List<String> getUsedKW(String isused,Long begin);
/**
*
* janwen
* @param begin
* @return seo关键字(未使用中)
*
*/
public List<String> getUnUsedKW(Long begin);
/**
*
* janwen
* @param isused 0/1
* @return kw总数
*
*/
public Long getKWCount(String isused);
/**
*
* janwen
* @return seo词库最后更新时间
*
*/
public String getKWUpdateTime();
/**
* @date 2012-5-17
* @description:通过关键词Id查询关键词
* @param id
* @return String
* @throws
*/
public String getKeyWordById(int id);
/**
* @date 2012-5-18
* @description:查询所有的关键词信息,
* @return List<Map<String,Object>>
* @throws
*/
public List<Map<String,Object>> getAllKeyWordMsg();
/**
* @date 2012-5-21
* @description:通过关键词查询相应的关键词信息
* @param keyWord
* @param count 查询关键词数量
* @return List<Map<String,String>>
* @throws
*/
public List<Map<String,String>> getMsgByKeyWord(String keyWord,int count);
}
|
package peace.developer.serj.photoloader.models;
import java.util.List;
public class Album {
private int id;
private List<Photo>photoLinks;
}
|
package com.trump.auction.back.auctionProd.dao.read;
import com.trump.auction.back.auctionProd.model.AuctionBidInfo;
import org.springframework.stereotype.Repository;
@Repository
public interface AuctionBidInfoDao {
int deleteByPrimaryKey(Integer id);
int insert(AuctionBidInfo record);
int insertSelective(AuctionBidInfo record);
AuctionBidInfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(AuctionBidInfo record);
int updateByPrimaryKey(AuctionBidInfo record);
} |
package kr.ac.kopo.day05;
import java.util.Arrays;
public class ArrayMain06 {
public static void main(String[] args) {
int[] a = {10, 20, 30};
int[] b;
b = new int[a.length];
//함수 사용!!
System.arraycopy(a, 0, b, 0, a.length);
System.out.println("a : " + Arrays.toString(a));
System.out.println("b : " + Arrays.toString(b));
// 두 배열 합쳐서 c배열 만들기
int[] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length); //시작점 조절하는 거 주의해!
System.out.println("c : " + Arrays.toString(c));
// 유용하긴하네~
}
}
|
/**
* @author TATTYPLAY
* @date Jul 3, 2018
* @created 12:33:38 AM
* @filename ItemStackET.java
* @project Reporter
* @package com.tattyhost.reporter
* @copyright 2018
*/
package com.tattyhost.reporter;
import org.bukkit.Material;
/**
*
*/
public class ItemStackET extends ItemStackE{
private EItemsBanTimeUnits time;
/**
* @param name
* @param material
* @param metaDataID
* @param amount
* @param slot
* @param time
*/
public ItemStackET(String name, int material, int metaDataID, int amount, int slot, EItemsBanTimeUnits time) {
super(name, material, metaDataID, amount, slot);
this.time = time;
}
/**
* @param name
* @param material
* @param metaDataID
* @param amount
* @param slot
* @param time
*/
public ItemStackET(String name, Material material, int metaDataID, int amount, int slot, EItemsBanTimeUnits time) {
super(name, material, metaDataID, amount, slot);
this.time = time;
}
/**
* @return the time
*/
public long getTime() {
return time.getTime();
}
/**
* @return
*/
public EItemsBanTimeUnits getTimeUnit() {
return time;
}
}
|
package com.github.dvdme.DarkSkyJava;
public interface WeatherDataPoint {
boolean exists();
String time();
long timestamp();
String summary();
String icon();
String sunriseTime();
String sunsetTime();
Double precipIntensity();
Double precipIntensityMax();
String precipIntensityMaxTime();
Double precipProbability();
String precipType();
Double precipAccumulation();
Double temperature();
Double temperatureError();
Double temperatureMin();
Double temperatureMinError();
String temperatureMinTime();
Double temperatureMax();
Double temperatureMaxError();
String temperatureMaxTime();
Double apparentTemperature();
Double apparentTemperatureMin();
String apparentTemperatureMinTime();
Double apparentTemperatureMax();
String apparentTemperatureMaxTime();
Double dewPoint();
Double dewPointError();
Double windSpeed();
Double windSpeedError();
Double windBearing();
Double windBearingError();
Double cloudCover();
Double cloudCoverError();
Double humidity();
Double humidityError();
Double pressure();
Double pressureError();
Double visibility();
Double visibilityError();
Double ozone();
Double nearestStormBearing();
Double nearestStormDistance();
Double moonPhase();
}
|
package de.cuuky.varo.player.stats.stat.offlinevillager;
import java.util.ArrayList;
import org.bukkit.Bukkit;
import org.bukkit.Difficulty;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Zombie;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import de.cuuky.varo.Main;
import de.cuuky.varo.config.messages.ConfigMessages;
import de.cuuky.varo.logger.logger.EventLogger.LogType;
import de.cuuky.varo.player.VaroPlayer;
import de.cuuky.varo.player.event.BukkitEventType;
import de.cuuky.varo.player.stats.stat.inventory.InventoryBackup;
import de.cuuky.varo.serialize.identifier.VaroSerializeField;
import de.cuuky.varo.serialize.identifier.VaroSerializeable;
import de.cuuky.varo.version.BukkitVersion;
import de.cuuky.varo.version.VersionUtils;
public class OfflineVillager implements VaroSerializeable {
private static ArrayList<OfflineVillager> villagers;
private static Class<?> nbttagClass;
static {
villagers = new ArrayList<>();
Bukkit.getPluginManager().registerEvents(new VillagerListener(), Main.getInstance());
try {
nbttagClass = Class.forName(VersionUtils.getNmsClass() + ".NBTTagCompound");
} catch(Exception | Error e) {
e.printStackTrace();
}
}
@VaroSerializeField(path = "villagerLocation")
private Location location;
@VaroSerializeField(path = "lastInventory")
private InventoryBackup backup;
private Zombie zombie;
private Entity entity;
private VaroPlayer vp;
public OfflineVillager() {
villagers.add(this);
}
public OfflineVillager(VaroPlayer vp, Location location) {
this.backup = new InventoryBackup(vp);
this.location = location;
this.vp = vp;
create();
villagers.add(this);
}
@Override
public void onDeserializeEnd() {
this.vp = backup.getVaroPlayer();
if(vp == null)
remove();
for(Entity ent : location.getWorld().getEntities())
if(ent.getType().toString().contains("ZOMBIE")) {
Zombie zombie = (Zombie) ent;
if(zombie.isVillager() && zombie.getCustomName() != null && zombie.getCustomName().equals("§c" + vp.getName())) {
this.zombie = (Zombie) ent;
this.entity = ent;
}
}
if(zombie == null)
create();
}
@Override
public void onSerializeStart() {}
public void create() {
Bukkit.getScheduler().scheduleSyncDelayedTask(Main.getInstance(), new Runnable() {
@Override
public void run() {
if(location.getWorld().getDifficulty() == Difficulty.PEACEFUL)
location.getWorld().setDifficulty(Difficulty.EASY);
EntityType type = VersionUtils.getVersion().isHigherThan(BukkitVersion.ONE_9) ? EntityType.valueOf("ZOMBIE_VILLAGER") : EntityType.ZOMBIE;
zombie = (Zombie) location.getWorld().spawnEntity(location, type);
zombie.setCustomName("§c" + vp.getName());
zombie.setCustomNameVisible(true);
if(!VersionUtils.getVersion().isHigherThan(BukkitVersion.ONE_9))
zombie.setVillager(true);
freezeVillager();
entity = zombie;
}
}, 1);
}
private void freezeVillager() {
if(VersionUtils.getVersion() == BukkitVersion.ONE_7) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(Main.getInstance(), new Runnable() {
@Override
public void run() {
zombie.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 1000000, 255));
}
}, 0, 1000000 * 20);
} else
try {
Object nmsEn = zombie.getClass().getMethod("getHandle").invoke(zombie);
Object compound = nbttagClass.newInstance();
nmsEn.getClass().getMethod("c", compound.getClass()).invoke(nmsEn, compound);
compound.getClass().getDeclaredMethod("setByte", String.class, byte.class).invoke(compound, "NoAI", (byte) 1);
nmsEn.getClass().getMethod("f", nbttagClass).invoke(nmsEn, compound);
} catch(Exception e) {
e.printStackTrace();
}
}
public void remove() {
if(zombie != null)
zombie.remove();
villagers.remove(this);
}
public Zombie getZombie() {
return zombie;
}
public VaroPlayer getVp() {
return vp;
}
public Entity getEntity() {
return entity;
}
public void kill(VaroPlayer killer) {
if(zombie != null)
zombie.getWorld().strikeLightningEffect(zombie.getLocation());
remove();
for(ItemStack it : backup.getInventory().getInventory().getContents())
if(it != null && it.getType() != Material.AIR)
location.getWorld().dropItemNaturally(location, it);
for(ItemStack it : backup.getArmor())
if(it != null && it.getType() != Material.AIR)
location.getWorld().dropItemNaturally(location, it);
Main.getLoggerMaster().getEventLogger().println(LogType.DEATH, ConfigMessages.ALERT_DISCORD_KILL.getValue().replace("%death%", vp.getName()).replace("%killer%", killer.getName()));
Bukkit.broadcastMessage(ConfigMessages.DEATH_KILLED_BY.getValue().replaceAll("%death%", vp.getName()).replaceAll("%killer%", killer.getName()));
killer.onEvent(BukkitEventType.KILL);
vp.onEvent(BukkitEventType.KILLED);
}
public static OfflineVillager getVillager(Entity entity) {
for(OfflineVillager vill : villagers) {
if(!entity.equals(vill.getEntity()))
continue;
return vill;
}
return null;
}
} |
package pp.model.enums;
public enum BattleType {
BATTLE(1, "battlesapp"),
DUEL(2, "duelsapp"),
SURVIVE(4, "survivalapp"),
EXAM(5, "exam");
private int id;
private String act;
private BattleType(int id, String act) {
this.id = id;
this.act = act;
}
public int getId() {
return id;
}
public String getAct() {
return act;
}
}
|
package lxy.liying.circletodo.ui;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.EditText;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import lxy.liying.circletodo.R;
import lxy.liying.circletodo.app.App;
import lxy.liying.circletodo.utils.ErrorCodes;
import lxy.liying.circletodo.utils.StringUtils;
public class UpdatePasswordActivity extends BaseActivity {
private EditText etCurrPass, etNewPass1, etNewPass2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_password);
actionBarNavigator();
etCurrPass = (EditText) findViewById(R.id.etCurrPass);
etNewPass1 = (EditText) findViewById(R.id.etNewPass1);
etNewPass2 = (EditText) findViewById(R.id.etNewPass2);
}
/**
* 更改密码
*
* @param view
*/
public void changePassword(View view) {
String currPass = etCurrPass.getText().toString();
String newPass1 = etNewPass1.getText().toString();
String newPass2 = etNewPass2.getText().toString();
if ("".equals(currPass)) {
App.getInstance().showToast("现密码不能为空。");
return;
} else if ("".equals(newPass1) || "".equals(newPass2)) {
App.getInstance().showToast("新密码不能为空。");
return;
} else if (!newPass1.equals(newPass2)) {
App.getInstance().showToast("两次输入的新密码不一致。");
return;
}
// 加密密码
currPass = StringUtils.encryptToSHA1(currPass);
newPass1 = StringUtils.encryptToSHA1(newPass1);
System.out.println("currPass = " + currPass + ", newPass = " + newPass1);
BmobUser.updateCurrentUserPassword(currPass, newPass1, new UpdateListener() {
@Override
public void done(BmobException e) {
if (e == null) {
AlertDialog.Builder builder = App.getAlertDialogBuilder(UpdatePasswordActivity.this);
builder.setTitle("修改成功");
builder.setMessage("密码修改成功,可以用新密码进行登录啦。");
builder.setPositiveButton("知道了", null);
builder.create().show();
} else {
showErrorDialog(UpdatePasswordActivity.this, "修改失败。\n" +
ErrorCodes.errorMsg.get(e.getErrorCode()), false);
}
}
});
}
}
|
/* $Id$ */
package djudge.utils;
import java.util.HashMap;
import org.apache.log4j.Logger;
public abstract class CachedObjectsSet<K, V>
{
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(CachedObjectsSet.class);
protected final long updateInterval;
private HashMap<K, CachedObject<V> > objects = new HashMap<K, CachedObject<V> >();
public CachedObjectsSet(long updateInterval)
{
this.updateInterval = updateInterval;
}
public abstract CachedObject<V> getObjectForKey(K key);
public synchronized V getData(K key)
{
CachedObject<V> cachedObject = objects.get(key);
if (null == cachedObject)
{
cachedObject = getObjectForKey(key);
objects.put(key, cachedObject);
}
return cachedObject.getData();
}
}
|
package com.beta.rulestrategy;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
class RuleStrategyTest {
@Autowired
private RuleFactory ruleFactory;
@BeforeEach
void setUp() {
}
@Test
@DisplayName("Test reverse rule")
void testRuleOne() {
Strategy strategy = ruleFactory.getRuleInstance(1);
assertEquals(strategy.applyRule("manish"), "hsinam");
}
@Test
@DisplayName("Test hash rule")
void testRuleTwo() {
Strategy strategy = ruleFactory.getRuleInstance(2);
assertEquals(strategy.applyRule("manish"), "59c95189ac895fcc1c6e1c38d067e244");
}
@Test
@DisplayName("Test hash rule")
void testRuleTwoOne() {
Strategy strategy = ruleFactory.getRuleInstance(1);
String firstConversion = strategy.applyRule("manish");
String secondConversion = ruleFactory.getRuleInstance(2).applyRule(firstConversion);
assertEquals(secondConversion, "91fab82f2ae4decb76fc4d4c809d0421");
}
}
|
package edu.uw.cwds.predictionservice;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
public class ServiceController {
@RequestMapping(value="/{name}", method=RequestMethod.GET)
public @ResponseBody double predict(@PathVariable("name") String model, @RequestParam("values") String values) throws Exception {
return ModelRepository.get(model).predict(values);
}
}
|
package nl.topicus.wqplot.components.plugins;
/**
* @author Ernesto Reinaldo Barreiro
*/
public class JQPlotBarRenderer extends Renderer
{
private static final JQPlotBarRenderer INSTANCE = new JQPlotBarRenderer();
private JQPlotBarRenderer()
{
super("$.jqplot.BarRenderer", JQPlotBarRendererResourceReference.get());
}
public static JQPlotBarRenderer get()
{
return INSTANCE;
}
}
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class ServiceLane
{
private int[] freeway;
public ServiceLane(int[] freeway)
{
this.freeway = freeway;
}
public int calculateLargestVehicleType(int entry, int exit)
{
if (entry == 1)
return 1;
int largestVehicle = 3;
for(int i = entry; i <= exit; i++)
{
if(freeway[i] < largestVehicle)
largestVehicle = freeway[i];
}
return largestVehicle;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
int[] freeway = new int[s.nextInt()];
int testCases = s.nextInt();
//Populate the array with widths of service lanes
for(int i = 0; i < freeway.length; i++)
freeway[i] = s.nextInt();
ServiceLane serviceLane = new ServiceLane(freeway);
for(int i = 0; i < testCases; i++)
{
int entry = s.nextInt();
int exit = s.nextInt();
System.out.println(serviceLane.calculateLargestVehicleType(entry, exit));
}
}
}
|
package com.tscloud.common.framework;
import java.util.ArrayList;
import java.util.List;
/**
* EnvConstants.java
*/
public final class Constants {
public final class Env {
private Env() {
}
public static final String BASE_HOME = "configs/";
public static final String BASE_CONF = "base.conf";
}
public final class RestPathPrefix {
public static final String CONSOLE = "console/";
public static final String GATHER = "gather/";
public static final String DATABASE = "database/";
public static final String GISSERVER = "gisserver/";
public static final String ETL = "etl/";
public static final String SERVICES = "services/";
public static final String SYSTEM = "system/";
public static final String DATANODE = "datanode/";
public static final String WEBCRAWLER = "webcrawler/";
//ESB常量
public static final String ESB = "esb/";
//portal门户常量
public static final String PORTAL = "portal/";
//内网门户
public static final String IN_PORTAL = "inportal/";
//外网门户常量
public static final String OUT_PORTAL = "outportal/";
public static final String WORKFLOW = "workflow/";
public static final String WORKFLOW_SERVER = "workflowServer/";
public static final String FILEGATHER = "filegather/";
public static final String MANAGER = "manager/";
public static final String CA = "ca/";
public static final String GISMANAGER = "gismanager/";
}
/**
* 服务标识
*/
public enum ServiceName {
CONSOLE//,ETL,ESB,DATABASE,ISWAP;
}
/**
* 引擎状态
*/
public final class engine {
public static final String ENGINE_TYPE_DISABLE = "0";
public static final String ENGINE_TYPE_ENABLE = "1";
}
/**
* 流程状态
*/
public final class workflow {
@Deprecated
public static final String WORKFLOW_STOP_STATUS = "0";
/*正在运行*/
public static final String RUN_STATUS_RUNNING = "0";
/*运行成功*/
public static final String RUN_STATUS_SUCCEED = "1";
/*运行失败*/
public static final String RUN_STATUS_ERROR = "-1";
/*部署状态*/
public static final String DEPLOY_STATUS = "1";
/*取消部署*/
public static final String UN_DEPLOY_STATUS = "0";
/*流程外部传入参数*/
public static final String WORKFLOW_MSG = "msg";
/**
* 流程作业监听任务在指定的节点机上执行
*/
public static final String WORKFLOW_LISTENINGCODE_IP = "workflow_listeningcode_ip";
/**
* 任务分配的key值
*/
public static final String WORKFLOW_OPERATION_TASK_KEY = "workflow_operation_task_key";
/**
* 流程任务key
*/
public static final String TOTAL_LIST_KEY = "total_list_key";
/**
* 数据包描述
*/
public static final String DATA_PACKAGE_DESCRIBE = "data_package_describe";
/**
* 是否指定ip执行
*/
public static final String IS_LOCAL_IP = "is_local_ip";
/**
* 其他参数
*/
public static final String OTHER_KEY = "_other_key";
/**
* 增量字段名称
*/
public static final String WF_INCRE_NAME = "_wf_increment_name";
/**
* 增量字段值
*/
public static final String WF_INCRE_VAL = "_wf_increment_val";
public static final String INCRE_VAL_BEGIN_DATE = "_increment_begin_date";
public static final String INCRE_VAL_END_DATE = "_increment_end_date";
}
/**
* 插件唯一标识符
*/
public final class plugin {
/*输入数据源*/
public static final String DB_INSOURCE = "inDS_conn";
/*输出数据源*/
public static final String DB_OUTSOURCE = "outDS_conn";
/*流程插件流转中用以存放请求参数的标识*/
public static final String DB_PARAMS = "_DB_PARAMS";
/*流程id标示*/
public static final String WORK_FLOW_ID = "_WORK_FLOW_ID";
/*流程code*/
public static final String WORK_FLOW_CODE_KEY = "WORK_FLOW_CODE";
/* 用来标识插件和fourinone之间的数据*/
public static final String WARE_HOUSE = "_WARE_HOUSE";
/* 标识引擎列表 */
public static final String ENGINE_LIST_TAG = "_ENGINE_LIST";
/* 调用服务,反馈的数据结果集*/
public static final String SERVICE_DATA_RESULT = "_DATA_RESULT";
/* 流程运行时,用于关联数据源的key */
public static final String DATA_SOURCE_KEY = "_DATA_SOURCE_KEY";
public static final String ENGINE_KEY = "_ENGINE_KEY";
/*-------------------------------流程运行调用插件统一参数设置---------------------------*/
/*参数统一调用content key*/
public static final String PLUG_CONTENT = "PLUG_CONTENT";
/*参数统一调用的key 即插件类型*/
public static final String PLUG_TYPE_KEY = "PLUG_TYPE_KEY";
/**
* -------------------------- db plugin start------------------------------------
*/
/*DB_INSERT 插件*/
public static final String PLUG_DB_INSERT = "db_insert ";
/*DB_UPSert 插件*/
public static final String PLUG_DB_UPSERT = "db_upsert";
/*GIS数据同步 插件*/
public static final String PLUG_GIS_DB_SYNC = "gis_db_sync";
public static final String PLUG_EXCEL_DIR_IMPORT = "excel_import";
/*DB_SELECT 插件*/
public static final String PLUG_DB_QUERY = "db_query";
/*DB_COUNT 插件*/
public static final String PLUG_DB_COUNT = "db_count";
/*日志插件*/
public static final String PLUG_RESULT_LOG = "result_log";
/**-------------------------- db plugin end----------------------------------------*/
/**
* -------------------------- file plugin start------------------------------------
*/
// /*fileCount 插件*/
// public static final String PLUG_FILE_COUNT = "filecount";
/*参数统一调用的key inFileType 文件总数查询类型*/
public static final String PLUG_QUERY_IN_FILE_TYPE_KEY = "inFileType";
/*参数统一调用的key inFileType 文件总数查询类型*/
public static final String PLUG_QUERY_OUT_FILE_TYPE_KEY = "outFileType";
/*参数统一调用的value=1 (查询文件) inFileType 文件总数查询类型*/
public static final String PLUG_QUERY_FILE_VALUE = "1";
/*参数统一调用的value=2 (查询文件目录) inFileType 文件目录总数查询类型*/
public static final String PLUG_QUERY_FILE_DIR_VALUE = "2";
/**-------------------------- file plugin end----------------------------------------*/
/**
* -------------------------- localfile plugin start----------------------------------------
*/
/* 本地文件 总数 */
public static final String PLUG_LOCALFILE_COUNT = "localfile_count";
/* 本地文件 -> bigfile */
public static final String PLUG_LOCALFILE_TO_BIGFILE = "localfile_to_bigfile";
/**-------------------------- localfile plugin end----------------------------------------*/
/**
* -------------------------- bigfile plugin start----------------------------------------
*/
public static final String PLUG_BIGFILE_COUNT = "bigfile_count";
public static final String PLUG_BIGFILE_TO_LOCALFILE = "bigfile_to_localfile";
/**-------------------------- bigfile plugin end----------------------------------------*/
/**
* -------------------------- 数据生产 plugin start----------------------------------------
*/
/* 生产数据导入 创建目录 */
public static final String PLUGIN_DP_IMPORT_CREATE_DIR = "dp_import_create_dir";
/* 生产数据导入 任务分配(远程工程目录) */
public static final String PLUGIN_DP_IMPORT_WINREMOTE_TASK = "dp_import_remote_task";
/* 生产数据导入 大文件系统*/
public static final String PLUGIN_DP_IMPORT_TO_BIGFILE = "dp_import_bigfile";
public static final String PLUGIN_DP_IMPORT_TO_CLOUDDB = "dp_import_clouddb";
public static final String PLUGIN_DP_OBFUSCATE = "dp_obfuscate";
public static final String PLUGIN_DP_DATA_RELEASE = "dp_data_release";
public static final String PLUGIN_DP_DATA_COUNT_QUERY = "dp_data_count_query";
public static final String PLUGIN_DP_DATA_DOWNLOAD = "dp_data_download";
public static final String PLUGIN_DP_DATA_UPLOAD = "dp_data_upload";
public static final String PLUGIN_DP_DATA_DEPLOY_TO_CLOUDDB = "dp_data_delpoy_info_to_clouddb";
public static final String PLUGIN_DP_DATA_READ_LOCAL_DIR = "dp_data_read_local_dir";
public static final String PLUGIN_DP_DATA_CREATE_DIR_TO_SMALLFILE = "dp_data_create_dir_to_smallfile";
public static final String PLUGIN_DP_DATA_BLUR_TO_CLOUDDB = "dp_data_blur_info_to_clouddb";
/* 拼接任务分配 */
public static final String PLUG_DP_STITCHING_TASK = "data_image_stitching_task";
/* 生产数据下发 */
public static final String PLUG_DP_SEND = "data_produce_send";
/* 图片拼接 */
public static final String PLUG_DP_IMAGE_STITCHING = "dp_image_stitching";
/* 图片拼接成果数据上传 */
public static final String PLUG_DP_IMAGE_STITCHING_RESULT = "dp_image_stitching_result";
public static final String PLUG_DP_ACTUAL_BLUR_TASK_ALLOCATE = "dp_actual_blur_task_allocate";
/*实际模糊化任务下发插件*/
public static final String PLUG_DP_ACTUAL_BLUR_DATA_SEND_TO_NODE = "dp_actual_blur_data_send_to_node";
/*实际模糊化执行插件*/
public static final String PLUG_DP_ACTUAL_BLUR = "dp_actual_blur";
/*实际模糊化云数据库存储插件*/
public static final String PLUG_DP_ACTUAL_BLUR_TO_CLOUDB = "dp_actual_blur_to_cloudb";
/**-------------------------- 数据生产 plugin end----------------------------------------*/
/**
* -------------------------- hdfs plugin start------------------------------------
*/
/*HDFS_READ 插件*/
public static final String PLUG_HDFS = "hdfs";
/*文件备份目录名称*/
public static final String PLUG_FILE_BACKUP_DIR = "/backup";
/**
* -------------------------- hdfs plugin end----------------------------------------
*/
// -------------------------- clouddb plugin start------------------------------------//
public static final String PLUGIN_CLOUDDB_UPSERT = "clouddb_upsert";
//-------------------------- clouddb plugin end----------------------------------------//
/**
* -------------------------- tachyon plugin start------------------------------------
*/
/*TACHYON插件*/
public static final String PLUG_TACHYON = "tachyon";
/**
* -------------------------- kafka plugin start------------------------------------
*/
/*KAFKA_SEND 插件*/
public static final String PLUG_KAFKA_SEND_VALUE = "KAFKA_SEND";
/*KAFKA_RECEIVE 插件*/
public static final String PLUG_KAFKA_RECEIVE_VALUE = "KAFKA_RECEIVE";
/**
* -------------------------- redis plugin end----------------------------------------
*/
public static final String PLUGIN_REDIS_COUNT = "redis_count";
/**-------------------------- kafka plugin end----------------------------------------*/
/**
* -------------------------- localfile plugin start------------------------------------
*/
/*localfile 插件*/
public static final String PLUG_LOCAL_FILE = "localfile";
/*文件备份目录名称*/
public static final String PLUG_LOCAL_FILE_BACKUP_DIR = "/backup";
/**-------------------------- localfile plugin end----------------------------------------*/
/**
* -------------------------- winfile plugin start------------------------------------
*/
/*winfile 插件*/
public static final String PLUG_WIN_FILE = "winfile";
/*文件备份目录名称*/
public static final String PLUG_WIN_FILE_BACKUP_DIR = "/backup";
/**-------------------------- winfile plugin end----------------------------------------*/
/**
* -------------------------- pci plugin start------------------------------------
*/
/*pci_autogcp 控制点采集 插件*/
public static final String PLUG_PCI_AUTOGCP = "autogcp2";
/*pci_autotie 连接点采集 插件*/
public static final String PLUG_PCI_AUTOTIE = "autotie2";
/*pci_fimport 导入 插件*/
public static final String PLUG_PCI_FIMPORT = "fimport";
/*pci_gcprefn 控制点过滤 插件*/
public static final String PLUG_PCI_GCPREFN = "gcprefn";
public static final String PLUG_PCI_GCPPRO = "gcppro";
public static final String PLUG_PCI_GCPPRUNE = "gcpprune";
public static final String PLUG_PCI_RFMODEL = "rfmodel";
/*pci_oemodel 正射校正工程建立 插件*/
public static final String PLUG_PCI_OEMODEL = "oemodel";
/*pci_ortho 正射校正 插件*/
public static final String PLUG_PCI_ORTHO = "ortho";
/*pci_tprefn 连接点过滤 插件*/
public static final String PLUG_PCI_TPREFN = "tprefn";
public static final String PLUG_PCI_PYRAMID = "pyramid";
public static final String PLUG_PCI_QBASMBLE = "qbasmble";
public static final String PLUG_PCI_LINK = "link";
public static final String PLUG_PCI_CRPROJ = "crproj";
/* 生成工程概要*/
public static final String PLUG_PCI_OEPROJ_SUM = "oeprojsum";
/* 写入优化后的数学模型*/
public static final String PLUG_PCI_CPMMSEG = "cpmmseg";
/**
* -------------------------- pci plugin end----------------------------------------
*/
}
/**
* redis
*/
public final class redis {
/*IP*/
public static final String IP = "ip";
/*端口*/
public static final String PORT = "port";
/*key*/
public static final String KEY = "key";
/*value*/
public static final String VALUE = "value";
/*数据类型*/
public static final String DATA_TYPE = "data_type";
/*数据类型 字符型*/
public static final String DATA_TYPE_STR = "str";
/*数据类型 字节*/
public static final String DATA_TYPE_BYTE = "byte";
}
/**
* 共享远程目录
*/
public final class remote {
/*IP*/
public static final String IP = "ip";
/*端口*/
public static final String PORT = "port";
/*用户名*/
public static final String USERNAME = "username";
/*密码*/
public static final String PASSWORD = "password";
/*文件目录*/
public static final String FILE_DIR = "file_dir";
/*文件名称*/
public static final String FILE_NAME = "file_name";
/*文件格式 文件格式以逗号隔开*/
public static final String FILE_FORMAT = "file_format";
}
/**
* 本地文件
*/
public final class localFile {
/*文件目录*/
public static final String lOCAL_FILE_DIR = "local_file_dir";
/*文件名字*/
public static final String lOCAL_FILE_NAME = "local_file_name";
/*文件格式 文件格式以逗号隔开*/
public static final String FILE_FORMAT = "file_format";
}
/**
* hdfs
*/
public final class hdfs {
/*IP*/
public static final String IP = "ip";
/*端口*/
public static final String PORT = "port";
/*HDFS中文件目录*/
public static final String HDFS_FILE_DIR = "hdfs_file_dir";
/*文件名字*/
public static final String HDFS_FILE_NAME = "hdfs_file_name";
/*文件格式 文件格式以逗号隔开*/
public static final String FILE_FORMAT = "file_format";
}
public final class rest {
/*IP*/
public static final String IP = "ip";
/*端口*/
public static final String PORT = "port";
}
/**
* phoenix
*/
public final class phoenix {
/*url*/
public static final String URL = "url";
/*插件插入数据时的sql语句*/
public static final String SQL = "sql";
/*插件插入数据时的list对象*/
public static final String UPSERT_LIST = "upsertList";
public static final String TABLE_SCHEMA = "tableSchema";
/*插件导入数据时的表名*/
public static final String TABLE_NAME = "tableName";
/*插件导入数据时的值*/
public static final String CSV_DATA_BYTE = "csvDataByte";
/*插件导出到HDFS时的文件系统*/
public static final String FILE_SYSTEM = "fileSystem";
/*插件导出到HDFS时的路径*/
public static final String PATH = "path";
/*用户名*/
public static final String USERNAME = "username";
/*密码*/
public static final String PASSWORD = "password";
}
/**
* Restful 对外的静态变量
*/
public final class jsonView {
public static final String STATUS_SUCCESS = "success";
public static final String STATUS_FAIL = "fail";
public static final String NONE_LOGIN = "none_login";
/* 错误信息列表 */
public static final String ERRMSG_PAGE = "分页信息为空";
public static final String ERRMSG_ID = "主键ID为空";
public static final String ERRMSG_OBJ = "对象为空";
}
/**
* 数据源类型
*/
public final class DataSource {
/* 数据类型 0 结构型数据,1 文件*/
public static final String DATA_TYPE = "_DATA_TYPE";
/* 用于标识表名称变量 */
public static final String TABLE_NAME_KEY = "_TABLE_NAME";
/* 用区别表结构的前缀 */
public static final String TABLE_COLUMN_PREFIX = "COLUMN_PREFIX_";
public static final String DB_IP = "db_ip";
public static final String DB_PORT = "db_port";
public static final String DB_URL = "db_url";
public static final String DB_TYPE = "db_type";
public static final String DB_DRIVENAME = "db_drivename";
public static final String DB_USERNAME = "db_username";
public static final String DB_PASSWORD = "db_password";
public static final String DB_NAME = "db_name";
public static final String DS_TYPE_KAFKA = "KAFKA";
public static final String DS_TYPE_ES = "elasticearch";
public static final String DS_TYPE_CLOUD_HDFS = "HDFS";
public static final String DS_TYPE_CLOUD_HBASE = "HBase";
public static final String DS_TYPE_FTP = "FTP";
public static final String DS_TYPE_CLOUDDB = "CloudDB";
public static final String DS_TYPE_MONGODB = "MongoDB";
public static final String DS_TYPE_ORACLE = "ORACLE";
public static final String DS_TYPE_SQLSERVER = "SQLServer";
public static final String DS_TYPE_DB2 = "DB2";
public static final String DS_TYPE_MYSQL = "MySQL";
public static final String DS_TYPE_WIN_RMT_DIR = "Win";
public static final String DS_TYPE_LINUX_RMT_DIR = "Linux";
public static final String DS_TYPE_LOCAL = "LOCAL";
public static final String DS_TYPE_REDIS = "Redis";
public static final String DS_TYPE_TACHYON = "tachyon";
public static final String DS_TYPE_TFS = "TFS";
public static final String DS_TYPE_MQ = "MQ";
public static final String DS_TYPE_GREENPLUM = "GREENPLUM";
public static final String DS_TYPE_IGNITE = "IGNITE";
public static final String DS_TYPE_GLUSTERFS = "GLUSTERFS";
public static final String DS_TYPE_KAFKA_INT = "1";
public static final String DS_TYPE_ES_INT = "2";
public static final String DS_TYPE_FTP_INT = "3";
public static final String DS_TYPE_CLOUDDB_INT = "4";
public static final String DS_TYPE_MONGODB_INT = "5";
public static final String DS_TYPE_ORACLE_INT = "6";
public static final String DS_TYPE_SQLSERVER_INT = "7";
public static final String DS_TYPE_DB2_INT = "8";
public static final String DS_TYPE_MYSQL_INT = "9";
public static final String DS_TYPE_WIN_RMT_DIR_INT = "10";
public static final String DS_TYPE_LINUX_RMT_DIR_INT = "11";
public static final String DS_TYPE_LOCAL_INT = "12";
public static final String DS_TYPE_REDIS_INT = "13";
//结构化数据是HBASE
public static final String DS_TYPE_CLOUD_HBASE_INT = "14";
//非结构化数据是HDFS
public static final String DS_TYPE_CLOUD_HDFS_INT = "15";
//TFS文件系统
public static final String DS_TYPE_TFS_INT = "16";
//tachyon
public static final String DS_TYPE_TACHYON_INT = "17";
//MQ
public static final String DS_TYPE_MQ_INT = "18";
public static final String DS_TYPE_GREENPLUM_INT = "19";
//IGNITE
public static final String DS_TYPE_IGNITE_INT = "20";
public static final String DS_TYPE_GLUSTERFS_INT = "21";
}
/**
* 指标项 数据类型
* 0:数据库
* 1:文本
*/
public final class ItemDataType {
public static final String DS_TYPE_DB = "0";
public static final String DS_TYPE_TEXT = "1";
}
/**
* 指标项 文件类型
* 0:目录
* 1:文件
*/
public final class ItemFileType {
public static final String ITEM_DIR = "Folder";
public static final String ITEM_FILE = "文件";
}
/**
* 远程连接数据源的IP和端口
*/
public final class ipAndPort {
public static final String CONN_IP = "localhost";
public static final String CONN_PORT = "5052";
}
public final class kafka {
/*IP*/
public static final String IP = "ip";
/*端口*/
public static final String PORT = "port";
/*主题*/
public static final String TOPIC = "topic";
/*TYPE*/
public static final String TYPE = "type";
//字符类型
public static final String STR_TYPE = "0";
//文件类型
public static final String FILE_TYPE = "1";
//视频类型
public static final String VIDEO_TYPE = "2";
/* 连接类型为producer */
public static final String KAFKA_CONN_PRODUCER = "0";
/* 连接类型为Consumer */
public static final String KAFKA_CONN_CONSUMCER = "1";
public static final String KAFKA_GROUP_KEY = "_KAFKA_GROUP";
public static final String KAFKA_TOPIC_KEY = "_KAFKA_TOPIC";
/* temp data str key*/
public static final String DATA_STR_TMP_KEY = "_DATA_STR";
public static final String KAFKA_TMP_KEY = "_TMP_KEY";
}
/*分布式索引*/
public final class elasticsearch {
public static final int CONN_PORT = 9300;
/*设置elasticsearch集群的名称*/
public static final String CLUSTER_NAME = "elasticsearch";
public static final int MAX_QUERY_TERMS = 20;
}
/*zookeeper*/
public final class ZooKeeper {
/*连接zookeeper的Session超时时间*/
public static final int SESSION_TIME_OUT = 30000;
public static final String SLANT = "/";
public static final String BACK_SLANT = "\\";
public static final int CONN_PORT = 2181;
public static final String ZK_STATE_CONNECTING = "CONNECTING";
public static final String ZK_STATE_CLOSED = "CLOSED";
}
/*python*/
public final class python {
public static final String MID_FLAG = "$_#_$";
/*脚本名称*/
public static final String SCRIPTS_NAME = "scripts_name";
/*执行函数*/
public static final String FUNCTION = "function";
/*参数*/
public static final String PARAMETER = "parameter";
public static final String PCI_PYTHON_FILE = "main.py";
}
/**
* 数据库导出
*/
public final class export {
public static final String HBASE_TYPE = "0";
public static final String MYSQL_TYPE = "1";
public static final String ORACLE_TYPE = "2";
public static final String DM_TYPE = "3";
}
/**
* 规则引擎
*/
public final class rule {
/*规则类型*/
public static final String QL_TYPE = "type";
/*常用规则*/
public static final String QL_COMMON_RULE = "common_rule";
/*自定义规则*/
public static final String QL_CUSTOM_RULE = "custom_rule";
/*规则表达式*/
public static final String QL_Express_RULE = "express";
//固定参数
public static final String VAR = "str";
//参数列表
public static final String COLUMN = "param_column";
}
/**
* 任务相关
*/
public final class task {
/*任务已启动*/
public static final String TASK_RUN_STATUS = "1";
/*任务未启动*/
public static final String TASK_STOP_STATUS = "0";
}
/**
* 系统属性
*/
public final class system {
/*采集系统*/
public static final String DATA_GATHER_SYS_NAME = "DATA_GATHER";
/*数据库管理系统*/
public static final String DATA_BASE_SYS_NAME = "DATA_BASE";
public static final String DATA_ETL_SYS_NAME = "DATA_ETL";
public static final String DATA_ESB_SYS_NAME = "DATA_ESB";
/* 系统名称*/
public static final String SYS_NAME_KEY = "SYS_NAME_KEY";
/* 插件名称*/
public static final String PLUGIN_NAME_KEY = "PLUGIN_NAME_KEY";
/* 流程代码*/
public static final String WORK_FLOW_CODE_KEY = "WORK_FLOW_CODE_KEY";
}
/**
* 目录
*/
public final class catalog {
public static final String DIRECTORYTYPE_LAYER = "directoryType_layer";//图层目录
public static final String DIRECTORYTYPE_APP = "directoryType_app";//应用目录
public static final String DIRECTORYTYPE_SERVER = "directoryType_server";//服务目录
public static final String DIRECTORYTYPE_DATA = "directoryType_data";//数据目录
public static final String DIRECTORYTYPE_FILE = "directoryType_file";//文件目录
public static final String DIRECTORYTYPE_PKG = "directoryType_pkg";//套餐目录
}
/**
* 用户
*/
public final class user {
public static final String COOKIE_USER = "USER";
public static final String COOKIE_TENANT = "TENANT";
public static final String COOKIE_URL = "URL";
public static final String COOKIE_USER_NAME = "USER_NAME";
public static final String COOKIE_ORG_ID = "ORG_ID";
/**
* 系统用户
*/
public static final String USER_TYPE = "0";
/**
* 租户下用户
*/
public static final String TENAT_USER_TYPE = "1";
}
/**
* 定义存储管理的数据类型
*/
public final class dataSourceType {
public static final String HBASE = "4";
public static final String ORACEL = "6";
public static final String SQL_SERVER = "7";
public static final String DB2 = "8";
public static final String MYSQL = "9";
}
/**
* 定义索引日志状态
*/
public final class indexTaskLog {
//成功
public static final String SUCCESS = "1";
//失败
public static final String FAILED = "0";
}
/**
* 定义数据导出的类型
*/
public final class exportType {
public static final String INSERT = "1";
public static final String CSV = "2";
public static final String UPSERT = "3";
public static final String EXCEL = "4";
}
/*定义分隔符*/
public static final String SPLIT_COMMA = ",";
public static final String SPLIT_HASH_KEY = "#";
/**
* tachyon
*/
public final class tachyon {
/*IP*/
public static final String IP = "ip";
/*端口*/
public static final String PORT = "port";
/*es url*/
public static final String ES_HOST = "es_host";
/*es 集群名称*/
public static final String ES_CLOUSTER = "es_cluster";
/*中文件目录*/
public static final String TACHYON_FILE_DIR = "tachyon_file_dir";
/*文件名字*/
public static final String TACHYON_FILE_NAME = "tachyon_file_name";
/*文件格式 文件格式以逗号隔开*/
public static final String FILE_FORMAT = "file_format";
//Elasticsearch information of FileSystem.
public static final String ES_IP = "_ES_IP";
public static final String ES_PORT = "_ES_PORT";
public static final String ES_INDEX_NAME = "_ES_INDEX_NAME";
public static final String ES_INDEX_TYPE = "_ES_INDEX_TYPE";
public static final String ES_CLUSTER_NAME = "_ES_CLUSTER_NAME";
}
/**
* 定义System资源类型,数据类型
*/
public final class systemType {
public static final String RES_TYPE_DATA = "resourceType_data";
public static final String RES_TYPE_SERVICE = "resourceType_server";
public static final String RES_TYPE_LAYER = "resourceType_layer";
public static final String RES_TYPE_APP = "resourceType_app";
public static final String RES_TYPE_FILE = "resourceType_file";
public static final String RES_TYPE_MENU = "resourceType_menu";
public static final String RES_TYPE_PKG = "resourceType_pkg";
}
public final class fileSystemConfig {
public static final String TYPE_HDFS = DataSource.DS_TYPE_CLOUD_HDFS_INT;
public static final String TYPE_TACHYON = DataSource.DS_TYPE_TACHYON_INT;
}
/**
* 数据网格
*/
public final class DataGrid {
public static final String WORKFLOW_DATAGRID = "workflow_datagrid";
public static final String LOG_DATAGRID = "log_datagird";
public static final String MONITOR_LOG = "monitor_log";
public static final String DB_DATAGRID = "db_datagrid";
public static final String PROXY_DATAGRID = "proxy_datagrid";
}
/**
* mq
*/
public final class rabbitMQ {
//数据采集 流程运行消息队列
public static final String DG_WORKFLOW_RUN_Q = "dg_workflow_run_q";
//数据采集 流程运行日志消息队列
public static final String DG_WORKFLOW_LOG_Q = "dg_workflow_log_q";
//流程分配的任务消息队列
public static final String DG_WORKFLOW_OPERATION_TASK_Q = "dg_workflow_operation_task_q_fb";
// public static final String EXCHANGE_NAME = "exchange_name";
//
// public static final String ROUTE_KEY = "route_Key";
}
public static List<String> ImageTypes = new ArrayList<String>();
static {
ImageTypes.add("gif");
ImageTypes.add("png");
ImageTypes.add("jpg");
ImageTypes.add("jpeg");
ImageTypes.add("bmp");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.