text
stringlengths 10
2.72M
|
|---|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.Date;
/**
* BCostRatioId generated by hbm2java
*/
public class BCostRatioId implements java.io.Serializable {
private String uniqueid;
private String costElementId;
private String relationResourceId;
private Long resourceType;
private String assignStandard;
private BigDecimal costRatio;
private String workCoefficient;
private String creator;
private Date createtime;
private String notes;
private String uom;
private String deptid;
private BigDecimal actualCostRatio;
public BCostRatioId() {
}
public BCostRatioId(String uniqueid) {
this.uniqueid = uniqueid;
}
public BCostRatioId(String uniqueid, String costElementId, String relationResourceId, Long resourceType,
String assignStandard, BigDecimal costRatio, String workCoefficient, String creator, Date createtime,
String notes, String uom, String deptid, BigDecimal actualCostRatio) {
this.uniqueid = uniqueid;
this.costElementId = costElementId;
this.relationResourceId = relationResourceId;
this.resourceType = resourceType;
this.assignStandard = assignStandard;
this.costRatio = costRatio;
this.workCoefficient = workCoefficient;
this.creator = creator;
this.createtime = createtime;
this.notes = notes;
this.uom = uom;
this.deptid = deptid;
this.actualCostRatio = actualCostRatio;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public String getCostElementId() {
return this.costElementId;
}
public void setCostElementId(String costElementId) {
this.costElementId = costElementId;
}
public String getRelationResourceId() {
return this.relationResourceId;
}
public void setRelationResourceId(String relationResourceId) {
this.relationResourceId = relationResourceId;
}
public Long getResourceType() {
return this.resourceType;
}
public void setResourceType(Long resourceType) {
this.resourceType = resourceType;
}
public String getAssignStandard() {
return this.assignStandard;
}
public void setAssignStandard(String assignStandard) {
this.assignStandard = assignStandard;
}
public BigDecimal getCostRatio() {
return this.costRatio;
}
public void setCostRatio(BigDecimal costRatio) {
this.costRatio = costRatio;
}
public String getWorkCoefficient() {
return this.workCoefficient;
}
public void setWorkCoefficient(String workCoefficient) {
this.workCoefficient = workCoefficient;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getUom() {
return this.uom;
}
public void setUom(String uom) {
this.uom = uom;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public BigDecimal getActualCostRatio() {
return this.actualCostRatio;
}
public void setActualCostRatio(BigDecimal actualCostRatio) {
this.actualCostRatio = actualCostRatio;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof BCostRatioId))
return false;
BCostRatioId castOther = (BCostRatioId) other;
return ((this.getUniqueid() == castOther.getUniqueid()) || (this.getUniqueid() != null
&& castOther.getUniqueid() != null && this.getUniqueid().equals(castOther.getUniqueid())))
&& ((this.getCostElementId() == castOther.getCostElementId())
|| (this.getCostElementId() != null && castOther.getCostElementId() != null
&& this.getCostElementId().equals(castOther.getCostElementId())))
&& ((this.getRelationResourceId() == castOther.getRelationResourceId())
|| (this.getRelationResourceId() != null && castOther.getRelationResourceId() != null
&& this.getRelationResourceId().equals(castOther.getRelationResourceId())))
&& ((this.getResourceType() == castOther.getResourceType())
|| (this.getResourceType() != null && castOther.getResourceType() != null
&& this.getResourceType().equals(castOther.getResourceType())))
&& ((this.getAssignStandard() == castOther.getAssignStandard())
|| (this.getAssignStandard() != null && castOther.getAssignStandard() != null
&& this.getAssignStandard().equals(castOther.getAssignStandard())))
&& ((this.getCostRatio() == castOther.getCostRatio()) || (this.getCostRatio() != null
&& castOther.getCostRatio() != null && this.getCostRatio().equals(castOther.getCostRatio())))
&& ((this.getWorkCoefficient() == castOther.getWorkCoefficient())
|| (this.getWorkCoefficient() != null && castOther.getWorkCoefficient() != null
&& this.getWorkCoefficient().equals(castOther.getWorkCoefficient())))
&& ((this.getCreator() == castOther.getCreator()) || (this.getCreator() != null
&& castOther.getCreator() != null && this.getCreator().equals(castOther.getCreator())))
&& ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null
&& castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime())))
&& ((this.getNotes() == castOther.getNotes()) || (this.getNotes() != null
&& castOther.getNotes() != null && this.getNotes().equals(castOther.getNotes())))
&& ((this.getUom() == castOther.getUom()) || (this.getUom() != null && castOther.getUom() != null
&& this.getUom().equals(castOther.getUom())))
&& ((this.getDeptid() == castOther.getDeptid()) || (this.getDeptid() != null
&& castOther.getDeptid() != null && this.getDeptid().equals(castOther.getDeptid())))
&& ((this.getActualCostRatio() == castOther.getActualCostRatio())
|| (this.getActualCostRatio() != null && castOther.getActualCostRatio() != null
&& this.getActualCostRatio().equals(castOther.getActualCostRatio())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getUniqueid() == null ? 0 : this.getUniqueid().hashCode());
result = 37 * result + (getCostElementId() == null ? 0 : this.getCostElementId().hashCode());
result = 37 * result + (getRelationResourceId() == null ? 0 : this.getRelationResourceId().hashCode());
result = 37 * result + (getResourceType() == null ? 0 : this.getResourceType().hashCode());
result = 37 * result + (getAssignStandard() == null ? 0 : this.getAssignStandard().hashCode());
result = 37 * result + (getCostRatio() == null ? 0 : this.getCostRatio().hashCode());
result = 37 * result + (getWorkCoefficient() == null ? 0 : this.getWorkCoefficient().hashCode());
result = 37 * result + (getCreator() == null ? 0 : this.getCreator().hashCode());
result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode());
result = 37 * result + (getNotes() == null ? 0 : this.getNotes().hashCode());
result = 37 * result + (getUom() == null ? 0 : this.getUom().hashCode());
result = 37 * result + (getDeptid() == null ? 0 : this.getDeptid().hashCode());
result = 37 * result + (getActualCostRatio() == null ? 0 : this.getActualCostRatio().hashCode());
return result;
}
}
|
package backjoon.minpath;
import java.io.*;
import java.util.StringTokenizer;
class Bus{
// 시작점, 도착점, 걸리는 시간
int start, end, weight;
public Bus(int start, int end, int weight){
this.start = start;
this.end = end;
this.weight = weight;
}
}
public class Backjoon11657 {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
private static final int INF = 500 * 100_000;
static int n, m;
static int dist[];
static Bus busArr[];
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
busArr = new Bus[m + 1];
dist = new int[n + 1];
// 최단거리 배열 무한대로 초기화
for(int i = 1 ; i <= n; i++) dist[i] = INF;
// 입력값 초기화
for(int i = 0; i < m; i++){
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
int time = Integer.parseInt(st.nextToken());
busArr[i] = new Bus(start, end, time);
}
// 결과 출력을 위한 객체
StringBuilder sb = new StringBuilder();
// 음의 cycle이 없는 경우
if(bellmanFord()){
for(int i = 2; i <= n; i++){
sb.append(dist[i] == INF ? "-1\n" : dist[i] + "\n");
}
// 음의 cycle이 있는 경우
}else{
sb.append("-1\n");
}
bw.write(sb.toString());
bw.close();
br.close();
}
// 음의 cycle이 있다면 false리턴 없다면 true리턴
// 벨만포드 알고리즘
private static boolean bellmanFord() {
// 시작점 최단거리 0 갱신
dist[1] = 0;
// v - 1번 수행
for(int i = 1; i < n; i++){
for(int j = 0; j < m; j++){
Bus bus = busArr[j];
// 더 작은 최단거리 가 있는 경우 갱신
if(dist[bus.start] != INF && dist[bus.end] > dist[bus.start] + bus.weight){
dist[bus.end] = dist[bus.start] + bus.weight;
}
}
}
// 음수 cycle 확인
// 갱신되는게 있다면 음수 cycle이 있다는 뜻
for(int i = 0; i < m; i++){
Bus bus = busArr[i];
if(dist[bus.start] != INF &&dist[bus.end] > dist[bus.start] + bus.weight) return false;
}
return true;
}
}
|
package com.tencent.mm.ui.chatting.b;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.R;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.h;
import com.tencent.mm.ui.chatting.b.b.g;
class j$2 implements OnClickListener {
final /* synthetic */ j tOS;
j$2(j jVar) {
this.tOS = jVar;
}
public final void onClick(View view) {
g gVar = (g) this.tOS.bAG.O(g.class);
if (gVar.boX() == 0) {
x.w("MicroMsg.ChattingMoreBtnBarHelper", "ignore click del btn, selected items count is 0");
return;
}
Context context = this.tOS.bAG.tTq.getContext();
h.a(context, context.getString(R.l.confirm_delete), "", context.getString(R.l.delete_message), context.getString(R.l.app_cancel), new 1(this, context, gVar), null, R.e.alert_btn_color_warn);
}
}
|
package br.com.cem01.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import br.com.cem01.model.TeacherModel;
@Entity
@Table(name="discipline")
public class DisciplineModel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="code", unique=true)
private String code;
@Column(name="name")
private String name;
@ManyToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinTable(
name="disciplineTeacher",
joinColumns=@JoinColumn(name="disciplineCode", referencedColumnName="code"),
inverseJoinColumns=@JoinColumn(name="teacherId", referencedColumnName="id"))
private List<TeacherModel> teacherList;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<TeacherModel> getTeacherList() {
return teacherList;
}
public void setTeacherList(List<TeacherModel> teacherList) {
this.teacherList = teacherList;
}
}
|
package p4_group_8_repo.Game_actor;
import javafx.scene.image.ImageView;
import javafx.scene.input.InputEvent;
import p4_group_8_repo.Game_scene.World;
import java.util.ArrayList;
/**
* Class of Actor
* @author Jun Yuan
*
*/
public abstract class Actor extends ImageView{
/**
* Method for animations to move (coordinates are set)
* @param dx horizontal motion
* @param dy vertical motion
*/
public void move(double dx, double dy) {
setX(getX() + dx);
setY(getY() + dy);
}
/**
* Access to World
* @return getParent() and type cast into WORLD
*/
public World getWorld() {
return (World) getParent();
}
/**
* Access to width of animation
* @return width of animation
*/
public double getWidth() {
return this.getBoundsInLocal().getWidth();
}
/**
* Access to height of animation
* @return height if animation
*/
public double getHeight() {
return this.getBoundsInLocal().getHeight();
}
/**
* Method to get objects which are intersect
* @param <A> is the array list
* @param cls is the class extending to look for
* @return array list of animations which are intersected
*/
public <A extends Actor> java.util.List<A> getIntersectingObjects(java.lang.Class<A> cls){
ArrayList<A> someArray = new ArrayList<A>();
for (A actor: getWorld().getObjects(cls)) {
if (actor != this && actor.intersects(this.getBoundsInLocal())) {
someArray.add(actor);
}
}
return someArray;
}
/**
* Method to manage input (empty body)
* @param e is the key typed
*/
public void manageInput(InputEvent e) {
}
/**
* Method to get one intersecting object
* @param <A> is the array list
* @param cls is the class extending to look for
* @return animation that is first intersecting
*/
public <A extends Actor> A getOneIntersectingObject(java.lang.Class<A> cls) {
ArrayList<A> someArray = new ArrayList<A>();
for (A actor: getWorld().getObjects(cls)) {
if (actor != this && actor.intersects(this.getBoundsInLocal())) {
someArray.add(actor);
break;
}
}
return someArray.get(0);
}
/**
* Abstract method (empty body)
* @param now is the current run time
*/
public abstract void act(long now);
}
|
package com.example.satu.mediapp.Interfaces;
import com.example.satu.mediapp.Data.Medicine;
/**
* Created by Satu on 2016-01-05.
*/
public interface OnMedicinePut {
public void onMedicinePut(Medicine medicine);
}
|
package com.ellalee.travelmaker;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import static java.sql.Types.NULL;
/**
* Created by jiwon on 2018-06-09.
*/
public class CalendarDayMain extends Activity {
String sched, memo;
int day, month, year;
private TextView date;
private TextView scheView, memoView,category_sche, category_memo;
private EditText scheEdit, memoEdit;
private Button changeBtn, deleteBtn, completeBtn;
private String mode = "View";
SQLiteDatabase db;
CalendarDBHelper helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar_day);
helper = new CalendarDBHelper(CalendarDayMain.this, "calendar.db", null, 1);
Intent intent = getIntent();
day = intent.getIntExtra("day", 0);
year = intent.getIntExtra("year", 0);
month = intent.getIntExtra("month", 0);
sched = intent.getStringExtra("sche");
memo = intent.getStringExtra("memo");
date = (TextView)findViewById(R.id.dayMain_date);
scheView = (TextView)findViewById(R.id.dayMain_sche);
memoView = (TextView)findViewById(R.id.dayMain_memo);
changeBtn = (Button)findViewById(R.id.dayMain_change);
deleteBtn = (Button)findViewById(R.id.dayMain_delete);
scheEdit = (EditText)findViewById(R.id.change_editsche);
memoEdit = (EditText)findViewById(R.id.change_editmemo);
completeBtn = (Button)findViewById(R.id.complete_change);
category_sche = (TextView)findViewById(R.id.category3);
category_memo = (TextView)findViewById(R.id.category4);
date.setText(String.valueOf(year) + "." + String.valueOf(month) + "." + String.valueOf(day));
scheView.setText(sched);
memoView.setText(memo);
changeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mode = "Edit";
scheEdit.setVisibility(View.VISIBLE);
memoEdit.setVisibility(View.VISIBLE);
completeBtn.setVisibility(View.VISIBLE);
category_memo.setVisibility(View.VISIBLE);
category_sche.setVisibility(View.VISIBLE);
scheView.setVisibility(View.INVISIBLE);
completeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String newSche = scheEdit.getText().toString();
memo = memoEdit.getText().toString();
if(!newSche.replace(" ", "").equals("")) {
update(String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day),
sched, newSche, memo);
scheView.setText(sched);
scheEdit.setVisibility(View.INVISIBLE);
memoEdit.setVisibility(View.INVISIBLE);
completeBtn.setVisibility(View.INVISIBLE);
category_memo.setVisibility(View.INVISIBLE);
category_sche.setVisibility(View.INVISIBLE);
scheView.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), newSche + " 스케줄 수정완료!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CalendarDayMain.this, CalendarListMain.class);
intent.putExtra("year", year);
intent.putExtra("month", month);
intent.putExtra("day", day);
setResult(RESULT_OK, intent);
finish();
}
else {
setResult(RESULT_CANCELED);
Toast.makeText(getApplicationContext(), "스케줄이 입력되지 않았습니다!", Toast.LENGTH_LONG).show();
}
}
});
}
});
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
delete(String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day),
sched);
Toast.makeText(getApplicationContext(), "스케줄 삭제완료!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CalendarDayMain.this, CalendarListMain.class);
intent.putExtra("year", year);
intent.putExtra("month", month);
intent.putExtra("day", day);
setResult(RESULT_OK, intent);
finish();
}
});
}
/*
* DB에 있는 값 업데이트 method
*/
public void update(String date, String sched, String newSche, String memo) {
db = helper.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put("date", date);
// values.put("schedule", sched);
// db.update("calendar", values, "date=?", new String[]{date});
db.execSQL("UPDATE calendar SET schedule = '"+ newSche + "', memo = '" + memo + "' WHERE (date = '" + date + "') AND (schedule = '" + sched + "');");
}
/*
* 원하는 날짜의 스케줄 삭제
*/
public void delete(String date, String sched) {
db = helper.getWritableDatabase();
db.execSQL("DELETE FROM calendar WHERE (date='" + date + "') AND (schedule='" + sched + "');");
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.blueprints;
import vanadis.core.collections.Generic;
import vanadis.core.lang.EqHc;
import vanadis.core.lang.Not;
import vanadis.core.lang.ToString;
import java.io.Serializable;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* A boot config models part of a {@link Blueprints boot config set},
* and are used to build
* {@link SystemSpecification boot checklists}.
*/
public final class Blueprint implements Serializable, Iterable<ModuleSpecification> {
private final String name;
private final String[] extendz;
private final boolean abstrackt;
private final List<Blueprint> parents = Generic.list();
private final URI source;
private final Collection<BundleSpecification> autoCoordinates;
private final Collection<BundleSpecification> dynaCoordinates;
private final Collection<ModuleSpecification> moduleSpecifications;
private boolean leaf = true;
public Blueprint(URI source, String name, String extend, Boolean abstrackt,
List<BundleSpecification> autoCoordinates,
List<BundleSpecification> dynaCoordinates,
List<ModuleSpecification> moduleSpecifications) {
this(source, name, new String[] { extend }, abstrackt,
autoCoordinates,
dynaCoordinates,
moduleSpecifications);
}
public Blueprint(URI source, String name, String[] extendz, Boolean abstrackt,
List<BundleSpecification> autoCoordinates,
List<BundleSpecification> dynaCoordinates,
List<ModuleSpecification> moduleSpecifications) {
this.source = source;
this.autoCoordinates = Generic.seal(autoCoordinates);
this.dynaCoordinates = Generic.seal(dynaCoordinates);
this.moduleSpecifications = Generic.seal(moduleSpecifications);
this.name = Not.nil(name, "name");
this.extendz = extendz != null && extendz.length > 0 ? extendz : NO_PARENTS;
this.abstrackt = abstrackt != null && abstrackt;
}
@Override
public Iterator<ModuleSpecification> iterator() {
return moduleSpecifications.iterator();
}
public Iterable<BundleSpecification> getAutoBundles() {
return autoCoordinates;
}
public Iterable<BundleSpecification> getDynaBundles() {
return dynaCoordinates;
}
public String getName() {
return name;
}
public String[] getExtends() {
return extendz;
}
public boolean isAbstract() {
return abstrackt;
}
public boolean isLeaf() {
return leaf;
}
public SystemSpecification createSpecification(URI root) {
return SystemSpecification.createSystemSpecifiction(root, new BlueprintExtendsTraverser(this));
}
public List<Blueprint> getParents() {
return Generic.seal(parents);
}
boolean contains(BundleSpecification spec) {
for (Blueprint blueprint : new BlueprintExtendsTraverser(this)) {
if (blueprint.dynaCoordinates.contains(spec) || blueprint.autoCoordinates.contains(spec)) {
return true;
}
}
return false;
}
SystemSpecification createSystemSpecification(URI root) {
return new SystemSpecification(source, name, root, autoCoordinates, dynaCoordinates, moduleSpecifications);
}
void addParent(Blueprint parentBlueprint) {
Not.nil(parentBlueprint, "parent blueprint");
if (parents.contains(parentBlueprint)) {
return;
}
failOnCycle(parentBlueprint);
this.parents.add(parentBlueprint);
parentBlueprint.leaf = false;
}
private void failOnCycle(Blueprint parent) {
for (Blueprint elder : new BlueprintExtendsTraverser(parent)) {
if (elder == this) {
throw new IllegalArgumentException("Cycle! " + this + " cannot parent itself!");
}
}
}
private static final long serialVersionUID = -6951559860905287939L;
private static final String[] NO_PARENTS = new String[] {};
@Override
public int hashCode() {
return EqHc.hc(name);
}
@Override
public boolean equals(Object obj) {
Blueprint blueprint = EqHc.retyped(this, obj);
return blueprint != null && EqHc.eq(name, blueprint.name);
}
@Override
public String toString() {
return ToString.of(this, name, "parents", Arrays.toString(extendz));
}
}
|
package leetcode;
/**
* @author kangkang lou
*/
public class Main_174 {
public int calculateMinimumHP(int[][] dungeon) {
if (dungeon == null || dungeon.length == 0 || dungeon[0].length == 0) return 0;
int m = dungeon.length;
int n = dungeon[0].length;
int[][] health = new int[m][n];
health[m - 1][n - 1] = Math.max(1 - dungeon[m - 1][n - 1], 1);
for (int i = m - 2; i >= 0; i--) {
health[i][n - 1] = Math.max(health[i + 1][n - 1] - dungeon[i][n - 1], 1);
}
for (int j = n - 2; j >= 0; j--) {
health[m - 1][j] = Math.max(health[m - 1][j + 1] - dungeon[m - 1][j], 1);
}
for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
int down = Math.max(health[i + 1][j] - dungeon[i][j], 1);
int right = Math.max(health[i][j + 1] - dungeon[i][j], 1);
health[i][j] = Math.min(right, down);
}
}
return health[0][0];
}
public static void main(String[] args) {
int[][] arr = {
{-2, -3, 3},
{-5, -10, 1},
{10, 30, -5}
};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println(new Main_174().calculateMinimumHP(arr));
}
}
|
package com.zs.dao.split;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* @Created by IDEA
* @author:LiuYiBo(小博)
* @Date:2018/7/31
* @Time:9:53
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDbType();
}
}
|
package com.zzidc.web.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.Callable;
/**
* @ClassName AsyncController
* @Author chenxue
* @Description 异步处理REST服务
* @Date 2019/4/1 13:41
**/
@RestController
public class AsyncController {
private Logger logger = LoggerFactory.getLogger(AsyncController.class);
@RequestMapping("/order")
public Callable<String> order(){
Callable<String> result = ()->{
logger.info("副线程开始");
Thread.sleep(1000);
logger.info("副线程返回");
return "success";
};
logger.info("主线程返回");
return result;
}
@RequestMapping("/syncOrder")
public DeferredResult suncOrder(){
return null;
}
}
|
package com.tencent.mm.ui.base.sortview;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.VerticalScrollBar;
import com.tencent.mm.ui.base.VerticalScrollBar.a;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseSortView extends LinearLayout implements a {
private OnItemSelectedListener DT;
private OnItemClickListener UD;
private ListView hqn;
private int mMode;
private VerticalScrollBar tDG;
private View tDH;
private c tDI = new c(getItemViewCreator());
private OnItemLongClickListener tDJ;
private List<d> tDK = new ArrayList();
public boolean tDL;
public boolean tDM;
private a tDN;
public abstract boolean a(String str, d dVar);
public abstract c.a getItemViewCreator();
public abstract ListView getListView();
public abstract View getNoResultView();
public abstract VerticalScrollBar getScrollBar();
public abstract View inflate();
public BaseSortView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
inflate();
this.tDG = getScrollBar();
this.hqn = getListView();
this.tDH = getNoResultView();
this.tDL = true;
lP(true);
this.hqn.setAdapter(this.tDI);
if (this.tDG != null) {
this.tDG.setOnScrollBarTouchListener(this);
}
this.tDI.registerDataSetObserver(new 1(this));
this.hqn.setOnItemClickListener(new 2(this));
this.hqn.setOnItemLongClickListener(new OnItemLongClickListener() {
public final boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long j) {
if (BaseSortView.this.tDJ != null) {
return BaseSortView.this.tDJ.onItemLongClick(adapterView, view, i, j);
}
return false;
}
});
this.hqn.setOnItemSelectedListener(new 4(this));
}
public void refresh() {
ah.A(this.tDI.tDR);
}
public c getAdapter() {
return this.tDI;
}
public final void dx(List<d> list) {
if (this.mMode == 0 && this.tDK != list) {
this.tDK.clear();
if (list != null) {
this.tDK.addAll(list);
}
}
this.tDI.dx(list);
}
public final void aac(String str) {
boolean z = true;
if (this.mMode != 1) {
x.w("MicroMsg.BaseSortView", "Can't doFilter successfully out of the search mode.");
return;
}
boolean z2;
boolean z3;
List arrayList = new ArrayList();
if (bi.oW(str)) {
z2 = false;
} else {
arrayList.clear();
for (d dVar : this.tDK) {
if (a(str, dVar)) {
arrayList.add(dVar);
}
}
z2 = true;
}
View view = this.hqn;
if (!z2 || arrayList.size() <= 0) {
z3 = false;
} else {
z3 = true;
}
o(view, z3);
View view2 = this.tDH;
if (!z2 || arrayList.size() > 0) {
z = false;
}
o(view2, z);
dx(arrayList);
}
public List<d> getDatas() {
return this.tDI.tDK;
}
public final void ys(String str) {
int aad = this.tDI.aad(str);
if (aad >= 0) {
this.hqn.setSelection(aad);
}
}
public OnItemClickListener getOnItemClickListener() {
return this.UD;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.UD = onItemClickListener;
}
public OnItemLongClickListener getOnItemLongClickListener() {
return this.tDJ;
}
public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
this.tDJ = onItemLongClickListener;
}
public OnItemSelectedListener getOnItemSelectedListener() {
return this.DT;
}
public void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
this.DT = onItemSelectedListener;
}
public int getMode() {
return this.mMode;
}
public void setMode(int i) {
if (i == 1) {
this.mMode = 1;
aac("");
return;
}
this.mMode = 0;
o(this.tDH, false);
o(this.hqn, true);
dx(this.tDK);
}
public static void o(View view, boolean z) {
if (view != null) {
view.setVisibility(z ? 0 : 8);
}
}
public final void lP(boolean z) {
this.tDM = z;
if (this.tDG != null) {
this.tDG.setVisibility(z ? 0 : 8);
}
}
public final void cso() {
this.tDL = false;
ah.A(this.tDI.tDR);
}
public a getDataSetObserver() {
return this.tDN;
}
public void setDataSetObserver(a aVar) {
this.tDN = aVar;
}
}
|
package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.util.math.BlockPos;
public class SPacketBlockBreakAnim implements Packet<INetHandlerPlayClient> {
private int breakerId;
private BlockPos position;
private int progress;
public SPacketBlockBreakAnim() {}
public SPacketBlockBreakAnim(int breakerIdIn, BlockPos positionIn, int progressIn) {
this.breakerId = breakerIdIn;
this.position = positionIn;
this.progress = progressIn;
}
public void readPacketData(PacketBuffer buf) throws IOException {
this.breakerId = buf.readVarIntFromBuffer();
this.position = buf.readBlockPos();
this.progress = buf.readUnsignedByte();
}
public void writePacketData(PacketBuffer buf) throws IOException {
buf.writeVarIntToBuffer(this.breakerId);
buf.writeBlockPos(this.position);
buf.writeByte(this.progress);
}
public void processPacket(INetHandlerPlayClient handler) {
handler.handleBlockBreakAnim(this);
}
public int getBreakerId() {
return this.breakerId;
}
public BlockPos getPosition() {
return this.position;
}
public int getProgress() {
return this.progress;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\server\SPacketBlockBreakAnim.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package co.nos.noswallet.network.websockets;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.annotations.SerializedName;
import java.io.EOFException;
import java.io.Serializable;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.inject.Inject;
import javax.net.ssl.SSLException;
import co.nos.noswallet.BuildConfig;
import co.nos.noswallet.analytics.CrashLog;
import co.nos.noswallet.db.RepresentativesProvider;
import co.nos.noswallet.network.nosModel.SocketResponse;
import co.nos.noswallet.network.websockets.model.PendingBlocksCredentialsBag;
import co.nos.noswallet.persistance.IndexedWallet;
import co.nos.noswallet.persistance.currency.CryptoCurrency;
import co.nos.noswallet.push.FirebasePushMessagingRepository;
import co.nos.noswallet.ui.addWallet.SubAccounts;
import co.nos.noswallet.ui.home.HasWebsocketMachine;
import co.nos.noswallet.util.Extensions;
import co.nos.noswallet.util.NosLogger;
import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import okhttp3.OkHttpClient;
import okhttp3.WebSocket;
public class WebsocketMachine {
private boolean alreadyFcmRegistered = false;
public PublishSubject<Boolean> internetConnectivitySubject = PublishSubject.create();
public String getRecentAccountBalanceOf(CryptoCurrency currencyInUse, IndexedWallet indexedWallet) {
CurrencyHandler currencyHandler = getMatchingHandler(currencyInUse);
if (currencyHandler != null) {
return currencyHandler.recentAccountBalanceOf(indexedWallet);
}
return "0";
}
public void logout() {
// Disposable d = firebasePushMessagingRepository.getToken()
// .subscribeOn(Schedulers.io())
// .subscribe(token -> {
// if (websocketExecutor != null) {
// websocketExecutor.send(bulkFcmRegisterRequest(token, true));
// }
// },
// throwable -> {
//
// });
}
public void setRecentAccountBalance(String balance,
CryptoCurrency currency,
IndexedWallet indexedWallet) {
CurrencyHandler handler = getMatchingHandler(currency);
if (handler != null && isNumber(balance)) {
String accountNumber = indexedWallet.provideAccountNumber(currency);
handler.recentAccountBalances.put(accountNumber, balance);
}
}
public void enableWallet(CryptoCurrency currency,
IndexedWallet indexedWallet) {
getMatchingHandlerAndPerform(currency, handler -> handler.enableAccount(indexedWallet));
}
public static boolean isNumber(String balance) {
try {
Double.valueOf(balance);
return true;
} catch (NumberFormatException c) {
Log.e(TAG, "isNumber: ", c);
return false;
}
}
public void requestGetPendingBlocks(CryptoCurrency cryptoCurrency,
IndexedWallet indexedWallet) {
getMatchingHandlerAndPerform(cryptoCurrency, handler -> handler.requestGetPendingBlocks(indexedWallet));
}
public interface DoSth {
void doSomething(CurrencyHandler handler);
}
@Nullable
public static WebsocketMachine obtain(Activity activity) {
if (activity instanceof HasWebsocketMachine) {
return ((HasWebsocketMachine) activity).getWebsocketMachine();
}
return null;
}
private final Runnable reconnectToApi = this::setupWebSockets;
interface Mutator {
PendingBlocksCredentialsBag mutate(PendingBlocksCredentialsBag ref);
}
private RepresentativesProvider representativesProvider;
private FirebasePushMessagingRepository firebasePushMessagingRepository;
private final CrashLog crashLog;
public static final String TAG = WebsocketMachine.class.getSimpleName();
private RequestInventor requestInventor;
@Nullable
private volatile WebsocketExecutor websocketExecutor;
private Handler handler = new Handler(Looper.getMainLooper());
private CompositeDisposable disposable = new CompositeDisposable();
private final List<CurrencyHandler> currencyHandlers;
@Inject
WebsocketMachine(RequestInventor requestInventor,
RepresentativesProvider representativesProvider,
FirebasePushMessagingRepository firebasePushMessagingRepository,
CrashLog crashLog) {
this.requestInventor = requestInventor;
this.representativesProvider = representativesProvider;
this.firebasePushMessagingRepository = firebasePushMessagingRepository;
this.crashLog = crashLog;
this.currencyHandlers = Observable.fromArray(CryptoCurrency.values())
.map(this::createWithCurrency)
.toList()
.blockingGet();
}
private CurrencyHandler createWithCurrency(CryptoCurrency cryptoCurrency) {
return new CurrencyHandler(cryptoCurrency, requestInventor, representativesProvider,
firebasePushMessagingRepository, crashLog);
}
public void start() {
setupWebSockets();
}
public void pausePendingTransactions() {
handler.removeCallbacksAndMessages(null);
}
private OkHttpClient buildOkHttpClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.build();
return client;
}
private void setupWebSockets() {
NosLogger.i(TAG, "setupWebSockets() called");
String url = BuildConfig.WEBSOCKET_URL;
websocketExecutor = new WebsocketExecutor(buildOkHttpClient(), url, new NosNodeWebSocketListener());
websocketExecutor.init(new NosNodeWebSocketListener.Doable() {
@Override
public void onOpen(WebSocket websocket) {
Log.w(TAG, "Websocket initialized at " + readableTime());
}
});
Disposable disposable = websocketExecutor.observeMessages()
.subscribeOn(Schedulers.io())
.subscribe(this::recognize, this::onError);
this.disposable.add(disposable);
}
private void onError(Throwable err) {
NosLogger.e(TAG, "onError: ", err);
err.printStackTrace();
if (err instanceof UnknownHostException) {
internetConnectivitySubject.onNext(true);
}
if (isNetworkError(err) || socketClosedError(err)) {
handler.removeCallbacks(null);
handler.postDelayed(reconnectToApi, 3_000);
closeAll();
} else {
NosLogger.e(TAG, "onError: unrecognized error", err);
}
}
public void closeAll() {
performForAll(CurrencyHandler::closeConnection);
}
private boolean socketClosedError(Throwable err) {
return err instanceof EOFException;
}
private boolean isNetworkError(Throwable err) {
return err instanceof SocketTimeoutException
|| err instanceof UnknownHostException
|| err instanceof SSLException;
}
@SuppressLint("LogNotTimber")
private void recognize(String json) {
NosLogger.i(TAG, "onNext -> \n" + json);
internetConnectivitySubject.onNext(false);
SocketResponse response = safeCast(json, SocketResponse.class);
for (CurrencyHandler handler : currencyHandlers) {
if (handler.currencyMatches(response.currency)) {
handler.handle(response, websocketExecutor);
}
}
}
public Observable<SocketResponse> observeUiTriggers(CryptoCurrency cryptoCurrency) {
for (CurrencyHandler handler : currencyHandlers) {
if (handler.currencyMatches(cryptoCurrency)) {
return handler.observeUiTriggers();
}
}
return Observable.error(new NoSuchElementException("cannot find matching observable for " + cryptoCurrency.name()));
}
public Observable<SocketResponse> observeAccountData(CryptoCurrency currency, String accountNumber) {
for (CurrencyHandler handler : currencyHandlers) {
if (handler.currencyMatches(currency)) {
return handler.observeAccountData(accountNumber);
}
}
return Observable.error(new NoSuchElementException("cannot find matching observable for " + currency.name()));
}
public void requestAccountHistory(CryptoCurrency cryptoCurrency, IndexedWallet indexedWallet) {
NosLogger.w(TAG, "requestAccountHistory: ");
getMatchingHandlerAndPerform(cryptoCurrency, s -> s.requestAccountHistory(indexedWallet));
}
private void performForAll(DoSth doSth) {
for (CurrencyHandler handler : currencyHandlers) {
doSth.doSomething(handler);
}
}
private void getMatchingHandlerAndPerform(CryptoCurrency cryptoCurrency, DoSth doSth) {
for (CurrencyHandler handler : currencyHandlers) {
if (handler.currencyMatches(cryptoCurrency)) {
doSth.doSomething(handler);
return;
}
}
}
@Nullable
public CurrencyHandler getMatchingHandler(CryptoCurrency cryptoCurrency) {
for (CurrencyHandler handler : currencyHandlers) {
if (handler.currencyMatches(cryptoCurrency)) {
return handler;
}
}
return null;
}
public void requestAccountInfo(CryptoCurrency cryptoCurrency,
IndexedWallet indexedWallet) {
NosLogger.w(TAG, "requestAccountInfo: ");
getMatchingHandlerAndPerform(cryptoCurrency, s -> s.requestAccountInfo(indexedWallet));
}
public void requestBatchedAccountInfo(CryptoCurrency cryptoCurrency,
SubAccounts subAccounts) {
NosLogger.w(TAG, "requestBatchedAccountInfo: ");
getMatchingHandlerAndPerform(cryptoCurrency, currencyHandler -> {
currencyHandler.websocketExecutor = websocketExecutor;
currencyHandler.requestBatchedAccountsInfo(subAccounts);
});
}
public void transferCoins(String sendAmount,
String destinationAccount,
CryptoCurrency cryptoCurrency,
IndexedWallet issuingWallet) {
getMatchingHandlerAndPerform(cryptoCurrency,
handler -> handler.transferCoins(sendAmount, destinationAccount, cryptoCurrency, issuingWallet)
);
}
public void registerPushNotificationsIfNotRegistered() {
if (alreadyFcmRegistered) {
return;
}
// Disposable d = firebasePushMessagingRepository.getToken()
// .subscribe(token -> {
// if (websocketExecutor != null) {
// websocketExecutor.send(bulkFcmRegisterRequest(token));
// }
// },
// throwable -> {
//
// });
}
public void forceRegisterPushNotifications() {
Log.w(TAG, "forceRegisterPushNotifications: DISABLED");
// Disposable d = firebasePushMessagingRepository.getToken()
// .subscribe(token -> {
// Log.w(TAG, "firebase token " + token);
// if (websocketExecutor != null) {
// websocketExecutor.send(bulkFcmRegisterRequest(token));
// } else {
// Log.e(TAG, "failed to register fcm token: websocketexecutor is null");
// }
// },
// throwable -> {
// Log.e(TAG, "failed to register fcm token", throwable);
// crashLog.logNosException("failed to register fcm token", throwable);
// });
}
private BulkFcmRegisterRequest bulkFcmRegisterRequest(String token) {
return bulkFcmRegisterRequest(token, false);
}
private BulkFcmRegisterRequest bulkFcmRegisterRequest(String token, boolean resign) {
List<AccountRegisterEntry> entries = new ArrayList<>();
performForAll(handler -> {
Set<String> activeAccounts = handler.fastWalletAccess.keySet();
for (String accountNumber : activeAccounts) {
entries.add(new AccountRegisterEntry(
accountNumber, token, resign
));
}
});
return new BulkFcmRegisterRequest(entries);
}
public void handleClickedNotification(Intent intent) {
//todo://
// if (intent != null) {
// if (ACTION_GOT_SAUCE.equalsIgnoreCase(intent.getAction())) {
// performForAll(CurrencyHandler::requestGetPendingBlocks);
// }
// }
}
public static <T> T safeCast(String json, Class<T> klazz) {
return SafeCast.safeCast(json, klazz);
}
static class BulkFcmRegisterRequest implements Serializable {
@SerializedName("accounts")
List<AccountRegisterEntry> accounts;
@SerializedName("action")
final String action = "register_notifications";
public BulkFcmRegisterRequest(List<AccountRegisterEntry> accounts) {
this.accounts = accounts;
}
@Override
public String toString() {
return Extensions.GSON.toJson(this);
}
}
static class AccountRegisterEntry implements Serializable {
@SerializedName("account")
String account;
@SerializedName("token")
String token;
@SerializedName("resign")
boolean resign;
public AccountRegisterEntry(String account, String token, boolean resign) {
this.account = account;
this.token = token;
this.resign = resign;
}
@Override
public String toString() {
return Extensions.GSON.toJson(this);
}
}
private String readableTime() {
Date date = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss", Locale.ENGLISH);
return dateFormat.format(date);
}
}
|
package fr.tenebrae.MMOCore.Quests.MMOQuest;
import java.util.ArrayList;
import fr.tenebrae.MMOCore.Entities.MMOEntities.L10AlphaTestZombie;
import fr.tenebrae.MMOCore.Quests.DiscoverCoord;
import fr.tenebrae.MMOCore.Quests.KillCounter;
import fr.tenebrae.MMOCore.Quests.Quest;
import fr.tenebrae.MMOCore.Quests.QuestCondition;
import fr.tenebrae.MMOCore.Quests.QuestObjective;
import fr.tenebrae.MMOCore.Quests.QuestReward;
import fr.tenebrae.MMOCore.Quests.QuestCondition.ConditionType;
import fr.tenebrae.MMOCore.Quests.QuestObjective.ObjectiveType;
import fr.tenebrae.MMOCore.Quests.QuestReward.RewardType;
public class QuestTest2 extends Quest{
private static final long serialVersionUID = -2268661713719735986L;
public QuestTest2(){
super();
QuestCondition condition = new QuestCondition(ConditionType.LEVEL, (int)5, null, null, null);
QuestObjective obj = new QuestObjective(ObjectiveType.DISCOVER, "Test Land", new DiscoverCoord(301.663, 67, -1586.501, 3, 3), null, null);
KillCounter killc = new KillCounter();
QuestObjective obj2 = new QuestObjective(ObjectiveType.KILL, L10AlphaTestZombie.class, 3, killc, null);
QuestReward rew = new QuestReward(RewardType.MONEY, (int)20, null, null, null);
ArrayList<QuestCondition> conditionArr2 = new ArrayList<>();
conditionArr2.add(condition);
ArrayList<QuestObjective> objArr2 = new ArrayList<>();
objArr2.add(obj);
objArr2.add(obj2);
ArrayList<QuestReward> rewardArr2 = new ArrayList<>();
rewardArr2.add(rew);
this.title = "Quêtes Secondaire";
this.description = "Ceci est une description pour la quête secondaire";
this.setNiveauQuete("1");
this.idNom = 70133;
this.idDescription = 70135;
this.setConditions(conditionArr2);
this.setObjectives(objArr2);
this.setReward(rewardArr2);
}
}
|
package com.bingo.code.example.design.state.leaverequestcomplete;
public class Client {
public static void main(String[] args) {
//����ҵ���������ҵ������
LeaveRequestModel lrm = new LeaveRequestModel();
lrm.setUser("��");
lrm.setBeginDate("2010-02-08");
lrm.setLeaveDays(5);
//������������
LeaveRequestContext request = new LeaveRequestContext();
//Ϊ�����Ķ�������ҵ�����ݶ���
request.setBusinessVO(lrm);
//���������ģ���Ϊ��ʼ��״̬���Ժ�Ͳ�����
request.setState(new ProjectManagerState());
//���������ģ��������Ŀ�ʼ������
request.doWork();
}
}
|
package com.example.inspired.simplified;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private boolean mSaveIsChecked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Button actionButton = (Button) findViewById(R.id.action_button);
actionButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.text_form_field);
TextView textView = (TextView) findViewById(R.id.message);
String message = editText.getText().toString();
textView.setText(message);
System.out.println(mSaveIsChecked);
if(mSaveIsChecked){
SharedPreferences.Editor editor = prefs.edit();
editor.putString(message, message);
editor.apply();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("Here");
switch (item.getItemId()){
case R.id.checkbox_save:
mSaveIsChecked = item.isChecked();
return true;
default:
return true;
}
}
}
|
package code;
/**
* Created by likz on 2023/4/26
*
* @author likz
*/
public class SortColors {
public void sortColors(int[] nums) {
int less = -1;
int more = nums.length;
int index = 0;
while(index < more){
if (nums[index] == 1){
index++;
} else if (nums[index] < 1){
swap(nums, ++less, index++);
} else {
swap(nums, --more, index);
}
}
}
public void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
|
package net.npaka.appwidgetex;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
//ホームスクリーンウィジェットを提供するブロードキャストレシーバー(1)
public class AppWidgetEx extends AppWidgetProvider {
//ホームスクリーンウィジェット更新時に呼ばれる
@Override
public void onUpdate(Context context,
AppWidgetManager appWidgetManager,int[] appWidgetIds) {
android.util.Log.e("debug","flag");
//ホームスクリーンウィジェットのイベント処理を担当するサービスの起動(2)
Intent intent=new Intent(context,AppWidgetService.class);
context.startService(intent);
}
}
|
package com.n26.challenge.statistics.service;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.function.BiPredicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.n26.challenge.statistics.model.Transaction;
import com.n26.challenge.statistics.repository.TransactionDao;
/**
* @author dsakho
*
*/
@Service
public class TransactionService {
private TransactionDao transactionDao;
private final BiPredicate<LocalDateTime, LocalDateTime> durationPredicate = (a, b) -> {
return Duration.between(a, b).getSeconds() > Duration.ofSeconds(60).getSeconds();
};
public ResponseEntity<?> addTransaction(final Transaction transaction) {
final LocalDateTime now = LocalDateTime.now();
transactionDao.addTransaction(transaction);
final LocalDateTime transactionTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(transaction.getTimestamp()), ZoneOffset.UTC);
// Returns 204 if transaction is older than 60 seconds, 201 otherwise
if (durationPredicate.test(transactionTime, now)) {
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} else {
return ResponseEntity.status(HttpStatus.CREATED).build();
}
}
@Autowired
public void setTransactionDao(final TransactionDao transactionDao) {
this.transactionDao = transactionDao;
}
}
|
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package basiclibrary;
import java.util.*;
public class Library {
public static void main(String[] args) {
int[] input = new int[]{1, 2, 3, 4, 5};
System.out.println(containsDuplicates(input));
int[] dice = roll(6);
System.out.println(Arrays.toString(dice));
System.out.println(calculateAverage(input));
int[][] weeklyMonthTemperatures = {
{66, 64, 58, 65, 71, 57, 60},
{57, 65, 65, 70, 72, 65, 51},
{55, 54, 60, 53, 59, 57, 61},
{65, 56, 55, 52, 55, 62, 57}
};
System.out.println(lowestAverage(weeklyMonthTemperatures));
analyzeWeatherData(weeklyMonthTemperatures);
List<String> votes = new ArrayList<>();
votes.add("Bush");
votes.add("Bush");
votes.add("Bush");
votes.add("Shrub");
votes.add("Hedge");
votes.add("Shrub");
votes.add("Bush");
votes.add("Hedge");
votes.add("Bush");
votes.add("Shrub");
votes.add("Shrub");
votes.add("Shrub");
List<String> winner = tally(votes);
System.out.println(winner + " received the most votes!");
}
public static int[] roll(int rollNumber) {
int[] dice = new int[rollNumber];
for (int i = 0; i < dice.length; i++) {
dice[i] = (int) ((Math.random() * 6) + 1);
}
return dice;
}
public static boolean containsDuplicates(int[] input) {
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input.length; j++) {
if (j != i && input[i] == input[j]) {
return true;
}
}
}
return false;
}
public static float calculateAverage(int[] input) {
float sum = 0;
for (int i = 0; i < input.length; i++) {
sum += input[i];
}
if (input.length != 0) {
return sum / input.length;
} else {
return 0;
}
}
public static float lowestAverage(int[][] input) {
float lowestAverage = 0;
for(int i = 0; i < input.length; i++) {
float currentAverage = 0;
for(int j = 0; j<input[i].length; j++) {
currentAverage += input[i][j];
}
if (i == 0 && input[i].length != 0) {
lowestAverage = currentAverage/input[i].length;
} else if (input[i].length != 0) {
if (currentAverage/input[i].length < lowestAverage) {
lowestAverage = currentAverage/input[i].length;
}
}
}
if (input.length != 0) {
return lowestAverage;
} else {
return 0;
}
}
public static String analyzeWeatherData(int[][] weather) {
String output = "";
HashSet<Integer> data = new HashSet<>();
for(int i = 0; i < weather.length; i++) {
for(int j = 0; j < weather[i].length; j++) {
data.add(weather[i][j]);
}
}
int lowTemp = Collections.min(data);
int highTemp = Collections.max(data);
System.out.println("High: " + highTemp);
System.out.println("Low: " + lowTemp);
output += "High: " + highTemp + "\n";
output += "Low: " + lowTemp + "\n";
for(int i = lowTemp; i <= highTemp; i++) {
if(!data.contains(i)) {
System.out.println("Never saw temperature: " + i);
output += "Never saw temperature: " + i + "\n";
}
}
return output;
}
public static List<String> tally(List<String> input) {
HashMap<String, Integer> tallyList = new HashMap<>();
for(int i = 0; i < input.toArray().length; i++) {
if(!tallyList.containsKey(input.toArray()[i])) {
tallyList.put(input.toArray()[i].toString(), 1);
} else {
tallyList.put(input.toArray()[i].toString(), tallyList.get(input.toArray()[i].toString()) + 1);
}
}
int maxValue = Collections.max(tallyList.values());
List<String> winner = new ArrayList<>();
for (Map.Entry<String, Integer> candidate : tallyList.entrySet()) {
if (candidate.getValue()==maxValue) {
winner.add(candidate.getKey());
}
}
return winner;
}
}
|
package com.dave.project.util;
import android.util.Log;
import java.util.List;
/**
* 创建和删除db表的语句
* Created by Dave on 2016/12/30.
*/
public class DBTableUtil {
/**
* 返回拼接好的sql语句(主键自动默认设置为_id,自增长)
*
* @param tableName 表名字
* @param clumList clum集合
* @return 返回创建表的语句
*/
public synchronized static String appendCreateTableSqString(String tableName, List<String> clumList) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("create table if not exists").append(" ");
stringBuilder.append(tableName).append(" ");
stringBuilder.append("(_id integer primary key autoincrement,");
for (String clum : clumList) {
stringBuilder.append(clum).append(" ");
if (!clum.equals(clumList.get(clumList.size() - 1))) {
stringBuilder.append("text,");
} else {
stringBuilder.append("text)");
}
}
Log.e("db", stringBuilder.toString());
return stringBuilder.toString();
}
/**
* @param tableName 表明
* @return 返回删除表的语句
*/
public synchronized static String dropTable(String tableName) {
return "DROP TABLE IF EXISTS " + tableName;
}
}
|
package com.wannajob.core.services.company;
public class CompanyUserService {
}
|
package com.module.controllers.veterandialog.tables;
import com.module.model.entity.VeteranWoundEntity;
import com.module.model.entity.WoundDisabilityEntity;
import com.module.model.entity.WoundTypeEntity;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.stage.Stage;
import lombok.Data;
import org.springframework.stereotype.Component;
@Data
@Component
public class AddWoundController {
@FXML
private DatePicker dateField;
@FXML
private ComboBox<WoundDisabilityEntity> disabilityField;
@FXML
private ComboBox<WoundTypeEntity> typeField;
private ObservableList<WoundDisabilityEntity> disabilityEntities = FXCollections.observableArrayList();
private ObservableList<WoundTypeEntity> typeEntities = FXCollections.observableArrayList();
private Stage dialogStage;
private boolean saveClicked = false;
private VeteranWoundEntity woundEntity;
@FXML
public void initialize() {
typeField.setItems(typeEntities);
disabilityField.setItems(disabilityEntities);
}
public boolean isSaveClicked() {
return saveClicked;
}
public void setDialogStage(Stage dialogStage) {
this.dialogStage = dialogStage;
}
public void setWoundEntity(VeteranWoundEntity veteranWoundEntity) {
this.woundEntity = veteranWoundEntity;
typeField.setValue(this.woundEntity.getWoundType());
disabilityField.setValue(this.woundEntity.getWoundDisability());
dateField.setValue(this.woundEntity.getDate());
}
@FXML
private void cancelButtonClick() {
dialogStage.close();
}
@FXML
private void saveButtonClick() {
setNewWoundEntity();
saveClicked = true;
dialogStage.close();
}
private void setNewWoundEntity() {
this.woundEntity.setWoundType(typeField.getValue());
this.woundEntity.setDate(dateField.getValue());
this.woundEntity.setWoundDisability(disabilityField.getValue());
}
}
|
package com.controller;
import com.entity.Department;
import com.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.Map;
/**
* @author roy.zhuo
*/
@Controller
public class DepartmentController {
@Autowired
DepartmentService departmentService;
}
|
package com.changgou.goods.controller;
import com.changgou.goods.pojo.Goods;
import com.changgou.goods.pojo.Spu;
import com.changgou.goods.service.SpuService;
import com.github.pagehelper.Page;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping("/spu")
public class SpuController {
@Autowired
private SpuService spuService;
/**
* 商品批量上架
* @param ids
* @return
*/
@PutMapping("/put/many")
public Result putManySpu(@RequestBody Long[] ids){
spuService.putMany(ids);
return new Result(true,StatusCode.OK,"上架成功");
}
/**
* 商品上架
* @param id
* @return
*/
@PutMapping("/put/{id}")
public Result putSpu(@PathVariable(name="id")Long id){
spuService.putSpu(id);
return new Result(true,StatusCode.OK,"上架成功");
}
/**
* 商品下架
* @param id
* @return
*/
@PutMapping("/pull/{id}")
public Result pullSpu(@PathVariable(name="id")Long id){
spuService.pullSpu(id);
return new Result(true,StatusCode.OK,"下架成功");
}
/**
* //审核商品 自动上架
* @param id spu的ID
* @return
*/
@PutMapping("/audit/{id}")
public Result auditSpu(@PathVariable(name="id")Long id){
spuService.auditSpu(id);
return new Result(true,StatusCode.OK,"审核通过");
}
/**
* Goods(SPU+SKU)增加方法详情
*/
@PostMapping("/save")
public Result save(@RequestBody Goods goods){
spuService.saveGoods(goods);
return new Result(true,StatusCode.OK,"保存商品成功",null);
}
// http://localhost:18081/spu/goods/1146722014917144576
@GetMapping(value = "goods/{id}")
public Result<Goods> findGoodsById(@PathVariable(value = "id")Long spuId){
Goods goods = spuService.findGoodsById(spuId);
return new Result<>(true,StatusCode.OK,"查询Goods成功",goods);
}
/**
* 查询全部数据
* @return
*/
@GetMapping
public Result findAll(){
List<Spu> spuList = spuService.findAll();
return new Result(true, StatusCode.OK,"查询成功",spuList) ;
}
/***
* 根据ID查询数据
* @param id
* @return
*/
@GetMapping("/{id}")
public Result findById(@PathVariable String id){
Spu spu = spuService.findById(id);
return new Result(true,StatusCode.OK,"查询成功",spu);
}
/***
* 新增数据
* @param spu
* @return
*/
@PostMapping
public Result add(@RequestBody Spu spu){
spuService.add(spu);
return new Result(true,StatusCode.OK,"添加成功");
}
/***
* 修改数据
* @param spu
* @param id
* @return
*/
@PutMapping(value="/{id}")
public Result update(@RequestBody Spu spu,@PathVariable String id){
spu.setId(Long.parseLong(id));
spuService.update(spu);
return new Result(true,StatusCode.OK,"修改成功");
}
/***
* 根据ID删除品牌数据
* @param id
* @return
*/
@DeleteMapping(value = "/{id}" )
public Result delete(@PathVariable String id){
spuService.delete(id);
return new Result(true,StatusCode.OK,"删除成功");
}
/***
* 多条件搜索品牌数据
* @param searchMap
* @return
*/
@GetMapping(value = "/search" )
public Result findList(@RequestParam Map searchMap){
List<Spu> list = spuService.findList(searchMap);
return new Result(true,StatusCode.OK,"查询成功",list);
}
/***
* 分页搜索实现
* @param searchMap
* @param page
* @param size
* @return
*/
@GetMapping(value = "/search/{page}/{size}" )
public Result findPage(@RequestParam Map searchMap, @PathVariable int page, @PathVariable int size){
Page<Spu> pageList = spuService.findPage(searchMap, page, size);
PageResult pageResult=new PageResult(pageList.getTotal(),pageList.getResult());
return new Result(true,StatusCode.OK,"查询成功",pageResult);
}
}
|
package util;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Locale;
/**
* @author Klein
* @version 1.1.5
* @date 2018/12/6 11:19
*/
public class SignatureUtil {
public final static String MD5 = "MD5";
public final static String SHA1 = "SHA1";
public final static String SHA256 = "SHA256";
public static String getSignatureStr(Context context, String mPackageName, String mType) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(mPackageName, PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest md = MessageDigest.getInstance(mType);
byte[] publicKey = md.digest(cert);
StringBuffer hexString = new StringBuffer();
for (byte digestByte : publicKey) {
hexString.append((Integer.toHexString((digestByte & 0xFF) | 0x100)).substring(1, 3).toUpperCase(Locale.US));
}
return hexString.toString();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
public static String getSignatureStrSymbol(Context context, String mPackageName, String mType) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(mPackageName, PackageManager.GET_SIGNATURES);
byte[] cert = info.signatures[0].toByteArray();
MessageDigest md = MessageDigest.getInstance(mType);
byte[] publicKey = md.digest(cert);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < publicKey.length; i++) {
String appendString = Integer.toHexString(0xFF & publicKey[i]).toUpperCase(Locale.US);
if (appendString.length() == 1)
hexString.append("0");
hexString.append(appendString);
hexString.append(":");
}
String result = hexString.toString();
return result.substring(0, result.length() - 1);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
|
package com.bjtu.deviceusage.thread;
import android.util.Log;
public class TrackControlThread extends Thread{
private static final String TAG = "TrackControlThread";
@Override
public void run(){
Log.v(TAG, "TrackControlThread run");
}
}
|
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.sync.diffsync;
/**
* Strategy interface for determining if two objects are equivalent.
*
* <p>During the course of a patch, a resource entity may have its properties change, thus rendering it
* unequal to another unchanged instance of the same resource entity. Yet, for the purposes of the
* differential synchronization algorithm, it's important to know if two entity objects are equivalent.
* That is, it's important to know if two objects are considered to represent the same resource, even
* if their properties are different.</p>
*
* @author Craig Walls
*/
public interface Equivalency {
/**
* Determines if two objects are considered equivalent (not necessarily equal).
* @param o1 object to compare
* @param o2 object to compare
* @return true if the two objects are considered equivalent, false otherwise.
*/
boolean isEquivalent(Object o1, Object o2);
}
|
package com.cs4125.bookingapp.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import com.cs4125.bookingapp.controllers.UserController;
import com.cs4125.bookingapp.model.ConcreteUserFactory;
import com.cs4125.bookingapp.model.UserFactory;
import com.cs4125.bookingapp.model.repositories.LogRepository;
import com.cs4125.bookingapp.model.repositories.UserRepository;
import com.cs4125.bookingapp.services.UserServiceImpl;
import com.cs4125.bookingapp.services.interceptor.FilterManager;
import com.cs4125.bookingapp.services.interceptor.LogFilter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
//This creates a DB in memory so it doesn't affect the real DB.
@DataJpaTest
public class UserControllerTests {
private FilterManager myManager;
private LogFilter logFilter;
private UserServiceImpl userServiceMock;
private UserController userControllerMock;
private UserFactory userFactory;
@Autowired
private UserRepository userRepository;
@Autowired
private LogRepository logRepository;
@BeforeEach
public void init(){
myManager = new FilterManager();
logFilter = new LogFilter(logRepository);
userFactory = new ConcreteUserFactory();
userServiceMock = new UserServiceImpl(userRepository, new ConcreteUserFactory());
userControllerMock = new UserController(userServiceMock,myManager,logFilter);
}
//Test the 4 Controllers in separate files.
@Test
public void registerUserTest() {
String message = userControllerMock.addNewUser("Mock","password","mock@gmail.com");
assertEquals("SUCCESS",message.split(":")[0]);
}
@Test
public void loginFailTest() {
String mockUsername = "MOCKUSERNAMETHATNOONEWILLEVERGET";
String mockPassword = "RANDOMPASSWORDTHATNOONEWILLEVERGET";
String message = userControllerMock.getUser(mockUsername,mockPassword);
assertEquals("FAILURE", message.split(":")[0]);
}
@Test
public void LoginTest() { ;
userControllerMock.addNewUser("dummy","testing","dummytesting@gmail.com");
String mockUsername = "dummy";
String mockPassword = "testing";
String message = userControllerMock.getUser(mockUsername,mockPassword);
assertEquals("SUCCESS", message.split(":")[0]);
}
}
|
package it.unirc.pwm.eureca.tessera.dao;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import it.unirc.pwm.eureca.hibernate.util.HibernateUtil;
import it.unirc.pwm.eureca.socio.model.Socio;
import it.unirc.pwm.eureca.tessera.model.Tessera;
public class TesseraDAOImplement implements TesseraDAOInterface
{
private static Logger logger = LogManager.getLogger(TesseraDAOImplement.class);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
public TesseraDAOImplement() {
super();
}
public boolean creaTessera(Tessera t)
{
session = HibernateUtil.getSessionFactory().openSession();
boolean control=false;
try {
transaction=session.beginTransaction();
session.save(t);
logger.info("Tessera inserito");
control=true;
transaction.commit();
} catch (Exception e) {
control=false;
e.printStackTrace();
System.out.println("errore dentro il creaTessera");
transaction.rollback();
} finally{
session.close();
}
return control;
}
public boolean modificaTessera(Tessera t)
{
boolean result=false;
try {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.update(t);
result=true;
logger.info("Utente modificato");
transaction.commit();
} catch (Exception e) {
e.printStackTrace();
logger.info("errore dentro il modificata Utente");
transaction.rollback();
}finally{
session.close();
}
return result;
}
public Tessera getTesseraSocio(Socio s)
{
session = HibernateUtil.getSessionFactory().openSession();
transaction=session.beginTransaction();
Tessera res = null;
try {
res = (Tessera)session.createQuery( "from Tessera where idSocio= :idSocio" ).setParameter("idSocio", s.getIdPersonaFisica()).uniqueResult();
transaction.commit();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
logger.error("errore nella ricerca della TesseraSocio");
}finally{
session.close();
}
return res;
}
}
|
/*
* Program: GameObject.java
* Project: MissileDefense
* Author: J. Ethan Wallace and Michael Gibson
* Date Written: 10/05/2014 - 10/08/2014
* Abstract: This is the abstract class from which all game objects are derived.
* It is not implemented directly, but many of its functions do all the work for its children.
*/
import java.awt.*;
import java.awt.geom.Area;
public abstract class GameObject {
// Whether this can be removed from the game
public boolean canRemove = false;
// The game object this is housed in
protected MDGame game;
// Width/height
protected int width = 35;
protected int height = 75;
// Position on the screen
protected double x, y;
// Color to draw this with
protected Color color=Color.WHITE;
// This class houses the logic steps
public void update() {}
// This class houses the drawing steps
public void render(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
// Get my area for use in both drawing
Area myArea = getArea();
g2d.setColor(color);
g2d.draw(myArea);
g2d.fill(myArea);
if (game.showBoundingBox) {
g2d.setColor(Color.RED);
g2d.draw(myArea);
}
}
// Returns whether this area collides with another
public boolean collides(Area a) {
Area a2 = getArea();
a.intersect(a2);
return !(a.isEmpty());
}
// If hit by something, the onDeath method is called. Although fairly useless in this case,
// this method is overridden by the objects that have health to remove it and only call their
// death when they are out of health
public void hit() {
onDeath();
}
// The actions that must be performed before this object is destroyed
protected void onDeath() {
canRemove = true;
}
// Gets the area of this rectangle for using in both drawing and collision
public Area getArea() {
return new Area(new Rectangle((int)x-width/2, (int)y-height, width, height));
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public int getHeight() {
return height;
}
}
|
package charts;
public class Chart {
}
|
package cnrst.ma.entity;
public enum BoursierEnum {
Rejete,Active,EnListeAttente,EnListePrincipale,Admis,EnCours
}
|
package swm11.jdk.jobtreaming.back.app.lecture.service;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import swm11.jdk.jobtreaming.back.app.lecture.model.LectureQuestion;
import swm11.jdk.jobtreaming.back.app.lecture.repository.LectureQuestionRepository;
import swm11.jdk.jobtreaming.back.constants.PageConstants;
import java.util.List;
import java.util.Optional;
@AllArgsConstructor
@Service("lectureQuestionService")
public class LectureQuestionServiceImpl implements LectureQuestionService {
private LectureQuestionRepository lectureQuestionRepository;
@Override
public List<LectureQuestion> findAll(int pageNum) {
return lectureQuestionRepository.findAll(PageRequest.of(pageNum, PageConstants.pageSize)).getContent();
}
@Override
public List<LectureQuestion> findAllByWriterId(Long writerId, int pageNum) {
return lectureQuestionRepository.findAllByWriter_Id(writerId, PageRequest.of(pageNum, PageConstants.pageSize));
}
@Override
public List<LectureQuestion> findAllByLectureId(Long lectureId, int pageNum) {
return lectureQuestionRepository.findAllByLecture_Id(lectureId, PageRequest.of(pageNum, PageConstants.pageSize));
}
@Override
public Optional<LectureQuestion> findById(Long id) {
return lectureQuestionRepository.findById(id);
}
@Override
public LectureQuestion save(LectureQuestion lectureQuestion) {
return lectureQuestionRepository.save(lectureQuestion);
}
@Override
public void delete(Long id) {
lectureQuestionRepository.deleteById(id);
}
}
|
package collector.event.listener.kafka;
import collector.configuration.EthConfiguration;
import collector.configuration.EthKafkaConfiguration;
import collector.event.EthBlockEvent;
import collector.event.publisher.EthBlockPublisher;
import collector.event.publisher.EthTransactionPublisher;
import collector.message.kafka.EthKafkaProducer;
import collector.rpc.EthRpcServiceManager;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
/**
* @author zacconding
*/
@Slf4j(topic = "listener")
@ConditionalOnBean(value = {EthConfiguration.class, EthKafkaConfiguration.class})
@Component
public class EthBlockKafkaProduceListener {
private EthKafkaProducer ethKafkaProducer;
private EthRpcServiceManager rpcServiceManager;
private EthTransactionPublisher ethTransactionPublisher;
@Autowired
public EthBlockKafkaProduceListener(EthKafkaProducer ethKafkaProducer,
EthBlockPublisher ethBlockPublisher,
EthTransactionPublisher ethTransactionPublisher,
EthRpcServiceManager rpcServiceManager) {
this.ethKafkaProducer = ethKafkaProducer;
this.ethTransactionPublisher = ethTransactionPublisher;
this.rpcServiceManager = rpcServiceManager;
// register
ethBlockPublisher.register(this);
}
/**
* Handle block event
* - produce kafka block message
*/
@Subscribe
@AllowConcurrentEvents
public void onBlock(EthBlockEvent blockEvent) {
if (blockEvent == null) {
logger.warn("receive null block event");
return;
}
logger.debug("## subscribe block event. network : {} / node : {} / block : {} / # tx : {}"
, blockEvent.getNetworkName(), blockEvent.getEthereumNode().getNodeName(), blockEvent.getBlock().getNumber()
, blockEvent.getBlock().getTransactions().size());
ethKafkaProducer.produceEthereumBlockMessage(blockEvent);
}
}
|
package com.github.hippo.server;
import com.github.hippo.bean.HippoRequest;
import com.github.hippo.bean.HippoResponse;
import com.github.hippo.chain.ChainThreadLocal;
import com.github.hippo.enums.HippoRequestEnum;
import com.github.hippo.exception.HippoRequestTypeNotExistException;
import com.github.hippo.exception.HippoServiceException;
import com.github.hippo.util.CommonUtils;
import com.github.hippo.util.FastJsonConvertUtils;
import com.github.hippo.zipkin.SpanKind;
import com.github.hippo.zipkin.ZipkinReq;
import com.github.hippo.zipkin.ZipkinResp;
import com.github.hippo.zipkin.ZipkinUtils;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
/**
* netty handler处理类
*
* @author sl
*/
@Sharable
class HippoServerHandler extends SimpleChannelInboundHandler<HippoRequest> {
private static final Logger LOGGER = LoggerFactory.getLogger(HippoServerHandler.class);
private void handle(ChannelHandlerContext ctx, HippoRequest request) {
long start = System.currentTimeMillis();
HippoRequestEnum hippoRequestEnum = HippoRequestEnum.getByType(request.getRequestType());
ZipkinResp zipkinResp = null;
if (hippoRequestEnum != HippoRequestEnum.PING) {
LOGGER.info("hippo start chainId:{},in param:{}", request.getChainId(), ToStringBuilder.reflectionToString(request));
zipkinResp = zipkinStart(request);
if (zipkinResp != null) {
request.setChainId(zipkinResp.getParentTraceId());
request.setSpanId(zipkinResp.getParentSpanId());
ChainThreadLocal.INSTANCE.setSpanId(request.getSpanId());
} else {
ChainThreadLocal.INSTANCE.clearSpanId();
}
}
HippoResponse response = new HippoResponse();
try {
response.setChainId(request.getChainId());
response.setChainOrder(request.getChainOrder());
response.setServiceName(request.getServiceName());
ChainThreadLocal.INSTANCE.setChainId(request.getChainId());
ChainThreadLocal.INSTANCE.incChainOrder(request.getChainOrder());
response.setRequestId(request.getRequestId());
if (hippoRequestEnum == null) {
response.setError(true);
response.setThrowable(new HippoRequestTypeNotExistException(
"HippoRequest requestType not exist.current requestType is:"
+ request.getRequestType()));
} else if (hippoRequestEnum == HippoRequestEnum.API) {
response.setResult(apiProcess(request));
} else if (hippoRequestEnum == HippoRequestEnum.RPC) {
response.setResult(rpcProcess(request));
} else if (hippoRequestEnum == HippoRequestEnum.PING) {
response.setResult("pong");
response.setRequestId("-99");
}
} catch (Exception e1) {
if (e1 instanceof InvocationTargetException) {
response.setThrowable(e1.getCause());
LOGGER.error("handle error:" + ToStringBuilder.reflectionToString(request), e1.getCause());
} else {
response.setThrowable(e1);
LOGGER.error("handle error:" + ToStringBuilder.reflectionToString(request), e1);
}
response.setError(true);
}
if (hippoRequestEnum != HippoRequestEnum.PING) {
zipkinFinish(zipkinResp, response);
LOGGER.info("hippo end chainId:{} out result:{},耗时:{}毫秒", request.getChainId(), response, System.currentTimeMillis() - start);
}
ChainThreadLocal.INSTANCE.clearTL();
ctx.writeAndFlush(response);
}
private void zipkinFinish(ZipkinResp zipkinResp, HippoResponse response) {
ZipkinCache zipkinCache = HippoServiceCache.INSTANCE.getZipkinCache();
if (zipkinResp != null && zipkinCache.getZipkinRecordService() != null) {
if (response.isError()) {
ZipkinUtils.zipkinRecordError(zipkinResp, zipkinCache.getZipkinRecordService(), response.getThrowable());
}
ZipkinUtils.zipkinRecordFinish(zipkinResp, zipkinCache.getZipkinRecordService());
}
}
private ZipkinResp zipkinStart(HippoRequest request) {
ZipkinCache zipkinCache = HippoServiceCache.INSTANCE.getZipkinCache();
if (zipkinCache.getZipkinRecordService() != null) {
ZipkinReq zipkinReq = fillZipkinData(request);
return ZipkinUtils.zipkinRecordStart(zipkinReq, zipkinCache.getZipkinRecordService());
}
return null;
}
private ZipkinReq fillZipkinData(HippoRequest request) {
ZipkinReq zipkinReq = new ZipkinReq();
zipkinReq.setServiceName(request.getServiceName());
zipkinReq.setMethodName(request.getMethodName());
zipkinReq.setSpanKind(SpanKind.SERVER);
zipkinReq.setAnnotate(request.getMethodName());
Map<String, String> tagMap = new HashMap<>();
tagMap.put("className", request.getClassName());
tagMap.put("methodName", request.getMethodName());
tagMap.put("requestType", HippoRequestEnum.getByType(request.getRequestType()).name());
zipkinReq.setTags(tagMap);
zipkinReq.setParentSpanId(new BigInteger(request.getSpanId(), 16).longValue());
zipkinReq.setParentTraceId(new BigInteger(request.getChainId(), 16).longValue());
return zipkinReq;
}
private Object rpcProcess(HippoRequest paras) throws InvocationTargetException {
return HippoServiceCache.INSTANCE.getImplClassMap().get(paras.getClassName()).getMethod(paras.getMethodName(), paras.getParameterTypes()).invoke(HippoServiceCache.INSTANCE.getImplObjectMap().get(paras.getClassName()), paras.getParameters());
}
/**
* apiProcess 不可能有2个Dto的接口,但是可能有多个基础类型 test(User user,Address add)//不会有这种情况,有也不支持 test(String
* userName,String pwd)//会有
*
* @param paras
* @return
* @throws Exception
*/
private Object apiProcess(HippoRequest paras) throws Exception {
Method _method = HippoServiceCache.INSTANCE.getApiMethodMap().get(paras.getClassName() + "-" + paras.getMethodName());
Class<?> aClass = HippoServiceCache.INSTANCE.getInterfaceMap().get(paras.getClassName());
if (_method == null) {
Method[] methods = aClass.getDeclaredMethods();
for (Method method : methods) {
if (!method.getName().equals(paras.getMethodName())) {
continue;
}
_method = method;
HippoServiceCache.INSTANCE.getApiMethodMap().put(paras.getClassName() + "-" + paras.getMethodName(), method);
break;
}
}
if (_method == null) {
throw new NoSuchMethodException(paras.getClassName() + ":" + paras.getMethodName());
}
Object[] paramDto;
Class<?>[] parameterTypes = _method.getParameterTypes();
FastMethod serviceFastMethod = HippoServiceCache.INSTANCE.getImplClassMap().get(aClass.getName()).getMethod(_method.getName(), parameterTypes);
String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(serviceFastMethod.getJavaMethod());
Object[] objects = paras.getParameters();
// 无参数
if (parameterTypes.length == 0 || objects == null) {
paramDto = null;
}
// 一个参数(是否是Dto)
else if (parameterTypes.length == 1) {
Class<?> parameterType = parameterTypes[0];
paramDto = new Object[1];
// 非自定义dto就是java原生类了
if (CommonUtils.isJavaClass(parameterType)) {
paramDto[0] = covert(getMap(objects).get(parameterNames[0]), parameterType);
} else {
paramDto[0] = FastJsonConvertUtils.jsonToJavaObject((String) objects[0], parameterType);
}
}
// 多参
else {
paramDto = new Object[parameterNames.length];
int index = 0;
Map<String, Object> map = getMap(objects);
for (String parameter : parameterNames) {
paramDto[index] = covert(map.get(parameter), parameterTypes[index]);
index++;
}
}
// 拿到返回
return FastJsonConvertUtils.cleanseToObject(serviceFastMethod.invoke(HippoServiceCache.INSTANCE.getImplObjectMap().get(aClass.getName()), paramDto));
}
/**
* 常用类转换
*
* @param o 原始数据
* @param parameterType 转换后的类型
* @return 转换后的数据
*/
private Object covert(Object o, Class<?> parameterType) {
if (o == null) {
return null;
}
String param = String.valueOf(o);
if (parameterType == long.class || parameterType == Long.class) {
return Long.valueOf(param);
} else if (parameterType == int.class || parameterType == Integer.class) {
return Integer.valueOf(param);
} else if (parameterType == double.class || parameterType == Double.class) {
return Double.valueOf(param);
} else if (parameterType == float.class || parameterType == Float.class) {
return Float.valueOf(param);
} else if (parameterType == boolean.class || parameterType == Boolean.class) {
return Boolean.valueOf(param);
} else if (parameterType == BigDecimal.class) {
return new BigDecimal(param);
} else if (parameterType == String.class) {
return param;
}
throw new HippoServiceException("数据转换失败,请检查接口参数,原始数据:" + param + ",转换类型:" + parameterType.getName());
}
private Map<String, Object> getMap(Object[] objects) {
if (objects.length == 1) {
return FastJsonConvertUtils.jsonToMap((String) objects[0]);
} else {
return new HashMap<>();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LOGGER.error("netty server error", cause.fillInStackTrace());
ctx.close();
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, HippoRequest request) throws Exception {
if (request != null && request.getRequestType() == HippoRequestEnum.PING.getType()) {
// 单独的线程去执行心跳操作,业务请求不影响心跳
HippoServerThreadPool.SINGLE.getPool().execute(() -> handle(ctx, request));
} else {
HippoServerThreadPool.FIXED.getPool().execute(() -> handle(ctx, request));
}
}
}
|
/**
* LibraryConfiguration.java
*/
package org.crf.libmatrix.core;
import java.util.Map;
import java.util.HashMap;
/**
*
* @author cvirtue
* @version "%I%, %G%"
*/
public class LibraryConfiguration {
/**
* Overrides the configuration value specified by its name by the value
* passed as argument.
* <p>
* Also returns the previous value set.
*
* @param name
* @param value
* @return the original value
* */
public static final Object set(final String name, final Object value) {
return CONFIGURATION.put(name, value);
}
/**
* @param name
* @return the current value corresponding to the name specified
* */
public static final Object get(final String name) {
return CONFIGURATION.get( name );
}
public static final String MTX_THREAD_COUNT = "mtx-thread-count";
private static final Map<String, Object> CONFIGURATION;
static {
CONFIGURATION = new HashMap<>();
CONFIGURATION.put(MTX_THREAD_COUNT, Integer.valueOf(8));
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.clerezza;
/**
* An <a href= "http://www.w3.org/TR/rdf11-concepts/#dfn-rdf-term" >RDF-1.1
* Term</a>, as defined by <a href= "http://www.w3.org/TR/rdf11-concepts/"
* >RDF-1.1 Concepts and Abstract Syntax</a>, a W3C Recommendation published on
* 25 February 2014.<br>
*
* @see <a href= "http://www.w3.org/TR/rdf11-concepts/#dfn-rdf-term" >RDF-1.1
* Term</a>
*/
public interface RDFTerm {
}
|
package Model;
public class Edge {
private double cost;
private int firstVertexId;
private int secondVertexId;
public Edge(double cost, int firstVertexId, int secondVertexId) {
this.cost = cost;
this.firstVertexId = firstVertexId;
this.secondVertexId = secondVertexId;
}
public double getCost() {
return this.cost;
}
public int getFirstVertexId() {
return firstVertexId;
}
public int getSecondVertexId() {
return secondVertexId;
}
}
|
// Queue class to help parse the txt file
// Holds individual words with no outer punctuation
public class Queue
{
// pointers for the front and the rear of the queue
private QNode front;
private QNode rear;
private QNode beginning;
//constructor to assign front and rear to null
public Queue()
{
beginning = null;
front = null;
rear = null;
}
public void enqueue(String element)
{
//creates new node with given string
QNode newNode = new QNode(element);
//checks if list is empty
if (rear == null)
{
front = newNode;
beginning = newNode;
}
else
{
rear.setLink(newNode);
}
rear = newNode;
}
public void restore() //sets queue back to original queue without re-parsing text file
{
front = beginning;
}
public String dequeue()
{
//checks for an empty queue
if (isEmpty())
{
throw new QueueUnderflowException("Dequeue attempted on empty queue.");
}
else
{
// returns the first thing in the queue and sets front to the next item in line
String element;
element = front.getInfo();
front = front.getLink();
if(front == null)
rear = null;
return element;
}
}
// checks if the queue is empty
public boolean isEmpty()
{
if (front == null)
return true;
else
return false;
}
}
|
package com.teaman.accessstillwater.ui.establishment;
import android.content.Context;
import android.support.v7.widget.AppCompatRatingBar;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.squareup.picasso.Picasso;
import com.teaman.accessstillwater.AccessStillwaterApp;
import com.teaman.accessstillwater.R;
import com.teaman.accessstillwater.base.ItemCallback;
import com.teaman.accessstillwater.utils.StringUtils;
import com.teaman.data.entities.Activity;
import com.teaman.data.entities.Establishment;
import com.teaman.data.entities.Review;
import com.teaman.data.entities.json.Results;
import com.teaman.data.entities.json.places.PlaceEntity;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by weava on 3/14/16.
*/
public class EstablishmentViewHolder extends RecyclerView.ViewHolder {
@Bind(R.id.establishment_name)
protected TextView mEstablishmentName;
@Bind(R.id.establishment_picture)
protected ImageView mEstablishmentImage;
@Bind(R.id.linear_star_layout)
protected LinearLayout mReviewStarsLayout;
@Bind(R.id.rating_bar_establishment)
protected AppCompatRatingBar mEstablishmentStarViews;
private PlaceEntity mPlaceEntity;
private Establishment mEstablishment;
private ItemCallback<Establishment> mEstablishmentItemCallback;
private Context mContext;
private List<Review> mEstablishmentReviews;
public EstablishmentViewHolder(View itemView, ItemCallback<Establishment> establishmentItemCallback, Context context) {
super(itemView);
ButterKnife.bind(this, itemView);
mContext = context;
mEstablishmentItemCallback = establishmentItemCallback;
}
private void setView() {
if(mPlaceEntity.getName() != null) {
mEstablishmentName.setText(mPlaceEntity.getName());
}
if(mPlaceEntity.getPhotos().size() > 0) {
if (mPlaceEntity.getPhotos().get(0).getPhotoReference() != null) {
Picasso.with(mContext)
.load(StringUtils.MAPS_API_PHOTO_URL + mPlaceEntity.getPhotos().get(0).getPhotoReference())
.fit()
.into(mEstablishmentImage);
}
}
int totalScore = mEstablishment.getTotalRatingWithReviews(mEstablishmentReviews);
Log.d("Total Revies", "" + mEstablishmentReviews.size());
Log.d("Total Score", "" + totalScore);
if(totalScore >= 0) {
mEstablishmentStarViews.setRating(totalScore);
} else {
mReviewStarsLayout.setVisibility(View.GONE);
}
}
@Override
public String toString() {
return super.toString();
}
public void bind(Establishment est) {
mEstablishment = est;
mEstablishmentReviews = new ArrayList<>();
Log.d("EstablishmentViewHolder", mEstablishment.getPlacesId());
AccessStillwaterApp.getmInstance().getPlacesApi().getAllDetails(mEstablishment.getPlacesId()).enqueue(new Callback<Results<PlaceEntity>>() {
@Override
public void onResponse(Call<Results<PlaceEntity>> call, Response<Results<PlaceEntity>> response) {
mPlaceEntity = response.body().getSingleResult();
Activity.getQuery()
.whereEqualTo("establishment", mEstablishment)
.whereEqualTo("type", Activity.TYPE_REVIEW)
.include("review")
.findInBackground(new FindCallback<Activity>() {
@Override
public void done(List<Activity> objects, ParseException e) {
if(objects != null) {
if(objects.size() > 0) {
for (Activity act : objects) {
if(act.getReview() != null) {
Review rev = act.getReview().fromParseObject(act.getReview());
mEstablishmentReviews.add(rev);
}
}
}
}
setView();
}
});
}
@Override
public void onFailure(Call<Results<PlaceEntity>> call, Throwable t) {
}
});
}
}
|
package com.fanooos.ScatterAndGather.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.router.HeaderValueRouter;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;
import com.fanooos.ScatterAndGather.model.User;
@Service
public class UserService {
@Value("${app.external.resources.urls}")
private List<String> urls;
private final String headerName = "RESOURCE_DOMAIN";
@Autowired
private HeaderValueRouter router;
@Autowired
private QueueChannel resultsChannel;
public List<User> getUsers() {
this.broadcast();
List<User> users = new ArrayList<>();
Message<?> message = resultsChannel.receive();
if (Objects.nonNull(message)) {
users = (List<User>) message.getPayload();
}
return users;
}
private void broadcast() {
System.out.println("Before Broadcasting");
urls.stream().forEach(url -> {
String domain = url.split("\\|")[0];
String resourceurl = url.split("\\|")[1].substring(0);
Message<String> message = MessageBuilder.withPayload(resourceurl).setHeader(headerName, domain).build();
router.handleMessage(message);
});
System.out.println("After Broadcasting");
}
}
|
package com.lupan.HeadFirstDesignMode.chapter8_template;
/**
* TODO
*
* @author lupan
* @version 2016/3/24 0024
*/
public abstract class CaffeineBeverage {
/**
* 模板方法
*/
public void prepareRecipe(){
System.out.println("准备咖啡因饮料。。。");
boilWater();
pureInCup();
brew();
//判断钩子
if(wantsCondiments()){
addCondiments();
}
}
private void boilWater(){
System.out.println("烧开水。。。");
}
private void pureInCup(){
System.out.println("开水倒入杯子中。。。");
}
protected abstract void brew();
protected abstract void addCondiments();
/**
* 钩子方法
* @return 默认为真
*/
protected boolean wantsCondiments(){
return true;
}
}
|
package graph;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
public class MinGenerateTree {
// 边
class edges{
int weight;
int point1;
int point2;
public edges(int weight, int point1, int point2) {
this.weight = weight;
this.point1 = point1;
this.point2 = point2;
}
}
// 最小数生成一共有俩种算法,第一种就是prim算法,第二种就是kruskal克鲁斯卡尔算法
// 俩种都是贪心算法,不过一个全部贪心来看,一个局部集合贪心
// prim算法,其中用优先队列来存储最重要的边关系
public List<edges> primAlgorithm(int[][] map) {
int map_size = map.length;
// 需要一个数组表示是否已经加入到已访问集合中
boolean[] visited_vector = new boolean[map_size];
Arrays.fill(visited_vector, false);
// 表示已访问集合到未访问集合中的路径
// 这里是优先队列,也要设置比较方法
PriorityQueue<edges> edge_queue = new PriorityQueue<edges>(new Comparator<edges>() {
public int compare(edges e1, edges e2) {
return e1.weight - e2.weight;
}
});
// 输出的路径顺序
List<edges> edge_list = new LinkedList<edges>();
int start = 0;
// 访问节点,并且将之全部的边都加入到优先队列中
for(int index = 0; index < map_size - 1; index++) {
visited_vector[start] = true;
for(int col = 0; col < map_size; col++) {
// 将路径加入到优先队列
if(map[start][col] != -1 && map[start][col] != 0) {
edges e = new edges(map[start][col], start, col);
edge_queue.offer(e);
}
}
// 拿出最小的路径,并且还是未访问过的点
edges min_weight = edge_queue.poll();
while(visited_vector[min_weight.point2]) min_weight = edge_queue.poll();
edge_list.add(min_weight);
start = min_weight.point2;
}
return edge_list;
}
// 克鲁斯卡尔算法,它与普利姆算法最大的不同就是它从全部边来看的
// 它需要并查集来看是否形成了环
public List<edges> kruskalAlgorithm(int[][] map){
int map_len = map.length;
// 输出的路径顺序
List<edges> edge_list = new LinkedList<edges>();
PriorityQueue<edges> edge_queue = new PriorityQueue<edges>(new Comparator<edges>(){
public int compare(edges e1, edges e2) {
return e1.weight - e2.weight;
}
});
// 并查集,表示它所在集合中,代表节点是哪个节点,开始默认的代表都是自身
Map<Integer, Integer> node_map = new HashMap<Integer, Integer>();
// 将图中所有的边都提取出来,并且初始化并查集
for(int first_index = 0; first_index < map_len - 1; first_index++) {
for(int second_index = first_index + 1; second_index < map_len; second_index++) {
if(map[first_index][second_index] != -1) {
edges e = new edges(map[first_index][second_index], first_index, second_index);
edge_queue.offer(e);
}
}
node_map.put(first_index, -1);
}
node_map.put(map_len - 1, -1);
while(edge_list.size() < map_len - 1) {
edges e = edge_queue.poll();
// 检查这条边加入是否会形成环路
while(getPoint(node_map,e.point1) == getPoint(node_map,e.point2)) {
e = edge_queue.poll();
}
// 如果不形成环路,那么就合并它们,其实就是改变并查集
edge_list.add(e);
// 这里的更新要注意是更新代表节点
node_map.put(getPoint(node_map,e.point2), getPoint(node_map, e.point1));
}
return edge_list;
}
// 得到节点所在集合的代表节点
public int getPoint(Map<Integer, Integer> node_map, int point) {
int key = point;
while(node_map.get(key) != -1) {
key = node_map.get(key);
}
return key;
}
public static void main(String[] args) {
// 图的邻接矩阵,-1表示不可达
// int[][] map = {
// {0,5,1,-1,-1,-1},
// {5,0,2, 1,-1,-1},
// {1,2,0, 4, 8,-1},
// {-1,1,4,0,3,6},
// {-1,-1,8,3,0,-1},
// {-1,-1,-1,6,-1,0}
// };
int[][] map = {
{0,2,2,3},
{2,0,-1,2},
{2,-1,0,2},
{3,2,2,0},
};
MinGenerateTree mgt = new MinGenerateTree();
List<edges> edge_list = mgt.primAlgorithm(map);
// List<edges> edge_list = mgt.kruskalAlgorithm(map);
for(edges e:edge_list) {
System.out.println(e.point1 + "-->" + e.point2 + ":" + e.weight);
}
}
}
|
package dev.felicity.felicity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.content.Intent;
import com.google.firebase.auth.FirebaseAuth;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.firebase.auth.AuthResult;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import android.support.annotation.NonNull;
public class Login extends AppCompatActivity {
private Button mLoginButton;
private EditText mEmail;
private EditText mPassword;
private android.widget.TextView mSignup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mEmail= findViewById(R.id.email);
mPassword=findViewById(R.id.password);
mLoginButton= findViewById(R.id.login);
mAuth= FirebaseAuth.getInstance();
mSignup= findViewById(R.id.signup);
mLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startSignIn();
}
});
mAuthListener= new FirebaseAuth.AuthStateListener(){
@Override
public void onAuthStateChanged(@android.support.annotation.NonNull FirebaseAuth firebaseAuth){
if(firebaseAuth.getCurrentUser()!=null && firebaseAuth.getCurrentUser().isEmailVerified()){
startActivity(new Intent(Login.this, LandingPage.class));
finish();
}
}
};
}
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void startSignIn(){
String email= mEmail.getText().toString();
String password= mPassword.getText().toString();
if(android.text.TextUtils.isEmpty(email) || TextUtils.isEmpty(password)){
Toast.makeText(Login.this,"Fields cannot be empty",Toast.LENGTH_LONG).show();
}
else{
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(Login.this,"Login Failed",Toast.LENGTH_LONG).show();
}
else if(!mAuth.getCurrentUser().isEmailVerified()){
Toast.makeText(Login.this,"You must verify email first",Toast.LENGTH_LONG).show();
mAuth.signOut();
}
}
});
}
}
public void goToSignUp(View v){
startActivity(new Intent(Login.this, Signup.class));
}
}
|
package Basics;
public class Armstrongno
{
public static void main(String[] args)
{
int n=153,r,s=0;
int a=n;
while(a>0)
{
r=a%10;
a=a/10;
s=s+r*r*r;
}
if(s==n)
System.out.println(s+" A Armstrong number.");
else
System.out.println("Not a Armstrong number.");
}
}
|
package com.croxx.hgwechat.res.didiumbrella;
import com.croxx.hgwechat.model.didiumbrella.DidiUmbrellaOrder;
import java.util.List;
public class ResDidiUmbrellaWithOrders extends ResDidiUmbrella {
private List<DidiUmbrellaOrder> orders;
public ResDidiUmbrellaWithOrders() {
}
public ResDidiUmbrellaWithOrders(int errcode, String errmsg, List<DidiUmbrellaOrder> orders) {
super(errcode, errmsg);
this.orders = orders;
}
/* Getters & Setters */
public List<DidiUmbrellaOrder> getOrders() {
return orders;
}
public void setOrders(List<DidiUmbrellaOrder> orders) {
this.orders = orders;
}
}
|
import java.util.Scanner;
public class P22 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final long first = Util.promptLongData("Enter the first number ", sc);
final long second = Util.promptLongData("Enter the second number ", sc);
final long third = Util.promptLongData("Enter the third number ", sc);
if (first == second || first == third || second == third){
return;
}
final long max = Math.max(first, Math.max(second, third));
System.out.println("The largest number is " + max);
sc.close();
}
}
|
package com.ygrik.currencyrate.app.api.retrofit;
import com.ygrik.currencyrate.app.network.models.CurrencyRate;
public interface Callback<T> {
void onFinish(T model);
void onError(String errorMessage);
}
|
package com.tencent.mm.ui.contact;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import com.tencent.mm.model.s;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.f;
import com.tencent.mm.ui.contact.AddressUI.a;
class AddressUI$a$3 implements OnItemLongClickListener {
final /* synthetic */ a uhE;
AddressUI$a$3(a aVar) {
this.uhE = aVar;
}
public final boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long j) {
x.i("MicroMsg.AddressUI", "onItemLongClick, targetview is SearchBar::ListView, pos = " + i);
if (i < a.c(this.uhE).getHeaderViewsCount()) {
x.w("MicroMsg.AddressUI", "on item long click, but match header view");
return true;
} else if (a.g(this.uhE) != null && a.g(this.uhE).uFK) {
return true;
} else {
f fVar = (f) a.a(this.uhE).Dy(i - a.c(this.uhE).getHeaderViewsCount());
if (fVar == null) {
x.e("MicroMsg.AddressUI", "cont is null. position:%d, header count:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(a.c(this.uhE).getHeaderViewsCount())});
return true;
}
String str = fVar.field_username;
if (s.hE(str) || s.hF(str)) {
return true;
}
a.b(this.uhE, str);
a.l(this.uhE).a(view, i, j, this.uhE, a.i(this.uhE), a.j(this.uhE), a.k(this.uhE));
return true;
}
}
}
|
package com.javazuki.sample.javaee.request;
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;
@WebServlet(urlPatterns = { "/aaa/bbb/*" })
public class DisplayURIInfoServlet extends HttpServlet {
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// http://localhost:8080/javazuki-sample-javaee/aaa/bbb/ccc.html?d=e&f=g でアクセスするとQueryStringまで表示される
System.out.println("DisplayURIInfoServlet doGet() called");
System.out.println();
System.out.println("request.getRequestURL() : " + request.getRequestURL());
System.out.println("request.getRequestURI() : " + request.getRequestURI());
System.out.println("request.getContextPath() : " + request.getContextPath());
System.out.println("request.getServletPath() : " + request.getServletPath());
System.out.println("request.getPathInfo() : " + request.getPathInfo());
System.out.println("request.getQueryString() : " + request.getQueryString());
System.out.println();
System.out.println("DisplayURIInfoServlet doGet() called");
}
}
|
package com.tencent.mm.protocal.c;
import f.a.a.c.a;
import java.util.LinkedList;
public final class byz extends bhd {
public int rth;
public int rxG;
public long rxH;
public String seC;
public cak suK;
public cak suL;
public long suO;
public int suY;
public int suZ;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.shX != null) {
aVar.fV(1, this.shX.boi());
this.shX.a(aVar);
}
if (this.seC != null) {
aVar.g(2, this.seC);
}
aVar.fT(3, this.rxG);
aVar.fT(4, this.suY);
if (this.suK != null) {
aVar.fV(5, this.suK.boi());
this.suK.a(aVar);
}
if (this.suL != null) {
aVar.fV(6, this.suL.boi());
this.suL.a(aVar);
}
aVar.T(7, this.rxH);
aVar.fT(8, this.rth);
aVar.T(9, this.suO);
aVar.fT(10, this.suZ);
return 0;
} else if (i == 1) {
if (this.shX != null) {
fS = f.a.a.a.fS(1, this.shX.boi()) + 0;
} else {
fS = 0;
}
if (this.seC != null) {
fS += f.a.a.b.b.a.h(2, this.seC);
}
fS = (fS + f.a.a.a.fQ(3, this.rxG)) + f.a.a.a.fQ(4, this.suY);
if (this.suK != null) {
fS += f.a.a.a.fS(5, this.suK.boi());
}
if (this.suL != null) {
fS += f.a.a.a.fS(6, this.suL.boi());
}
return (((fS + f.a.a.a.S(7, this.rxH)) + f.a.a.a.fQ(8, this.rth)) + f.a.a.a.S(9, this.suO)) + f.a.a.a.fQ(10, this.suZ);
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
byz byz = (byz) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
f.a.a.a.a aVar4;
boolean z;
cak cak;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
fk fkVar = new fk();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) {
}
byz.shX = fkVar;
}
return 0;
case 2:
byz.seC = aVar3.vHC.readString();
return 0;
case 3:
byz.rxG = aVar3.vHC.rY();
return 0;
case 4:
byz.suY = aVar3.vHC.rY();
return 0;
case 5:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
cak = new cak();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = cak.a(aVar4, cak, bhd.a(aVar4))) {
}
byz.suK = cak;
}
return 0;
case 6:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
cak = new cak();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = cak.a(aVar4, cak, bhd.a(aVar4))) {
}
byz.suL = cak;
}
return 0;
case 7:
byz.rxH = aVar3.vHC.rZ();
return 0;
case 8:
byz.rth = aVar3.vHC.rY();
return 0;
case 9:
byz.suO = aVar3.vHC.rZ();
return 0;
case 10:
byz.suZ = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package net.acomputerdog.lccontroller.gui;
import net.acomputerdog.lccontroller.LaserProperties;
import net.acomputerdog.lccontroller.gui.script.ScriptRunner;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class ComponentScriptPath extends JPanel {
public static final int LINES_PER_TICK = 100;
// cant put in constructor because IntelliJ builder runs before window constructor
private GUIMain main;
private final Color BG_COLOR = new Color(222, 238, 239);
private final Color GRAPH_COLOR = new Color(204, 206, 206);
private final Color PATH_COLOR = Color.RED;
private BufferedImage image;
private ScriptRunner script;
private boolean isDrawing = false;
private int nextLine = 0;
private long lastGX, lastGY;
private int lastIX, lastIY;
// scaling stuff
//private int imageStartX, imageStartY, imageWidth, imageHeight;
private double scaleLevel = 0.001d;
public GUIMain getMain() {
return main;
}
public void setMain(GUIMain main) {
this.main = main;
}
public ScriptRunner getScript() {
return script;
}
public void setScript(ScriptRunner script) {
this.script = script;
LaserProperties prop = main.getLaserProperties();
this.image = new BufferedImage(prop.getBedWidth(), prop.getBedHeight(), BufferedImage.TYPE_4BYTE_ABGR);
drawGrid(image.getGraphics(), image.getWidth(), image.getHeight());
//updateScale(image.getWidth(), image.getHeight(), getWidth(), getHeight());
//drawScript(image.getGraphics(), image.getWidth(), image.getHeight());
nextLine = 0;
scaleLevel = 0.001d;
isDrawing = true;
main.addLogLine("Starting script draw.");
//super.repaint();
}
public void updateDraw() {
if (isDrawing) {
String[] lines = script.getLines();
Graphics g = image.getGraphics();
g.setColor(PATH_COLOR);
for (int i = 0; i < LINES_PER_TICK; i++) {
if (nextLine >= lines.length) {
// we are finished, so we need to redraw
isDrawing = false;
repaint();
main.addLogLine("Script draw complete.");
break;
} else {
long lX = lastGX;
long lY = lastGY;
String line = lines[nextLine];
try {
if (line.startsWith("G0") || line.startsWith("G1")) {
int xIdx = line.indexOf('X');
if (xIdx > -1 && line.length() - xIdx > 2) {
int spaceIdx = line.indexOf(' ', xIdx);
if (spaceIdx > -1) {
lX = Long.parseLong(line.substring(xIdx + 1, spaceIdx));
} else {
lX = Long.parseLong(line.substring(xIdx + 1));
}
}
int yIdx = line.indexOf('Y');
if (yIdx > -1 && line.length() - yIdx > 2) {
int spaceIdx = line.indexOf(' ', yIdx);
if (spaceIdx > -1) {
lY = Long.parseLong(line.substring(yIdx + 1, spaceIdx));
} else {
lY = Long.parseLong(line.substring(yIdx + 1));
}
}
int iX = (int) Math.round(((double) lX * scaleLevel));
int iY = (int) Math.round(((double) lX * scaleLevel));
// draw line from lastIX, lastIY -> iX, iY
drawThickLine(g, lastIX, lastIY, iX, iY, 3);
//System.out.printf("Drawing from (%d, %d) to (%d, %d)\n", lastIX, lastIY, iX, iY);
lastIX = iX;
lastIY = iY;
lastGX = lX;
lastGY = lY;
}
} catch (NumberFormatException e) {
main.addLogLine(String.format("Preview failed: malformed gcode on line %d: %s", nextLine, line));
isDrawing = false;
break;
}
nextLine++;
}
}
}
}
void drawThickLine(Graphics g, int x1, int y1, int x2, int y2, int width) {
if (width > 0) {
g.drawLine(x1, y1, x2, y2);
if (width > 1) {
int currSide = 1;
// not a line
if (x1 == x2 && y1 == y2) {
return;
// horizontal line
} else if (y1 == y2) {
for (int i = 1; i < width; i++) {
int newY = y1 + (i * currSide);
g.drawLine(x1, newY, x2, newY);
currSide *= -1;
}
// vertical or diagonal line
} else if (x1 == x2) {
for (int i = 1; i < width; i++) {
int newX = x1 + (i * currSide);
g.drawLine(newX, y1, newX, y2);
currSide *= -1;
}
}
}
}
}
/*
private void updateScale(int imWidth, int imHeight, int viewWidth, int viewHeight) {
//TODO implement scale
int xSizeDiff = imWidth - viewWidth;
int ySizeDiff = imHeight - viewHeight;
int xSizeDiffPerSide = xSizeDiff / 2;
int ySizeDiffPerSide = ySizeDiff / 2;
imageStartX = -xSizeDiffPerSide;
imageStartY = -ySizeDiffPerSide;
imageWidth = viewWidth + xSizeDiff; // account for both edges
imageHeight = viewHeight + ySizeDiff; // account for both edges
}
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawBackground(g, getWidth(), getHeight());
if (image != null && !isDrawing) {
int widthDiff = getWidth() - image.getWidth();
int heightDiff = getHeight() - image.getHeight();
int widthMag = Math.abs(widthDiff);
int heightMag = Math.abs(heightDiff);
//System.out.printf("Component (%d, %d) - image (%d, %d) = diff (%d, %d)\n", getWidth(), getHeight(), image.getWidth(), image.getHeight(), widthDiff, heightDiff);
float rat;
if (widthMag > heightMag) {
rat = (float) getWidth() / (float) image.getWidth();
} else {
rat = (float) getHeight() / (float) image.getHeight();
}
float outWidthF = rat * (float) image.getWidth();
float outHeightF = rat * (float) image.getHeight();
// check for overflow
if (outWidthF > getWidth()) {
float downscale = getWidth() / outWidthF;
outWidthF = outWidthF * downscale;
outHeightF = outHeightF * downscale;
} else if (outHeightF > getHeight()) {
float downscale = getHeight() / outHeightF;
outWidthF = outWidthF * downscale;
outHeightF = outHeightF * downscale;
}
int outWidth = Math.round(outWidthF);
int outHeight = Math.round(outHeightF);
// TODO center
//System.out.printf("image (%d, %d) * rat (%f) = size (%d, %d)\n", image.getWidth(), image.getHeight(), rat, outWidth, outHeight);
//System.out.printf("Drawing image from (%d, %d) to (%d, %d)\n", 0, 0, outWidth, outHeight);
g.drawImage(image, 0, 0, outWidth, outHeight, BG_COLOR, null);
}
}
private void drawBackground(Graphics g, int width, int height) {
g.setColor(BG_COLOR);
g.fillRect(0, 0, width, height);
}
private void drawScript(Graphics g, int width, int height) {
drawGrid(g, width, height);
}
private void drawGrid(Graphics g, int width, int height) {
g.setColor(GRAPH_COLOR);
// draw border
g.drawRect(0, 0, width - 1, height - 1);
g.drawRect(1, 1, width - 2, height - 2);
//TODO apply to actual scale
// slow, but necessary
float xSpacing = width / 10f;
float ySpacing = height / 10f;
// vertical lines
for (int x = 0; x < 10; x++) {
int xLoc = Math.round((float) x * xSpacing);
drawThickLine(g, xLoc, 0, xLoc, height, 2);
}
// horizontal lines
for (int y = 0; y < 10; y++) {
int yLoc = Math.round((float) y * ySpacing);
drawThickLine(g, 0, yLoc, width, yLoc, 2);
}
}
public boolean isDrawing() {
return isDrawing;
}
}
|
/**
* DateValidator.java
*
* Skarpetis Dimitris 2016, all rights reserved.
*/
package dskarpetis.elibrary.ui.validator;
import java.util.Date;
/**
* Common date validator that define min and max range
*
* @author dskarpetis
*/
public class DateValidator {
/**
* Regular expression pattern in the form of String.
*/
private final Date minimum;
private final Date maximum;
/**
* Default Constructor.
*
* @param minimum
* @param maximum
*
*/
public DateValidator(Date minimum, Date maximum) {
super();
if (minimum == null || maximum == null) {
throw new IllegalArgumentException("Missing data");
}
this.minimum = minimum;
this.maximum = maximum;
}
/**
* @param validatable
* @return true
*/
public boolean validate(final Date validatable) {
if (validatable == null) {
throw new IllegalArgumentException("Missing data");
} else if (validatable.before(maximum) && validatable.after(minimum)) {
return true;
} else {
return false;
}
}
}
|
package day46_encapsulation;
public class CapitalOne {
public static void main(String[] args) {
CheckingAccount myBank =new CheckingAccount();
myBank.setAccountNumber(45612398456554L);
System.out.println("Account number is " + myBank.getAccountNumber());
myBank.setAccountHolder("Mike Smith");
System.out.println("Account holder is "+myBank.getAccountHolder());
myBank.setBalance(256);
System.out.println("Balance is " +myBank.getBalance());
myBank.setType("360 checking");
System.out.println("type is " +myBank.getType());
// myBank.getBalance();
System.out.println(myBank);
System.out.println("#########################");
}
}
|
package LeetCodeUtils.Experience.test;
import LeetCodeUtils.Experience.sortBean.BubbleSort;
import LeetCodeUtils.Experience.container.Container;
public class AnnotationTest {
public static void main(String[] args) throws Exception {
Container ioc = new Container();
BubbleSort bean1 = (BubbleSort) ioc.getBean("bubbleSort");
}
}
|
/**
* @author zxq876 Zetian Qin
* The solution of Worksheet2.
*/
public class Worksheet2 implements Worksheet2Interface {
// Exercise 1
static Tree<Integer> negateAll(Tree<Integer> t) {
if(t.isEmpty()) {
return new Tree<Integer>();
}
else {
return new Tree<Integer>(0 - t.getValue(), negateAll(t.getLeft()), negateAll(t.getRight()));
}
}
// Exercise 2
static boolean allEven(Tree<Integer> a) {
if(a.isEmpty()) {
return true;
}
else if(a.getValue() % 2 == 0) {
return true && allEven(a.getLeft()) && allEven(a.getRight());
}
else {
return false;
}
}
// Exercise 3
static int depth(Tree<Integer> a, int x) {
if(a.isEmpty()) {
return -1;
}
else if(a.getValue() == x) {
return 0;
}
else {
return Math.max(depth(a.left, x) == -1 ? -1 : depth(a.left, x) + 1, depth(a.right, x) == -1 ? -1 : depth(a.right, x) + 1);
}
}
// Exercise 4
static <E> List<E> preorder(Tree<E> a) {
if(a.isEmpty()) {
return new List<E>();
}
else if(!a.getLeft().isEmpty() && a.getRight().isEmpty()) {
return new List<E>(a.getValue(), preorder(a.getLeft()));
}
else if(a.getLeft().isEmpty() && !a.getRight().isEmpty()) {
return new List<E>(a.getValue(), preorder(a.getRight()));
}
else if(a.getLeft().isEmpty() && a.getRight().isEmpty()) {
return new List<E>(a.getValue(), new List<E>());
}
else {
return append(new List<E>(a.getValue(), preorder(a.getLeft())), preorder(a.getRight()));
}
}
/**
* helper method, for appending the List M to the tail of List L
* @param L List at the beginning, List
* @param M LIst at the end, List
* @param <E> generics parameter
* @return new List, List
*/
static <E> List<E> append(List<E> L, List<E> M) {
if(L.isEmpty()) {
return M;
}
else {
return new List<E>(L.getHead(), append(L.getTail(), M));
}
}
// Exercise 5
/**
* Given a tree of integers a, the method returns a boolean value indicating whether a is a binary search tree.
* @param a tree for input, Tree
* @return whether a is a binary search tree, boolean
*/
static boolean isSearchTree(Tree<Integer> a) {
if(a.isEmpty() || (a.getLeft().isEmpty() && a.getRight().isEmpty())) {
return true;
}
else if(a.getLeft().isEmpty() && (a.getRight().getValue() > a.getValue())) {
return true;
}
else if(a.getRight().isEmpty() && (a.getLeft().getValue() < a.getValue())) {
return true;
}
else if(a.getLeft().getValue() >= a.getValue() || a.getValue() >= a.getRight().getValue()) {
return false;
}
else {
return (isSearchTree(a.getLeft()) && isSearchTree(a.getRight()));
}
}
// Exercise 6
/**
* Given a binary search tree of integers a, write a method that prints the values stored in it in descending order
* @param a binary search tree, Tree
*/
static void printDescending(Tree<Integer> a) {
if (a.isEmpty()) {
System.out.print("");
}
else {
printDescending(a.getRight());
System.out.print(a.getValue() + " ");
printDescending(a.getLeft());
}
}
// Exercise 7
/**
* method to find the maximum value stored in the binary search tree a
* @param a binary search tree, Tree
* @return the maximum value in the tree a, int
*/
static int max(Tree<Integer> a) {
if(a.isEmpty()) {
return 0;
}
else if(a.getRight().isEmpty()) {
return a.getValue();
}
else {
return max(a.getRight());
}
}
// Exercise 8
/**
* the method delete the value x from a and return the resulting tree. The original tree a not be altered. Rather, it build a new tree that contains all the values of a except for one copy of x. The resulting tree again be a binary search tree.
* @param a the binary search tree needed to be searched, Tree
* @param x the value x needed to be deleted, int
* @return the new tree that contains all the values of a except for one cpr one copy of x.
*/
static Tree<Integer> delete(Tree<Integer> a, int x) {
if(a.isEmpty()) {
return a;
}
//have found the value note needed to be deleted
else if(a.getValue() == x) {
//the node without subtree
if(a.getRight().isEmpty() && a.getLeft().isEmpty()) {
return new Tree<Integer>();
}
//the node only have one subtree
else if(!a.getLeft().isEmpty() && a.getRight().isEmpty()) {
return a.getLeft();
}
else if(a.getLeft().isEmpty() && !a.getRight().isEmpty()) {
return a.getRight();
}
//the node have two subtrees
else {
return new Tree<Integer>(min(a.getRight()), a.getLeft(), delete(a.getRight(), min(a.getRight())));
}
}
//have not found the value note needed to be deleted
else {
return new Tree<Integer>(a.getValue(), delete(a.getLeft(), x), delete(a.getRight(), x));
}
}
/**
* helper method, used to find the minimum value in the search Tree
* @param a the search tree needed to be found, Tree
* @return the minimum value in the tree a.
*/
static int min(Tree<Integer> a) {
if(a.isEmpty()) {
return 0;
}
else if(a.getLeft().isEmpty()) {
return a.getValue();
}
else {
return min(a.getLeft());
}
}
// Exercise 9
/**
* Given a tree a (of an arbitrary element typeE), check to see if it is height-balanced, returning a boolean value.
* @param a Tree as input, Tree
* @param <E> generic parameter
* @return whether the Tree is height balanced(AVL Tree), boolean
*/
static <E> boolean isHeightBalanced(Tree<E> a) {
if(a.isEmpty()) {
return true;
}
// calculate the BF value of the node
else if(Math.abs(a.getRight().getHeight() - a.getLeft().getHeight()) > 1) {
return false;
}
else if(isHeightBalanced(a.getLeft()) && isHeightBalanced(a.getRight())) {
return true;
}
else {
return true;
}
}
// Exercise 10
/**
* the methods is to insert a node and maintain the height-balanced property of tree
* @param a the Tree as input, Tree
* @param x the value need to insert into a, int
* @return the result from a, Tree
*/
static Tree<Integer> insertHB(Tree<Integer> a, int x) {
assert isHeightBalanced(a);
if(a.isEmpty()) {
return new Tree<Integer>(x);
}
else if(a.getValue() == x) {
return a;
}
//insert into left subtree
else if(a.getValue() > x) {
return keepBalance(new Tree<Integer>(a.getValue(), insertHB(a.getLeft(), x), a.getRight()));
}
//insert into right subtree
else if(a.getValue() < x) {
return keepBalance(new Tree<Integer>(a.getValue(), a.getLeft(), insertHB(a.getRight(),x)));
}
else {
return new Tree<Integer>();
}
}
/**
* the methods is to delete a node and maintain the height-balanced property of tree
* @param a the Tree as input, Tree
* @param x the value need to delete a, int
* @return the result from a, Tree
*/
static Tree<Integer> deleteHB(Tree<Integer> a, int x) {
assert isHeightBalanced(a);
if(a.isEmpty()) {
return a;
}
//have found the value note needed to be deleted
else if(a.getValue() == x) {
//1. the node without subtree
if(a.getRight().isEmpty() && a.getLeft().isEmpty()) {
return new Tree<Integer>();
}
//2. the node only have one subtree
else if(!a.getLeft().isEmpty() && a.getRight().isEmpty()) {
return a.getLeft();
}
else if(a.getLeft().isEmpty() && !a.getRight().isEmpty()) {
return a.getRight();
}
//3. the node have two subtrees
else {
return keepBalance(new Tree<Integer>(min(a.getRight()), a.getLeft(), keepBalance(delete(a.getRight(), min(a.getRight())))));
}
}
//have not found the value note needed to be deleted
else {
return keepBalance(new Tree<Integer>(a.getValue(), keepBalance(delete(a.getLeft(), x)), keepBalance(delete(a.getRight(), x))));
}
}
/**
* unbalance height tree as input, then method will using correct rotation and return a balance-height tree
* @param a the tree as input, Tree
* @return the result after keep the balance of Tree a, Tree
*/
static Tree<Integer> keepBalance(Tree<Integer> a) {
//while the left subtree is higher than right subtree
if(a.getRight().getHeight() - a.getLeft().getHeight() == -2) {
//the left subtree is LL-case
if(a.getLeft().getRight().getHeight() - a.getLeft().getLeft().getHeight() <= 0) {
//single right rotation
return new Tree<Integer>(a.getLeft().getValue(), a.getLeft().getLeft(), new Tree<Integer>(a.getValue(), a.getLeft().getRight(), a.getRight()));
}
//the left subtree is LR-case
else {
//left rotation then right rotation
return new Tree<Integer>(a.getLeft().getRight().getValue(), new Tree<Integer>(a.getLeft().getValue(), a.getLeft().getLeft(), a.getLeft().getRight().getLeft()), new Tree<Integer>(a.getValue(), new Tree<Integer>(), a.getRight()));
}
}
//while the right subtree is higher than left subtree
else if(a.getLeft().getHeight() - a.getRight().getHeight() == 2) {
//the right subtree is RR-case
if(a.getRight().getRight().getHeight() - a.getRight().getLeft().getHeight() >= 0) {
//single left rotation
return new Tree<Integer>(a.getRight().getValue(), new Tree<Integer>(a.getValue(), a.getLeft(), a.getRight().getLeft()), a.getRight().getRight());
}
//the right subtree is RL-case
else {
//right rotation then left rotation
return new Tree<Integer>(a.getRight().getLeft().getValue(), new Tree<Integer>(a.getValue(), a.getLeft(), new Tree<Integer>()), new Tree<Integer>(a.getLeft().getValue(), a.getRight().getLeft().getRight(), a.getRight().getRight()));
}
}
else {
return a;
}
}
}
|
package com.anxpp.io.calculator.bio;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
public class sendphoto {
private Socket socket;
public sendphoto(Socket socket) {
this.socket = socket;
}
public void send(String str){
//·¢ËÍͼƬ
DataOutputStream dos;
try {
dos = new DataOutputStream(socket.getOutputStream());
FileInputStream fis = new FileInputStream(str);
int size = fis.available();
System.out.println("size = " + size);
byte[] data = new byte[size];
fis.read(data);
System.out.println("size = " + data.toString());
dos.writeInt(size);
dos.write(data);
dos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendjson(){
//·¢ËÍͼƬ
DataOutputStream dos;
try {
date da=new date();
dos = new DataOutputStream(socket.getOutputStream());
//FileInputStream fis = new FileInputStream(str);
//int size = fis.available();
//System.out.println("size = " + size);
System.out.println("ÀàÈÝ = " + da.jsonByte);
// dos.writeInt(da.len);
dos.writeUTF(da.st);
// dos.write(da.object.toString());
dos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.exception.commonlogging.master;
import com.cnk.travelogix.exception.commonlogging.customexception.UnknownException;
public class TravelogixError
{
/**
* Throw an exception
*/
public void sneeze(final String arg0, final String arg1, final int i) throws Exception
{
throw new UnknownException("TESTERROR", "Travelogix Simulation of an error");
}
}
|
package com.accp.pub.mapper;
import com.accp.pub.pojo.Surveystatistics;
public interface SurveystatisticsMapper {
int deleteByPrimaryKey(Integer statisid);
int insert(Surveystatistics record);
int insertSelective(Surveystatistics record);
Surveystatistics selectByPrimaryKey(Integer statisid);
int updateByPrimaryKeySelective(Surveystatistics record);
int updateByPrimaryKey(Surveystatistics record);
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.Song;
@Repository
public interface SongRepository extends JpaRepository<Song,Integer> {
@Query(value = "SELECT * FROM song WHERE title = ?1", nativeQuery=true)
Song findByTitle(String title);
@Query(value = "SELECT * FROM song where artist = ?1", nativeQuery=true)
List<Song> findSongsByArtist(String artist);
Page<Song> findByTitleContaining(String title, Pageable pageable);
Page<Song> findByArtistContaining(String artist, Pageable pageable);
}
|
package hk.edu.polyu.comp.comp2021.jungle.model;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit test for Coordinates
*/
public class CoordinatesTest {
/**
* Specific hash code for tile C5
*/
private static final int HASH_CODE_C5 = 66;
/**
* Test case for valid coordinates
*/
@Test
public void testIsValid() {
// Test string length larger than 0
assertFalse(Coordinates.isValid("G10"));
// Test english letter out of range
assertFalse(Coordinates.isValid("H9"));
assertFalse(Coordinates.isValid("@1"));
// Test number out of range
assertFalse(Coordinates.isValid("A0"));
assertFalse(Coordinates.isValid("GA"));
// Test true case boundary
assertTrue(Coordinates.isValid("A1"));
assertTrue(Coordinates.isValid("G9"));
}
/**
* Test the success Integer Coordinates.
*/
@Test
public void testSuccessIntegerCoordinates() {
Coordinates c = new Coordinates(0, 0);
Coordinates d = new Coordinates(6, 8);
}
/**
* Test if the coordinates failed on lower X boundary
*/
@Test(expected = IllegalArgumentException.class)
public void testFailedXLowCoordinates() {
Coordinates c = new Coordinates(-1, 0);
}
/**
* Test if the coordinates failed on upper X boundary
*/
@Test(expected = IllegalArgumentException.class)
public void testFailedXHighCoordinates() {
Coordinates c = new Coordinates(7, 0);
}
/**
* Test if the coordinates failed on lower Y boundary
*/
@Test(expected = IllegalArgumentException.class)
public void testFailedYLowCoordinates() {
Coordinates c = new Coordinates(0, -1);
}
/**
* Test if the coordinates failed on higher Y boundary
*/
@Test(expected = IllegalArgumentException.class)
public void testFailedYHighCoordinates() {
Coordinates c = new Coordinates(0, 9);
}
/**
* Test if the coordinates failed on String input
*/
@Test(expected = IllegalArgumentException.class)
public void testFailedStringCoordinates() {
Coordinates c = new Coordinates("H9");
}
/**
* Test case for getX and get Y
*/
@Test
public void string2xy() {
Coordinates c = new Coordinates("C5");
assertEquals(2, c.getX());
assertEquals(4, c.getY());
}
/**
* Test case for toString()
*/
@Test
public void testToString() {
Coordinates c = new Coordinates("A1");
Coordinates d = new Coordinates("G9");
Coordinates e = new Coordinates("C5");
assertEquals("A1", c.toString());
assertEquals("G9", d.toString());
assertEquals("C5", e.toString());
}
/**
* Test the hash code
*/
@Test
public void testHashCode() {
Coordinates c = new Coordinates("C5");
assertEquals(HASH_CODE_C5, c.hashCode());
}
/**
* Test whether equals() works
*/
@Test
public void testEquals() {
Coordinates c = new Coordinates("C5");
Coordinates d = new Coordinates(2, 4);
Coordinates x = new Coordinates("B2");
Coordinates y = new Coordinates("C4");
Coordinates z = new Coordinates("F5");
Object o = new Object();
assertTrue(c.equals(d));
assertTrue(d.equals(c));
assertFalse(c.equals(x));
assertFalse(c.equals(y));
assertFalse(c.equals(z));
assertFalse(c.equals(o));
}
}
|
package com.takshine.wxcrm.model;
import java.util.Date;
import com.takshine.wxcrm.base.common.Constants;
import com.takshine.wxcrm.base.model.BaseModel;
import com.takshine.wxcrm.base.util.PropertiesUtil;
import com.takshine.wxcrm.base.util.StringUtils;
/**
* 消息
* @author liulin
*
*/
public class MessagesModel extends BaseModel{
private String crmId = null;
private String msgType = null;
private Date lastTime = null;
//通用的信息功能
private String ownerCrmId = null;//拥有人的crmId
private String ownerOpenId = null;//拥有人的openId
private String userId = null;//发送人ID
private String targetUId = null;//目标人ID
private String username = null;//发送人姓名
private String targetUName = null;//目标人姓名
private String content =null;//消息内容
private String relaModule=null;//关联模块
private String relaId=null;//关联ID
private String relaName=null;//关联名称
private String subRelaId=null;//子级关联ID
private String readFlag=null;//读取标志(Y:已读,N:未读)
private String assignerid;//责任人ID
private String isatten = null; //是否是外部用户
private String msgtime = null; //首页消息用
private String shorttime = null; //首页消息用
private int totalcount = 0;
private String headimgurl;
private String cardname; //名片中的名字
private String cardimg; //名片中的头像
public String getCardname() {
return cardname;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public String getCardimg() {
return cardimg;
}
public void setCardimg(String cardimg) {
this.cardimg = cardimg;
}
public String getHeadimgurl() {
// if (StringUtils.isNotNullOrEmptyStr(headimgurl))
// {
// if (headimgurl.lastIndexOf("/") != -1)
// {
// headimgurl = headimgurl.substring(0,headimgurl.lastIndexOf("/") + 1) + Constants.OTHER_IMG_SIZE_96;
// }
// }
if (StringUtils.isNotNullOrEmptyStr(getCardimg())){
headimgurl = "http://"+PropertiesUtil.getAppContext("file.service") + PropertiesUtil.getAppContext("file.service.userpath").replace("/usr", "").replace("/zjftp","")+"/" + getCardimg();
}
return headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
public int getTotalcount() {
return totalcount;
}
public void setTotalcount(int totalcount) {
this.totalcount = totalcount;
}
public String getMsgtime() {
return msgtime;
}
public void setMsgtime(String msgtime) {
this.msgtime = msgtime;
}
public String getShorttime() {
return shorttime;
}
public void setShorttime(String shorttime) {
this.shorttime = shorttime;
}
public String getIsatten() {
return isatten;
}
public void setIsatten(String isatten) {
this.isatten = isatten;
}
public String getOwnerCrmId() {
return ownerCrmId;
}
public void setOwnerCrmId(String ownerCrmId) {
this.ownerCrmId = ownerCrmId;
}
public String getOwnerOpenId() {
return ownerOpenId;
}
public void setOwnerOpenId(String ownerOpenId) {
this.ownerOpenId = ownerOpenId;
}
public String getCrmId() {
return crmId;
}
public void setCrmId(String crmId) {
this.crmId = crmId;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
public Date getLastTime() {
return lastTime;
}
public void setLastTime(Date lastTime) {
this.lastTime = lastTime;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
if(StringUtils.isNotNullOrEmptyStr(getCardname())){
username = getCardname();
}
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getRelaModule() {
return relaModule;
}
public void setRelaModule(String relaModule) {
this.relaModule = relaModule;
}
public String getRelaId() {
return relaId;
}
public void setRelaId(String relaId) {
this.relaId = relaId;
}
public String getReadFlag() {
return readFlag;
}
public void setReadFlag(String readFlag) {
this.readFlag = readFlag;
}
public String getTargetUId() {
return targetUId;
}
public void setTargetUId(String targetUId) {
this.targetUId = targetUId;
}
public String getTargetUName() {
return targetUName;
}
public void setTargetUName(String targetUName) {
this.targetUName = targetUName;
}
public String getSubRelaId() {
return subRelaId;
}
public void setSubRelaId(String subRelaId) {
this.subRelaId = subRelaId;
}
public String getAssignerid() {
return assignerid;
}
public void setAssignerid(String assignerid) {
this.assignerid = assignerid;
}
public String getRelaName() {
return relaName;
}
public void setRelaName(String relaName) {
this.relaName = relaName;
}
}
|
/*
* Frame that allows the user to reset all data in the database.
*/
package stockorganizer;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
/**
*
*/
public class ResetFrame extends JFrame implements ActionListener {
private final JPanel resetPanel;
private final JPanel buttonPanel;
private final JLabel resetLabel;
private final JButton resetButton;
private final JButton goBackButton;
private final Dimension buttonSize;
private final Color GREEN_BACKGROUND;
private final Font warningFont;
private final Font buttonFont;
public ResetFrame() {
super("Reset Frame");
// Setting Color
GREEN_BACKGROUND = new Color(30,142,84);
// Setting Font
warningFont = new Font("Arial", Font.BOLD, 30);
buttonFont = new Font("Arial", Font.BOLD, 25);
buttonSize = new Dimension(200, 50);
this.setBounds(360, 200, 720, 450);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setBackground(GREEN_BACKGROUND);
resetPanel = new JPanel();
resetPanel.setLayout(new GridLayout(2,1));
resetPanel.setBackground(GREEN_BACKGROUND);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(GREEN_BACKGROUND);
resetLabel = new JLabel("<html>Are you sure you want to reset?</html>",SwingConstants.CENTER);
resetLabel.setFont(warningFont);
// resetLabel.setHorizontalTextPosition(SwingConstants.CENTER);
// resetLabel.setBackground(GREEN_BACKGROUND);
resetButton = new JButton("RESET");
resetButton.setFont(buttonFont);
resetButton.setPreferredSize(buttonSize);
resetButton.setHorizontalTextPosition(SwingConstants.CENTER);
goBackButton = new JButton("GO BACK");
goBackButton.setFont(buttonFont);
goBackButton.setPreferredSize(buttonSize);
goBackButton.setHorizontalTextPosition(SwingConstants.CENTER);
goBackButton.addActionListener(this);
resetButton.addActionListener(this);
buttonPanel.add(goBackButton);
buttonPanel.add(resetButton);
// resetPanel.add(Box.createRigidArea(new Dimension(0, 100)));
resetPanel.add(resetLabel);
// resetPanel.add(Box.createRigidArea(new Dimension(0, 60)));
resetPanel.add(buttonPanel);
this.add(resetPanel);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("RESET")) {
EditDataDb edi = new EditDataDb();
edi.resetInfo();
this.dispose();
RunningHoldingsTableFrame rhFrame = HomeFrame.getRunningHoldingFrame();
if (rhFrame != null) {
rhFrame.refreshDataTable();
}
PurchaseTableFrame pFrame = HomeFrame.getPurchaseFrame();
if (pFrame != null) {
pFrame.refreshDataTable();
}
SaleTableFrame sFrame = HomeFrame.getSaleFrame();
if (sFrame != null) {
sFrame.refreshDataTable();
}
DividendTableFrame dFrame = HomeFrame.getDividendFrame();
if (dFrame != null) {
dFrame.refreshDataTable();
}
}
if (command.equals("GO BACK")) {
this.dispose();
}
}
}
|
/*
* 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 thediary;
/**
*
* @author lkf5083
*/
public class DiaryCntl {
// Instance variables
private Diary diary;
private NavigationCntl navigationCntl;
//Constructor
public DiaryCntl(NavigationCntl navigationCntl, int accountID) {
//Set up diary.
diary = new Diary(accountID);
// Supports navagating back to the Main Menu
this.navigationCntl = navigationCntl;
}
public void addDailyEntry(int dailyEntryID, String input) {
diary.addDailyEntry(dailyEntryID, input);
}
public DailyEntry getDailyEntry(int dailyEntryID) {
return diary.getDailyEntry(dailyEntryID);
}
public void saveDailyEntry(int dailyEntryID, String input) {
diary.saveDailyEntry(dailyEntryID, input);
}
}
|
package fadhel.iac.tn.eventtracker.parsers;
import android.text.Html;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import fadhel.iac.tn.eventtracker.model.Event;
/**
* Created by Fadhel on 24/02/2016.
*/
public class HandleRest {
private String url_link= null;
private String catégorie = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleRest(String url_link,String catégorie) {
this.url_link= url_link;
this.catégorie = catégorie;
}
public int getCount() {
int tag;
int n=0;
String text=null;
XmlPullParser myParser = null;
try {
xmlFactoryObject = XmlPullParserFactory.newInstance();
myParser = xmlFactoryObject.newPullParser();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
try {
tag = myParser.getEventType();
while (tag != XmlPullParser.END_DOCUMENT) {
String name = myParser.getName();
switch (tag) {
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
switch (name) {
case "total_items":
n = Integer.valueOf(text);
break;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return n;
}
public int parseXMLAndStoreIt(XmlPullParser myParser,List<Event> res) {
int event;
int total=0;
String text=null;
Event item = new Event();
try {
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
String name=myParser.getName();
switch (event){
case XmlPullParser.START_TAG:
if(name.equals("event"))
item.setId(myParser.getAttributeValue(null,"id"));
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
switch(name) {
case "total_items" :
total = Integer.valueOf(text);
Log.d("TOTO",total+"");
break;
case "title" : item.setName(text);
break;
case "url":
if(text.contains("/images/medium/"))
item.setImageUrl(text);
else if(text.contains("/events/"))
item.setEventUrl(text);
break;
case "description":item.setDescription(Html.fromHtml(text).toString());
break;
case "start_time":
if(text.length()>0) {
item.setDateStart(text.substring(0,10));
item.setTimeStart(text.substring(11, text.length()));
}
break;
case "stop_time":
if(text.length()>7) {
item.setDateStop(text.substring(0, 10));
item.setTimeStop(text.substring(11, text.length()));
}
break;
case "venue_address": item.setAddress(text);
break;
case "city_name": item.setCity(text);
break;
case "country_name": item.setCountry(text);
break;
case "event":
if(catégorie.equals("sport")) item.setCatégorie("sport");
else item.setCatégorie("culture");
if(item.getDateStop().isEmpty() || item.getDateStop().equals(item.getDateStart()))
item.setDateReal(item.getDateStart());
res.add(item);
item = new Event();
break;
default:break;
}
break;
}
event = myParser.next();
}
parsingComplete = false;
}
catch (Exception e) {
e.printStackTrace();
}
return total;
}
public int ParseAndStore(List<Event> res,int pagenumber) {
int total=0;
try {
Log.d("URL",url_link+";page_number="+pagenumber);
URL url = new URL(url_link+";page_number="+pagenumber);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Log.d("Run","Running");
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
Log.d("Connection", "Before connection");
// Starts the query
conn.connect();
Log.d("Connection", "Connected");
InputStream stream = conn.getInputStream();
Log.d("Connection", "Getting Input Stream");
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
myparser.setInput(stream, null);
total = parseXMLAndStoreIt(myparser,res);
stream.close();
}
catch (Exception e) {
e.printStackTrace();
}
return total;
}
}
|
package com.ben.web.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface HandlerAdapter {
ModelAndView handle(HttpServletRequest request,HttpServletResponse response,Controller handler);
}
|
package com.lingnet.vocs.action.customer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.hibernate.criterion.Restrictions;
import com.lingnet.common.action.BaseAction;
import com.lingnet.qxgl.entity.QxUsers;
import com.lingnet.qxgl.service.AdminService;
import com.lingnet.util.JsonUtil;
import com.lingnet.util.LingUtil;
import com.lingnet.vocs.dao.partner.ContactsDao;
import com.lingnet.vocs.entity.Contacts;
import com.lingnet.vocs.entity.Contract;
import com.lingnet.vocs.entity.Partner;
import com.lingnet.vocs.entity.ProjectPreparation;
import com.lingnet.vocs.entity.Sewage;
import com.lingnet.vocs.service.baseinfo.CategoryService;
import com.lingnet.vocs.service.customer.CustomerService;
import com.lingnet.vocs.service.equipment.EquipmentUsagelogService;
import com.lingnet.vocs.service.finance.ContractService;
import com.lingnet.vocs.service.partner.PartnerService;
import com.lingnet.vocs.service.sewage.SewageService;
public class CustomerAction extends BaseAction {
private static final long serialVersionUID = 8521820161005025046L;
private String provinceId;// 省份id
private String cityId;// 市区id
private Partner partner;// 客户实体类
private Contacts contacts;// 联系人
private String formdata;// 主页面数据
private String griddata;// 子页面数据
private String name;
@Resource(name = "customerService")
private CustomerService customerService;// 客户
@Resource(name = "partnerService")
private PartnerService partnerService;// 合作商
@Resource(name = "contactsDao")
private ContactsDao contactsDao;
@Resource(name = "categoryService")
private CategoryService categoryService;
@Resource(name = "equipmentUsagelogService")
private EquipmentUsagelogService eulservice;
@Resource(name = "adminService")
private AdminService adminService;
@Resource(name = "contractService")
private ContractService contractService;
@Resource(name = "sewageService")
private SewageService sewageService;
private ProjectPreparation projectPreparation;//报备表
private Sewage sewage;//排污企业表
private String higherAgentName;
private String str;// 开始时间
private String end;// 结束时间
private String year;
private String month;
private String higherAgent;
private String flag;
private String partnerName;
private String areaId;// 区域id
private String status;
/**
* VOCS所有客户展现页面
*
* @Title: list
* @return String
* @author zmf
* @since 2016-5-31 V 1.0
*/
public String list() {
return LIST;
}
/**
* 当前用户下的数据显示
*
* @Title: myList
* @return String
* @author lizk
* @since 2017年7月3日 V 1.0
*/
public String myList() {
return "mylist";
}
/**
* 选择客户
*
* @Title: xzList
* @return String
* @author lizk
* @since 2017年7月13日 V 1.0
*/
public String xzList() {
return "xzlist";
}
/**
* 新增VOCS客户
*
* @Title: add
* @return String
* @author zmf
* @since 2016-5-31 V 1.0
*/
public String add() {
// 将用户名存入request作用域
QxUsers user = adminService.get(QxUsers.class,
Restrictions.eq("username", LingUtil.userName()));
String userId = user.getPartnerId();
Partner p = partnerService.get(Partner.class, userId);// 上级归属
higherAgentName = p.getName();
partner = new Partner();
partner.setHigherAgent(p.getId());
return ADD;
}
public String myAdd() {
// 将用户名存入request作用域
QxUsers user = adminService.get(QxUsers.class,
Restrictions.eq("username", LingUtil.userName()));
String userId = user.getPartnerId();
Partner p = partnerService.get(Partner.class, userId);// 上级归属
higherAgentName = p.getName();
higherAgent = p.getId();
return "myadd";
}
/**
* 编辑VOCS客户
*
* @Title: list
* @return String
* @author zmf
* @since 2016-5-31 V 1.0
*/
public String edit() {
/* partner = partnerService.get(Partner.class, id);
Partner p = partnerService.get(Partner.class,
Restrictions.eq("id", partner.getHigherAgent()));// 上级归属
higherAgentName = p.getName();
partner.setHigherAgent(partner.getHigherAgent());*/
sewage = getBeanById(Sewage.class, id);
//projectPreparation.setCusComName(sewage.getPwname());
return "edit";
}
public String myEdit() {
partner = partnerService.get(Partner.class, id);
QxUsers user = adminService.get(QxUsers.class,
Restrictions.eq("username", LingUtil.userName()));
String userId = user.getPartnerId();
Partner p = partnerService.get(Partner.class, userId);// 上级归属
higherAgentName = p.getName();
return "myadd";
}
public String look() {
partner = partnerService.get(Partner.class, id);
Partner p = partnerService.get(Partner.class, partner.getHigherAgent());// 上级归属
higherAgentName = p.getName();
flag = "false";
return ADD;
}
public String myLook() {
partner = partnerService.get(Partner.class, id);
Partner p = partnerService.get(Partner.class, partner.getHigherAgent());// 上级归属
higherAgentName = p.getName();
flag = "false";
return "myadd";
}
/**
* 查看VOCS客户
*
* @Title: view
* @return String
* @author zmf
* @since 2016-6-28 V 1.0
*/
public String view() {
return VIEW;
}
/**
* 获取VOCS客户信息
*
* @Title: getListData
* @return String
* @author zmf
* @since 2016-8-12 V 1.0
*/
public String getListData() {
String json = customerService.getListData(pager, name, key,
partnerName, areaId);
return ajax(Status.success, json);
}
/**
* 我的客户列表
*
* @Title: getMyListData
* @return String
* @author lizk
* @since 2017年7月13日 V 1.0
*/
public String getMyListData() {
String json = customerService.getMyListData(pager, name, key, areaId);
return ajax(Status.success, json);
}
/**
* 客户选择
*
* @Title: getListData
* @return String
* @author lizk
* @since 2017年7月13日 V 1.0
*/
public String getListCustomer() {
String json = customerService.getListCustomer(pager, name, key);
return ajax(Status.success, json);
}
/**
* 保存或编辑VOCS客户
*
* @Title: saveOrUpdate
* @return String
* @author zmf
* @since 2016-8-12 V 1.0
*/
public String saveOrUpdate() {
try {
return ajax(Status.success,
customerService.saveOrUpdate(formdata, griddata));
} catch (Exception e) {
return ajax(Status.error, e.getMessage());
}
}
/**
* 保存或编辑当前用户的客户
*
* @Title: saveUpdate
* @return String
* @author lizk
* @since 2017年7月4日 V 1.0
*/
public String saveUpdate() {
try {
return ajax(Status.success,
customerService.saveUpdate(formdata, griddata));
} catch (Exception e) {
return ajax(Status.error, e.getMessage());
}
}
/**
* VOCS客户--删除
*
* @Title: remove
* @return String
* @author zmf
* @since 2017-06-01 V 1.0
*/
public String remove() {
try {
List<Contract> c = contractService.getList(Contract.class,
Restrictions.eq("companyId", id));
if (c.size() > 0) {
throw new Exception("该客户存在合同不能删除");
}
Partner p = partnerService.get(Partner.class, ids[0]);
p.setIsDeleted("1");
partnerService.update(p);
operate("客户管理", "删除", LingUtil.userName());
return ajax(Status.success, "success");
} catch (Exception e) {
return ajax(Status.success, "删除失败");
}
}
/**
* VOCS客户--删除
*
* @Title: remove
* @return String
* @author zmf
* @since 2017-06-01 V 1.0
*/
public String myRemove() {
try {
List<Contract> c = contractService.getList(Contract.class,
Restrictions.eq("companyId", id));
if (c.size() > 0) {
throw new Exception("该客户存在合同不能删除");
}
Partner p = partnerService.get(Partner.class, ids[0]);
p.setIsDeleted("1");
partnerService.update(p);
return ajax(Status.success, "success");
} catch (Exception e) {
return ajax(Status.success, "删除失败");
}
}
/**
* Vocs 信息统计页面
*
* @Title: vocsindex
* @return String
* @author zhangyu
* @since 2017年6月20日 V 1.0
*/
public String vocsindex() {
return "vocsindex";
}
/**
* 设备使用频次
*
* @Title: getSbList
* @return String
* @author lizk
* @since 2017年6月30日 V 1.0
*/
public String getSbList() {
String json = "";
try {
json = customerService.getSbList(str, end, id);
return ajax(Status.success, json);
} catch (Exception e) {
e.printStackTrace();
return ajax(Status.success, e.getMessage());
}
}
/**
* 频次详细信息
*
* @Title: getSbPcxxList
* @return String
* @author lizk
* @since 2017年6月30日 V 1.0
*/
public String getSbPcxxList() {
String json = customerService.getSbPcxxList(pager, str, end, id, year,
month);
return ajax(Status.success, json);
}
/**
* Vocs 信息统计 左侧列表
*
* @Title: getMenu
* @return String
* @author zhangyu
* @since 2017年6月20日 V 1.0
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public String getMenu() {
List<Partner> p = partnerService.getList(Partner.class,
Restrictions.ne("id", "1"));
ArrayList arrlist = new ArrayList();
for (int i = 0; i < p.size(); i++) {
HashMap map = new HashMap();
map.put("id", p.get(i).getId());
map.put("text", p.get(i).getName());
map.put("pid", p.get(i).getHigherAgent());
if ("P".equals(p.get(i).getPartnerOrCustomer())) {
map.put("img", "../template/system/images/hezuos.png");
} else {
map.put("img", "../template/system/images/kehu.png");
}
arrlist.add(map);
}
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
}
/**
* VOCs处理量
*
* @Title: vocsoperation
* @return String
* @author zhangyu
* @since 2017年6月7日 V 1.0
*/
public String vocsoperation() {
return "vocsoperation";
}
public String frequency() {
return "frequency";
}
public String capacity() {
return "capacity";
}
/**
* VOCs达标情况
*
* @Title: vocsuptostandard
* @return String
* @author zhangyu
* @since 2017年6月7日 V 1.0
*/
public String vocsuptostandard() {
return "vocsuptostandard";
}
/**
* VOCs异常情况
*
* @Title: vocsabnormal
* @return String
* @author zhangyu
* @since 2017年6月7日 V 1.0
*/
public String vocsabnormal() {
return "vocsabnormal";
}
/**
* VOCs使用频次
*
* @Title: vocsfrequence
* @return String
* @author zhangyu
* @since 2017年6月7日 V 1.0
*/
public String vocsfrequence() {
return "vocsfrequence";
}
/**
* @Title: map
* @return String
* @author zhangyu
* @since 2017年6月7日 V 1.0
*/
public String map() {
return "map";
}
/**
* @Title: getChartCustomerData
* @return String
* @author zmf
* @since 2017年6月7日 V 1.0
*/
public String getChartCustomerData() {
String jsonString = "";
jsonString += "[{ \"id\":\"1\", \"city\":\"合作商1\", \"handling\":\"100000\" }"
+ " ,{ \"id\":\"2\", \"city\":\"合作商2\", \"handling\":\"90000\"}"
+ " ,{ \"id\":\"3\", \"city\":\"客户1\", \"handling\":\"80000\" }"
+ " ,{ \"id\":\"4\", \"city\":\"客户2\", \"handling\":\"70000\" }"
+ " ,{ \"id\":\"5\", \"city\":\"客户3\", \"handling\":\"60000\"}"
+ "]";
return ajax(Status.success, JsonUtil.Encode(jsonString));
}
public String getChartFrequencyData() {
String jsonString = "";
jsonString += "[{ \"id\":\"1\", \"equipment\":\"设备A\", \"handling\":\"100\" }"
+ " ,{ \"id\":\"2\", \"equipment\":\"设备B\", \"handling\":\"90\"}"
+ " ,{ \"id\":\"3\", \"equipment\":\"设备C\", \"handling\":\"80\" }"
+ " ,{ \"id\":\"4\", \"equipment\":\"设备D\", \"handling\":\"70\" }"
+ " ,{ \"id\":\"5\", \"equipment\":\"设备E\", \"handling\":\"60\"}"
+ " ,{ \"id\":\"6\", \"equipment\":\"设备F\", \"handling\":\"50\" }"
+ " ,{ \"id\":\"7\", \"equipment\":\"设备G\", \"handling\":\"40\" }"
+ " ,{ \"id\":\"8\", \"equipment\":\"设备H\", \"handling\":\"30\" }"
+ " ,{ \"id\":\"9\", \"equipment\":\"设备I\", \"handling\":\"20\"}"
+ " ,{ \"id\":\"10\", \"equipment\":\"设备J\", \"handling\":\"10\" }"
+ "]";
return ajax(Status.success, JsonUtil.Encode(jsonString));
}
public String abnormalrecord() {
return "abnormalrecord";
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public String getVocsAbnormalList() {
ArrayList arrlist = new ArrayList();
HashMap map = new HashMap();
map.put("id", "AB0001");
map.put("name", "15年第26次异常处理");
map.put("content", "VOCs箱体损坏,催化剂泄露,场地污染");
map.put("date", "2015-12-25");
arrlist.add(map);
HashMap mapResult = new HashMap();
mapResult.put("data", arrlist);
mapResult.put("total", 1);
String json = JsonUtil.Encode(mapResult);
return ajax(Status.success, json);
}
/**
* 客户,合作商 用户树
*
* @Title: getCustomerTree
* @return String
* @author lizk
* @since 2017年7月5日 V 1.0
*/
public String getCustomerTree() {
QxUsers user = (QxUsers) getBeanByCriteria(QxUsers.class,
Restrictions.eq("username", LingUtil.userName()));
String treeData = customerService.getCustomerTree(user.getPartnerId(),
key, areaId);
return ajax(Status.success, treeData);
}
/**
* 潜在客户展示页
* @Title: qzkh
* @return
* String
* @author lizk
* @since 2018年2月7日 V 1.0
*/
public String qzkh(){
return "qzkh";
}
/**
* 潜在客户信息展示
* @Title: getQzKhList
* @return
* String
* @author lizk
* @since 2018年2月7日 V 1.0
*/
public String getQzKhList(){
return ajax(Status.success,
customerService.getQzKhData(pager, searchData));
}
/**
* 意向客户展示页
* @Title: yxkh
* @return
* String
* @author lizk
* @since 2018年2月7日 V 1.0
*/
public String yxkh(){
return "yxkh";
}
/**
* 意向客户信息列表
* @Title: getYxkhList
* @return
* String
* @author lizk
* @since 2018年2月7日 V 1.0
*/
public String getYxkhList(){
return ajax(Status.success,
customerService.getYxkhList(pager, searchData,status));
}
/**
* 签单
* @Title: qd
* @return
* String
* @author lizk
* @since 2018年2月23日 V 1.0
*/
public String qd(){
try {
Sewage s = this.getBeanByCriteria(Sewage.class, Restrictions.eq("id", id));
s.setStatus("3");;//签单后改为成单客户
sewageService.update(s);
return ajax(Status.success, "success");
} catch (Exception e) {
return ajax(Status.success, "签单失败");
}
}
/**
* 驳回 成单客户改为潜在客户
* @Title: bh
* @return
* String
* @author lizk
* @since 2018年2月23日 V 1.0
*/
public String bh(){
try {
Sewage s = this.getBeanByCriteria(Sewage.class, Restrictions.eq("id", id));
s.setStatus("1");//
sewageService.update(s);
return ajax(Status.success, "success");
} catch (Exception e) {
return ajax(Status.success, "驳回失败");
}
}
/**
* 承担客户展示页
* @Title: cdkh
* @return
* String
* @author lizk
* @since 2018年2月7日 V 1.0
*/
public String cdkh(){
return "cdkh";
}
/**
* 承担客户信息列表
* @Title: getCdkhList
* @return
* String
* @author lizk
* @since 2018年2月7日 V 1.0
*/
public String getCdkhList(){
return "";
}
/**
*
* @Title: getProvinceData
* @return String
* @author zhangyu
* @since 2017年6月20日 V 1.0
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public String getProvinceData() {
HashMap map = new HashMap();
map.put("id", "shandong");
map.put("name", "山东省");
HashMap map2 = new HashMap();
map2.put("id", "zhejiang");
map2.put("name", "浙江省");
ArrayList arrlist = new ArrayList();
arrlist.add(map);
arrlist.add(map2);
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public String getCityData() {
if (getProvinceId().equals("shandong")) {
HashMap map = new HashMap();
map.put("id", "jinan");
map.put("name", "济南市");
HashMap map2 = new HashMap();
map2.put("id", "qingdao");
map2.put("name", "青岛市");
ArrayList arrlist = new ArrayList();
arrlist.add(map);
arrlist.add(map2);
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
} else if (getProvinceId().equals("zhejiang")) {
HashMap map = new HashMap();
map.put("id", "hangzhou");
map.put("name", "杭州市");
ArrayList arrlist = new ArrayList();
arrlist.add(map);
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
}
return NONE;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public String getDistrictData() {
if (cityId.equals("jinan")) {
HashMap map = new HashMap();
map.put("id", "lixia");
map.put("name", "历下区");
HashMap map2 = new HashMap();
map2.put("id", "tianqiao");
map2.put("name", "天桥区");
ArrayList arrlist = new ArrayList();
arrlist.add(map);
arrlist.add(map2);
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
} else if (cityId.equals("qingdao")) {
HashMap map = new HashMap();
map.put("id", "huangdao");
map.put("name", "黄岛区");
HashMap map2 = new HashMap();
map2.put("id", "shinan");
map2.put("name", "市南区");
ArrayList arrlist = new ArrayList();
arrlist.add(map);
arrlist.add(map2);
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
} else if (cityId.equals("hangzhou")) {
HashMap map = new HashMap();
map.put("id", "yuhang");
map.put("name", "余杭区");
HashMap map2 = new HashMap();
map2.put("id", "xiaoshan");
map2.put("name", "萧山区");
ArrayList arrlist = new ArrayList();
arrlist.add(map);
arrlist.add(map2);
String json = JsonUtil.Encode(arrlist);
return ajax(Status.success, json);
}
return NONE;
}
/**
* @return the provinceId
*/
public String getProvinceId() {
return provinceId;
}
/**
* @param provinceId
* the provinceId to set
*/
public void setProvinceId(String provinceId) {
this.provinceId = provinceId;
}
/**
* @return the cityId
*/
public String getCityId() {
return cityId;
}
/**
* @param cityId
* the cityId to set
*/
public void setCityId(String cityId) {
this.cityId = cityId;
}
public Partner getPartner() {
return partner;
}
public void setPartner(Partner partner) {
this.partner = partner;
}
public Contacts getContacts() {
return contacts;
}
public void setContacts(Contacts contacts) {
this.contacts = contacts;
}
public String getFormdata() {
return formdata;
}
public void setFormdata(String formdata) {
this.formdata = formdata;
}
public String getGriddata() {
return griddata;
}
public void setGriddata(String griddata) {
this.griddata = griddata;
}
public String getHigherAgentName() {
return higherAgentName;
}
public void setHigherAgentName(String higherAgentName) {
this.higherAgentName = higherAgentName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public void setStr(String str) {
this.str = str;
}
public void setEnd(String end) {
this.end = end;
}
public String getHigherAgent() {
return higherAgent;
}
public void setHigherAgent(String higherAgent) {
this.higherAgent = higherAgent;
}
public String getStr() {
return str;
}
public String getEnd() {
return end;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public CustomerService getCustomerService() {
return customerService;
}
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public PartnerService getPartnerService() {
return partnerService;
}
public void setPartnerService(PartnerService partnerService) {
this.partnerService = partnerService;
}
public ContactsDao getContactsDao() {
return contactsDao;
}
public void setContactsDao(ContactsDao contactsDao) {
this.contactsDao = contactsDao;
}
public CategoryService getCategoryService() {
return categoryService;
}
public void setCategoryService(CategoryService categoryService) {
this.categoryService = categoryService;
}
public EquipmentUsagelogService getEulservice() {
return eulservice;
}
public void setEulservice(EquipmentUsagelogService eulservice) {
this.eulservice = eulservice;
}
public AdminService getAdminService() {
return adminService;
}
public void setAdminService(AdminService adminService) {
this.adminService = adminService;
}
public ContractService getContractService() {
return contractService;
}
public void setContractService(ContractService contractService) {
this.contractService = contractService;
}
public String getPartnerName() {
return partnerName;
}
public void setPartnerName(String partnerName) {
this.partnerName = partnerName;
}
public String getAreaId() {
return areaId;
}
public void setAreaId(String areaId) {
this.areaId = areaId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public ProjectPreparation getProjectPreparation() {
return projectPreparation;
}
public void setProjectPreparation(ProjectPreparation projectPreparation) {
this.projectPreparation = projectPreparation;
}
public Sewage getSewage() {
return sewage;
}
public void setSewage(Sewage sewage) {
this.sewage = sewage;
}
}
|
/** originally used the nullwire code, tweaked out for carcast. */
package com.jadn.cc.trace;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
public class ExceptionHandler {
private static boolean busySendingTraces;
private static String[] stackTraceFileList = null;
public static void clearStackTraceCache() {
stackTraceFileList = null;
}
public static void setTraceData(Context context){
PackageManager pm = context.getPackageManager();
try {
PackageInfo pi;
// Version
pi = pm.getPackageInfo(context.getPackageName(), 0);
TraceData.APP_VERSION = pi.versionName;
// Package name
TraceData.APP_PACKAGE = pi.packageName;
// Files dir for storing the stack traces
TraceData.FILES_PATH = context.getFilesDir().getAbsolutePath();
// Device model
TraceData.PHONE_MODEL = android.os.Build.MODEL;
// Android version
TraceData.ANDROID_VERSION = android.os.Build.VERSION.RELEASE;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
public static boolean register(Context context) {
setTraceData(context);
boolean stackTracesFound = false;
// We'll return true if any stack traces were found
if (searchForStackTraces().length > 0) {
stackTracesFound = true;
}
// we register from our application and also from our service.
// lets not send stacktraces twice.
if (!busySendingTraces) {
busySendingTraces = true;
new Thread() {
@Override
public void run() {
// First of all transmit any stack traces that may be lying
// around
submitStackTraces();
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
if (currentHandler != null) {
Log.d(ExceptionHandler.class.getName(), "current handler class=" + currentHandler.getClass().getName());
}
// don't register again if already registered
if (!(currentHandler instanceof DefaultExceptionHandler)) {
// Register default exceptions handler
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler(currentHandler));
}
busySendingTraces = false;
}
}.start();
}
return stackTracesFound;
}
private static String[] searchForStackTraces() {
if (stackTraceFileList != null) {
return stackTraceFileList;
}
File dir = new File(TraceData.FILES_PATH + "/");
// Try to create the files folder if it doesn't exist
dir.mkdir();
// Filter for ".stacktrace" files
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".stacktrace");
}
};
return (stackTraceFileList = dir.list(filter));
}
public static void submitStackTraces() {
try {
String[] list = searchForStackTraces();
if (list != null && list.length > 0) {
for (int i = 0; i < list.length; i++) {
String filePath = TraceData.FILES_PATH + "/" + list[i];
// Extract the version from the filename:
// "packagename-version-...."
String version = list[i].split("-")[0];
// Read contents of stacktrace
StringBuilder contents = new StringBuilder();
BufferedReader input = new BufferedReader(new FileReader(filePath));
String traceTime = input.readLine();
String line = null;
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append('\n');
}
input.close();
String stacktrace;
stacktrace = contents.toString();
Log.d(ExceptionHandler.class.getName(), "Transmitting stack trace: " + stacktrace);
// Transmit stack trace with POST request
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(TraceData.URL);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("traceTime", traceTime));
nvps.add(new BasicNameValuePair("now", Long.toString(System.currentTimeMillis())));
nvps.add(new BasicNameValuePair("package_name", TraceData.APP_PACKAGE));
nvps.add(new BasicNameValuePair("package_version", version));
nvps.add(new BasicNameValuePair("phone_model", TraceData.PHONE_MODEL));
nvps.add(new BasicNameValuePair("android_version", TraceData.ANDROID_VERSION));
nvps.add(new BasicNameValuePair("stacktrace", stacktrace));
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// We don't care about the response, so we just hope it went
// well and on with it
httpClient.execute(httpPost);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
String[] list = searchForStackTraces();
for (int i = 0; i < list.length; i++) {
File file = new File(TraceData.FILES_PATH + "/" + list[i]);
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
package com.fight.job.core.biz.model;
import java.io.Serializable;
/**
* RegisterParam.
*/
public class RegisterParam implements Serializable {
private static final long serialVersionUID = -1L;
private String ip;
private int port;
private String groupId;
private String executorName;
private String executorDesc;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getExecutorName() {
return executorName;
}
public void setExecutorName(String executorName) {
this.executorName = executorName;
}
public String getExecutorDesc() {
return executorDesc;
}
public void setExecutorDesc(String executorDesc) {
this.executorDesc = executorDesc;
}
@Override
public String toString() {
return "RegisterParam{" +
"ip='" + ip + '\'' +
", port=" + port +
", groupId='" + groupId + '\'' +
", executorName='" + executorName + '\'' +
", executorDesc='" + executorDesc + '\'' +
'}';
}
}
|
package eu.lsem.bakalarka.webfrontend.extensions.typeconverters;
import net.sourceforge.stripes.integration.spring.SpringBean;
import eu.lsem.bakalarka.dao.categories.CategoryDao;
public class ThesesCategoryTypeConverter extends CategoryTypeConverter {
@Override
@SpringBean("thesesCategoriesDao")
protected void setCategoryDao(CategoryDao dao) {
super.categoryDao = dao;
}
}
|
package ca.antonious.habittracker.observable;
import junit.framework.Assert;
import java.util.ArrayList;
import java.util.List;
/**
* Created by George on 2016-09-14.
*/
public class TestObserver<T> implements IObserver<T> {
private List<T> itemsEmitted = new ArrayList<>();
@Override
public void onNext(T next) {
itemsEmitted.add(next);
}
public void assertItemEmitted(T item) {
Assert.assertTrue(itemsEmitted.contains(item));
}
public void assertTotalCompletions(int total) {
Assert.assertEquals(itemsEmitted.size(), total);
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.util.Collection;
import java.util.Comparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Utility class containing scheduling algorithms used in the fair scheduler.
*/
class SchedulingAlgorithms {
public static final Log LOG = LogFactory.getLog(
SchedulingAlgorithms.class.getName());
/**
* Compare Schedulables in order of priority and then submission time, as in
* the default FIFO scheduler in Hadoop.
*/
public static class FifoComparator implements Comparator<Schedulable> {
@Override
public int compare(Schedulable s1, Schedulable s2) {
int res = s1.getPriority().compareTo(s2.getPriority());
if (res == 0) {
res = (int) Math.signum(s1.getStartTime() - s2.getStartTime());
}
if (res == 0) {
// In the rare case where jobs were submitted at the exact same time,
// compare them by name (which will be the JobID) to get a deterministic
// ordering, so we don't alternately launch tasks from different jobs.
res = s1.getName().compareTo(s2.getName());
}
return res;
}
}
/**
* Compare Schedulables via weighted fair sharing. In addition, Schedulables
* below their min share get priority over those whose min share is met.
*
* Schedulables below their min share are compared by how far below it they
* are as a ratio. For example, if job A has 8 out of a min share of 10 tasks
* and job B has 50 out of a min share of 100, then job B is scheduled next,
* because B is at 50% of its min share and A is at 80% of its min share.
*
* Schedulables above their min share are compared by (runningTasks / weight).
* If all weights are equal, slots are given to the job with the fewest tasks;
* otherwise, jobs with more weight get proportionally more slots.
*/
public static class FairShareComparator implements Comparator<Schedulable> {
@Override
public int compare(Schedulable s1, Schedulable s2) {
double minShareRatio1, minShareRatio2;
double tasksToWeightRatio1, tasksToWeightRatio2;
int minShare1 = Math.min(s1.getMinShare(), s1.getDemand());
int minShare2 = Math.min(s2.getMinShare(), s2.getDemand());
boolean s1Needy = s1.getRunningTasks() < minShare1;
boolean s2Needy = s2.getRunningTasks() < minShare2;
minShareRatio1 = s1.getRunningTasks() / Math.max(minShare1, 1.0);
minShareRatio2 = s2.getRunningTasks() / Math.max(minShare2, 1.0);
tasksToWeightRatio1 = s1.getRunningTasks() / s1.getWeight();
tasksToWeightRatio2 = s2.getRunningTasks() / s2.getWeight();
int res = 0;
if (s1Needy && !s2Needy)
res = -1;
else if (s2Needy && !s1Needy)
res = 1;
else if (s1Needy && s2Needy)
res = (int) Math.signum(minShareRatio1 - minShareRatio2);
else // Neither schedulable is needy
res = (int) Math.signum(tasksToWeightRatio1 - tasksToWeightRatio2);
if (res == 0) {
// Jobs are tied in fairness ratio. Break the tie by submit time and job
// name to get a deterministic ordering, which is useful for unit tests.
res = (int) Math.signum(s1.getStartTime() - s2.getStartTime());
if (res == 0)
res = s1.getName().compareTo(s2.getName());
}
return res;
}
}
/**
* Number of iterations for the binary search in computeFairShares. This is
* equivalent to the number of bits of precision in the output. 25 iterations
* gives precision better than 0.1 slots in clusters with one million slots.
*/
private static final int COMPUTE_FAIR_SHARES_ITERATIONS = 25;
/**
* Given a set of Schedulables and a number of slots, compute their weighted
* fair shares. The min shares and demands of the Schedulables are assumed to
* be set beforehand. We compute the fairest possible allocation of shares
* to the Schedulables that respects their min shares and demands.
*
* To understand what this method does, we must first define what weighted
* fair sharing means in the presence of minimum shares and demands. If there
* were no minimum shares and every Schedulable had an infinite demand (i.e.
* could launch infinitely many tasks), then weighted fair sharing would be
* achieved if the ratio of slotsAssigned / weight was equal for each
* Schedulable and all slots were assigned. Minimum shares and demands add
* two further twists:
* - Some Schedulables may not have enough tasks to fill all their share.
* - Some Schedulables may have a min share higher than their assigned share.
*
* To deal with these possibilities, we define an assignment of slots as
* being fair if there exists a ratio R such that:
* - Schedulables S where S.demand < R * S.weight are assigned share S.demand
* - Schedulables S where S.minShare > R * S.weight are given share S.minShare
* - All other Schedulables S are assigned share R * S.weight
* - The sum of all the shares is totalSlots.
*
* We call R the weight-to-slots ratio because it converts a Schedulable's
* weight to the number of slots it is assigned.
*
* We compute a fair allocation by finding a suitable weight-to-slot ratio R.
* To do this, we use binary search. Given a ratio R, we compute the number
* of slots that would be used in total with this ratio (the sum of the shares
* computed using the conditions above). If this number of slots is less than
* totalSlots, then R is too small and more slots could be assigned. If the
* number of slots is more than totalSlots, then R is too large.
*
* We begin the binary search with a lower bound on R of 0 (which means that
* all Schedulables are only given their minShare) and an upper bound computed
* to be large enough that too many slots are given (by doubling R until we
* either use more than totalSlots slots or we fulfill all jobs' demands).
* The helper method slotsUsedWithWeightToSlotRatio computes the total number
* of slots used with a given value of R.
*
* The running time of this algorithm is linear in the number of Schedulables,
* because slotsUsedWithWeightToSlotRatio is linear-time and the number of
* iterations of binary search is a constant (dependent on desired precision).
*/
public static void computeFairShares(
Collection<? extends Schedulable> schedulables, double totalSlots) {
// Find an upper bound on R that we can use in our binary search. We start
// at R = 1 and double it until we have either used totalSlots slots or we
// have met all Schedulables' demands (if total demand < totalSlots).
double totalDemand = 0;
for (Schedulable sched: schedulables) {
totalDemand += sched.getDemand();
}
double cap = Math.min(totalDemand, totalSlots);
double rMax = 1.0;
while (slotsUsedWithWeightToSlotRatio(rMax, schedulables) < cap) {
rMax *= 2.0;
}
// Perform the binary search for up to COMPUTE_FAIR_SHARES_ITERATIONS steps
double left = 0;
double right = rMax;
for (int i = 0; i < COMPUTE_FAIR_SHARES_ITERATIONS; i++) {
double mid = (left + right) / 2.0;
if (slotsUsedWithWeightToSlotRatio(mid, schedulables) < cap) {
left = mid;
} else {
right = mid;
}
}
// Set the fair shares based on the value of R we've converged to
for (Schedulable sched: schedulables) {
sched.setFairShare(computeShare(sched, right));
}
}
/**
* Compute the number of slots that would be used given a weight-to-slot
* ratio w2sRatio, for use in the computeFairShares algorithm as described
* in #{@link SchedulingAlgorithms#computeFairShares(Collection, double)}.
*/
private static double slotsUsedWithWeightToSlotRatio(double w2sRatio,
Collection<? extends Schedulable> schedulables) {
double slotsTaken = 0;
for (Schedulable sched: schedulables) {
double share = computeShare(sched, w2sRatio);
slotsTaken += share;
}
return slotsTaken;
}
/**
* Compute the number of slots assigned to a Schedulable given a particular
* weight-to-slot ratio w2sRatio, for use in computeFairShares as described
* in #{@link SchedulingAlgorithms#computeFairShares(Collection, double)}.
*/
private static double computeShare(Schedulable sched, double w2sRatio) {
double share = sched.getWeight() * w2sRatio;
share = Math.max(share, sched.getMinShare());
share = Math.min(share, sched.getDemand());
return share;
}
}
|
package af;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class As {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
FirefoxOptions Prof = new FirefoxOptions();
Prof.addPreference("browser.download.dir", "D:\\Roambi folder");
Prof.addPreference("browser.download.folderList", 2);
Prof.addPreference("browser.helperApps.neverAsk.saveToDisk","application/zip");
//--------------------------------------------------------------------
System.setProperty("webdriver.gecko.driver", "D:\\hari\\Selenium webdriver\\gecodriver 19.1\\geckodriver.exe");
WebDriver driver = new FirefoxDriver(Prof);
//----------------------------------------------------------------------
driver.manage().window().maximize();
driver.get("http://docs.seleniumhq.org/download/");
//driver.get("http://selenium-release.storage.googleapis.com/index.html?path=3.11/");
Thread.sleep(3000);
driver.findElement(By.xpath("//*[@id='mainContent']/p[7]/a[1]")).click();
//driver.findElement(By.linkText("selenium-server-standalone-3.11.0.jar")).click();
}
}
|
package squares;
public class SqureIn {
public static int add(int x, int y) {
return 1;
}
public class add{
public add(int x, int y) {
}
}
}
|
package comparepdf;
import com.testautomationguru.utility.CompareMode;
import com.testautomationguru.utility.PDFUtil;
import java.io.IOException;
public class ComparePDF {
public static void main(String[] args) {
final PDFUtil pdfUtil = new PDFUtil();
String file1="C:/PDFtest/1.pdf";
String file2="C:/PDFtest/false2.pdf";
try {
pdfUtil.setCompareMode(CompareMode.VISUAL_MODE);
pdfUtil.highlightPdfDifference(true);
final boolean result = pdfUtil.compare(file1, file2);
System.out.println(result);
} catch (IOException e) {
System.out.println("Не нашли файл");
}
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import com.tencent.mm.kernel.g;
import com.tencent.mm.modelsimple.ac;
import com.tencent.mm.sdk.platformtools.al.a;
class SettingsUI$7 implements a {
final /* synthetic */ ac mRd;
final /* synthetic */ SettingsUI mUx;
SettingsUI$7(SettingsUI settingsUI, ac acVar) {
this.mUx = settingsUI;
this.mRd = acVar;
}
public final boolean vD() {
g.DF().c(this.mRd);
g.DF().b(281, SettingsUI.l(this.mUx));
SettingsUI.m(this.mUx);
if (SettingsUI.n(this.mUx) != null) {
SettingsUI.n(this.mUx).SO();
SettingsUI.o(this.mUx);
}
if (SettingsUI.p(this.mUx) != null) {
SettingsUI.p(this.mUx).dismiss();
}
SettingsUI.q(this.mUx);
return false;
}
}
|
import java.util.Vector;
/**
* @author Dan
*
*/
public class Concept {
String name;
Vector<String> terms;
/**
* Constructor
* @param name
*/
public Concept(String name) {
this.name = name;
terms = new Vector<String>();
}
/**
* addTerm
* @param term
*/
public void addTerm(String term) {
terms.add(term);
}
/**
* hasTerm
* @param term
* @return
*/
public boolean hasTerm(String term) {
if (terms.contains(term))
return true;
return false;
}
/**
* getTerms
* @return terms
*/
public Vector<String> getTerms() {return terms;}
/**
* getName
* @return name
*/
public String getName() {return name;}
}
|
package layouts;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import logs.Logs;
public class Start extends layout {
private Group root = new Group();
private static final String[] BUTTONS = { "New Game", "Load Game", "Main Options", "Instructions", "Exit" };
private static final String[] LEVELS = {"easy", "medium", "hard"};
public Start(double height, double width) {
super(height, width);
setBackground();
setButtons();
setMusicButton();
scene = new Scene(root, windowWidth, windowHeight);
}
private void setMusicButton() {
Button music = factory.getButton("music").getButton();
music.setAlignment(Pos.TOP_LEFT);
VBox v = new VBox();
v.getChildren().add(music);
v.setPadding(new Insets(30, 0, 0, 50));
root.getChildren().add(v);
}
private void setButtons() {
VBox vbox = new VBox(30);
for (String crnt : BUTTONS)
vbox.getChildren().add(factory.getButton(crnt).getButton());
vbox.setAlignment(Pos.CENTER_RIGHT);
root.getChildren().add(vbox);
vbox.setPadding(new Insets(windowHeight - 700, 50, 150, windowWidth - 300));
setLevels();
}
private void setLevels() {
HBox hbox = new HBox(10);
for (String crnt : LEVELS)
hbox.getChildren().add(factory.getButton(crnt).getButton());
root.getChildren().add(hbox);
hbox.setPadding(new Insets(windowHeight * 0.07, 50, 150, windowWidth * .5));
}
private void setBackground() {
Image background = imgFactory.getImage("mainMenu", windowWidth, windowHeight);
ImageView img = new ImageView(background);
root.getChildren().add(img);
Logs.log("layout Changed", "debug");
}
}
|
package cc.stan.example.springcloudconfigclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
@SpringBootApplication
@RefreshScope
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
System.out.println("start ...");
}
// @Bean
// CommandLineRunner runner() {
// return args -> {
// System.out.println("CommandLineRunner running...");
// System.out.println(String.format("title,%s, welcome,%s \n", title, welcome));
// };
// }
}
|
package com.tencent.mm.ak;
import com.tencent.mm.ab.s;
import com.tencent.mm.ab.u;
import com.tencent.mm.modelcdntran.b;
import com.tencent.mm.modelcdntran.d;
import com.tencent.mm.modelcdntran.g;
import com.tencent.mm.modelcdntran.i.a;
import com.tencent.mm.modelcdntran.keep_ProgressInfo;
import com.tencent.mm.modelcdntran.keep_SceneResult;
import com.tencent.mm.network.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.pointers.PInt;
import com.tencent.mm.protocal.c.bwi;
import com.tencent.mm.protocal.c.bwj;
import com.tencent.mm.protocal.c.ki;
import com.tencent.mm.protocal.c.kj;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.bl;
import com.tencent.mm.sdk.platformtools.x;
import java.io.ByteArrayOutputStream;
import java.util.Map;
class l$4 implements a {
final /* synthetic */ l dVN;
l$4(l lVar) {
this.dVN = lVar;
}
public final int a(String str, int i, keep_ProgressInfo keep_progressinfo, keep_SceneResult keep_sceneresult, boolean z) {
Throwable th;
x.d(l.f(this.dVN), "cdntra cdnCallback clientid:%s startRet:%d proginfo:[%s] res:[%s]", l.j(this.dVN), Integer.valueOf(i), keep_progressinfo, keep_sceneresult);
h hVar;
String str2;
if (i == -21005) {
x.w(l.f(this.dVN), "cdntra ERR_CNDCOM_MEDIA_IS_UPLOADING clientid:%s", l.j(this.dVN));
if (l.k(this.dVN) != null) {
l.k(this.dVN).OS();
}
l.g(this.dVN).a(3, i, "", this.dVN);
return 0;
} else if (i != 0) {
x.e(l.f(this.dVN), "cdntra cdnCallback clientid:%s startRet:%d", l.j(this.dVN), Integer.valueOf(i));
i.hU((int) l.b(this.dVN));
i.hT((int) l.b(this.dVN));
if (keep_sceneresult != null) {
hVar = h.mEJ;
Object[] objArr = new Object[16];
objArr[0] = Integer.valueOf(i);
objArr[1] = Integer.valueOf(1);
objArr[2] = Long.valueOf(l.l(this.dVN));
objArr[3] = Long.valueOf(bi.VF());
objArr[4] = Integer.valueOf(d.bL(ad.getContext()));
objArr[5] = Integer.valueOf(l.m(this.dVN));
objArr[6] = Integer.valueOf(keep_sceneresult.field_fileLength);
objArr[7] = keep_sceneresult.field_transInfo;
objArr[8] = "";
objArr[9] = "";
objArr[10] = "";
objArr[11] = "";
objArr[12] = "";
objArr[13] = "";
objArr[14] = "";
if (keep_sceneresult == null) {
str2 = "";
} else {
str2 = l.lO(keep_sceneresult.report_Part2);
}
objArr[15] = str2;
hVar.h(10421, objArr);
}
l.g(this.dVN).a(3, i, "", this.dVN);
if (l.k(this.dVN) != null) {
l.k(this.dVN).OS();
}
return 0;
} else {
e d = l.d(this.dVN);
if (d == null || d.dTK != l.c(this.dVN)) {
g.ND().lw(l.j(this.dVN));
x.e(l.f(this.dVN), "cdntra get imginfo failed maybe delete by user imgLocalId:%d client:%s", Long.valueOf(l.c(this.dVN)), l.j(this.dVN));
if (l.k(this.dVN) != null) {
l.k(this.dVN).OS();
}
return 0;
} else if (keep_progressinfo != null) {
l.a(this.dVN, d, keep_progressinfo.field_finishedLength, 0, 0, keep_sceneresult);
return 0;
} else {
if (keep_sceneresult != null) {
x.i(l.f(this.dVN), "dkupimg sceneResult:%s", keep_sceneresult);
bwj bwj;
Object[] objArr2;
if (keep_sceneresult.field_retCode != 0) {
x.e(l.f(this.dVN), "cdntra clientid:%s sceneResult.retCode:%d sceneResult[%s]", l.j(this.dVN), Integer.valueOf(keep_sceneresult.field_retCode), keep_sceneresult);
if (keep_sceneresult.field_retCode == -21111) {
x.w(l.f(this.dVN), "summersafecdn cdntra ERR_CDNCOM_SAFEPROTO_NOAESKEY clientid:%s, enableHitcheck:%b", l.j(this.dVN), Boolean.valueOf(l.n(this.dVN)));
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.Em().H(new 1(this, keep_sceneresult));
return 0;
}
bwj = null;
if (!bi.bC(keep_sceneresult.field_sKeyrespbuf)) {
bwj = new bwj();
try {
bwj.aG(keep_sceneresult.field_sKeyrespbuf);
x.d(l.f(this.dVN), "parse skeyrespbuf: ret:%d,msg:%s", Integer.valueOf(bwj.six.rfn), bwj.six.rgv.toString());
} catch (Throwable e) {
th = e;
bwj = null;
x.e(l.f(this.dVN), "UploadMsgImgResponse parse fail: %s", th);
x.e(l.f(this.dVN), "exception:%s", bi.i(th));
} catch (Throwable e2) {
th = e2;
bwj = null;
x.e(l.f(this.dVN), "UploadMsgImgResponse parse UninitializedMessageException: %s", th);
x.e(l.f(this.dVN), "exception:%s", bi.i(th));
}
}
i.hU((int) l.b(this.dVN));
i.hT((int) l.b(this.dVN));
h hVar2 = h.mEJ;
objArr2 = new Object[16];
objArr2[0] = Integer.valueOf(keep_sceneresult.field_retCode);
objArr2[1] = Integer.valueOf(1);
objArr2[2] = Long.valueOf(l.l(this.dVN));
objArr2[3] = Long.valueOf(bi.VF());
objArr2[4] = Integer.valueOf(d.bL(ad.getContext()));
objArr2[5] = Integer.valueOf(l.m(this.dVN));
objArr2[6] = Integer.valueOf(keep_sceneresult.field_fileLength);
objArr2[7] = keep_sceneresult.field_transInfo;
objArr2[8] = "";
objArr2[9] = "";
objArr2[10] = "";
objArr2[11] = "";
objArr2[12] = "";
objArr2[13] = "";
objArr2[14] = "";
objArr2[15] = keep_sceneresult == null ? "" : l.lO(keep_sceneresult.report_Part2);
hVar2.h(10421, objArr2);
hVar2 = h.mEJ;
objArr2 = new Object[16];
objArr2[0] = Integer.valueOf(keep_sceneresult.field_retCode);
objArr2[1] = Integer.valueOf(1);
objArr2[2] = Long.valueOf(l.l(this.dVN));
objArr2[3] = Long.valueOf(bi.VF());
objArr2[4] = Integer.valueOf(d.bL(ad.getContext()));
objArr2[5] = Integer.valueOf(l.m(this.dVN));
objArr2[6] = Integer.valueOf(keep_sceneresult.field_fileLength);
objArr2[7] = keep_sceneresult.field_transInfo;
objArr2[8] = "";
objArr2[9] = "";
objArr2[10] = "";
objArr2[11] = "";
objArr2[12] = "";
objArr2[13] = "";
objArr2[14] = "";
objArr2[15] = keep_sceneresult == null ? "" : l.lO(keep_sceneresult.report_Part2);
hVar2.h(13937, objArr2);
if (bwj == null || bwj.six.rfn == 0) {
l.g(this.dVN).a(3, keep_sceneresult.field_retCode, "", this.dVN);
} else {
l.g(this.dVN).a(4, bwj.six.rfn, bwj.six.rgv.toString(), this.dVN);
}
if (l.k(this.dVN) != null) {
l.k(this.dVN).OS();
}
} else {
String str3;
x.i(l.f(this.dVN), "summersafecdn uploadMsgImg by cdn, UploadHitCacheType: %d, needSendMsg:%b", Integer.valueOf(keep_sceneresult.field_UploadHitCacheType), Boolean.valueOf(keep_sceneresult.field_needSendMsgField));
hVar = h.mEJ;
objArr2 = new Object[3];
objArr2[0] = Integer.valueOf(d.source == 0 ? 3 : d.source);
objArr2[1] = l.u(this.dVN);
objArr2[2] = Integer.valueOf(keep_sceneresult.field_UploadHitCacheType);
hVar.h(13230, objArr2);
String v = l.v(this.dVN);
str2 = "";
a lL = f.lL(v);
if (lL == null || bi.oW(lL.appId)) {
str3 = str2;
} else {
str3 = f.c(lL.appId, lL.mediaTagName, lL.messageExt, lL.messageAction);
}
if (bi.oW(v)) {
str2 = (("<msg><img aeskey=\"" + keep_sceneresult.field_aesKey + "\" cdnmidimgurl=\"" + keep_sceneresult.field_fileId + "\" cdnbigimgurl=\"" + keep_sceneresult.field_fileId + "\" ") + "cdnthumburl=\"" + keep_sceneresult.field_fileId + "\" cdnthumbaeskey=\"" + keep_sceneresult.field_aesKey + "\" cdnthumblength=\"" + keep_sceneresult.field_thumbimgLength + "\" ") + "length=\"" + (keep_sceneresult.field_midimgLength == 0 ? keep_sceneresult.field_fileLength : keep_sceneresult.field_midimgLength) + "\" hdlength=\"" + keep_sceneresult.field_fileLength + "\"/>" + str3 + "</msg>";
x.i(l.f(this.dVN), "cdn callback new build cdnInfo:%s", str2);
} else {
Map z2 = bl.z(v, "msg");
if (z2 != null) {
if (d.dTO == 0) {
str2 = (("<msg><img aeskey=\"" + ((String) z2.get(".msg.img.$aeskey")) + "\" cdnmidimgurl=\"" + keep_sceneresult.field_fileId + "\" cdnbigimgurl=\"" + ((String) z2.get(".msg.img.$cdnbigimgurl")) + "\" ") + "cdnthumburl=\"" + ((String) z2.get(".msg.img.$cdnthumburl")) + "\" cdnthumbaeskey=\"" + ((String) z2.get(".msg.img.$cdnthumbaeskey")) + "\" cdnthumblength=\"" + ((String) z2.get(".msg.img.cdnthumblength")) + "\" ") + "length=\"" + (keep_sceneresult.field_midimgLength == 0 ? keep_sceneresult.field_fileLength : keep_sceneresult.field_midimgLength) + "\" hdlength=\"" + ((String) z2.get(".msg.img.$hdlength")) + "\"/>" + str3 + "</msg>";
} else {
str2 = (("<msg><img aeskey=\"" + ((String) z2.get(".msg.img.$aeskey")) + "\" cdnmidimgurl=\"" + ((String) z2.get(".msg.img.$cdnmidimgurl")) + "\" cdnbigimgurl=\"" + keep_sceneresult.field_fileId + "\" ") + "cdnthumburl=\"" + ((String) z2.get(".msg.img.$cdnthumburl")) + "\" cdnthumbaeskey=\"" + ((String) z2.get(".msg.img.$cdnthumbaeskey")) + "\" cdnthumblength=\"" + ((String) z2.get(".msg.img.cdnthumblength")) + "\" ") + "length=\"" + ((String) z2.get(".msg.img.$length")) + "\" hdlength=\"" + keep_sceneresult.field_fileLength + "\"/>" + str3 + "</msg>";
}
x.i(l.f(this.dVN), "cdn callback rebuild cdnInfo:%s", str2);
} else {
str2 = v;
}
}
if (keep_sceneresult.isUploadBySafeCDNWithMD5()) {
if (bi.oW(l.w(this.dVN))) {
x.w(l.f(this.dVN), "summersafecdn sceneResult isUploadBySafeCDNWithMD5 but prepareResponse AESKey is null");
} else {
str2 = (("<msg><img aeskey=\"" + l.w(this.dVN) + "\" cdnmidimgurl=\"" + keep_sceneresult.field_fileId + "\" cdnbigimgurl=\"" + keep_sceneresult.field_fileId + "\" ") + "cdnthumburl=\"" + keep_sceneresult.field_fileId + "\" cdnthumbaeskey=\"" + l.w(this.dVN) + "\" ") + "length=\"" + keep_sceneresult.field_midimgLength + "\" hdlength=\"" + keep_sceneresult.field_fileLength + "\"/>" + str3 + "</msg>";
}
}
d.lK(str2);
if (l.b(this.dVN) != l.c(this.dVN)) {
l.e(this.dVN).lK(str2);
}
if (keep_sceneresult.field_needSendMsgField) {
com.tencent.mm.kernel.g.Eh().dpP.a(new m(l.x(this.dVN), (bwi) l.s(this.dVN).dID.dIL, d, keep_sceneresult, new 2(this, keep_sceneresult, d)), 0);
} else {
h.mEJ.h(10421, Integer.valueOf(0), Integer.valueOf(1), Long.valueOf(l.l(this.dVN)), Long.valueOf(bi.VF()), Integer.valueOf(d.bL(ad.getContext())), Integer.valueOf(l.m(this.dVN)), Integer.valueOf(keep_sceneresult.field_fileLength), keep_sceneresult.field_transInfo, "", "", "", "", "", "", "", l.lO(keep_sceneresult.report_Part2));
bwj = new bwj();
try {
bwj.aG(keep_sceneresult.field_sKeyrespbuf);
long j = bwj.rcq != 0 ? bwj.rcq : (long) bwj.rci;
x.d(l.f(this.dVN), "parse skeyrespbuf: ret:%d,msg:%s", Integer.valueOf(bwj.six.rfn), bwj.six.rgv.toString());
l.a(this.dVN, d, d.dHI, j, bwj.lOH, keep_sceneresult);
l.g(this.dVN).a(0, 0, "", this.dVN);
if (l.k(this.dVN) != null) {
l.k(this.dVN).OS();
}
return 0;
} catch (Throwable e22) {
x.e(l.f(this.dVN), "UploadMsgImgResponse parse fail: %s", e22);
x.e(l.f(this.dVN), "exception:%s", bi.i(e22));
l.g(this.dVN).a(3, keep_sceneresult.field_retCode, "", this.dVN);
if (l.k(this.dVN) != null) {
l.k(this.dVN).OS();
}
}
}
}
}
return 0;
}
}
}
public final void a(String str, ByteArrayOutputStream byteArrayOutputStream) {
bwi bwi = (bwi) l.s(this.dVN).dID.dIL;
ki kiVar = new ki();
kiVar.rmn = bwi.ssC.siM;
kiVar.jTv = bwi.rcj.siM;
kiVar.jTu = bwi.rck.siM;
kiVar.rmo = bwi.ssJ;
kiVar.rmp = bwi.ssK;
kiVar.otY = l.y(this.dVN);
kiVar.rmr = l.z(this.dVN);
kiVar.rms = l.A(this.dVN);
kiVar.rmt = l.B(this.dVN);
kiVar.rco = bwi.rco;
kiVar.rmy = l.C(this.dVN);
kiVar.jQb = bwi.jQb;
kiVar.raM = bwi.raM;
kiVar.raO = bwi.raO;
kiVar.raN = bwi.raN;
e d = l.d(this.dVN);
String o = o.Pf().o(d.dTL, "", "");
g.NE();
kiVar.rmA = b.lr(o);
kiVar.rmB = d.dTP;
if (kiVar.rmB <= 0) {
kiVar.rmB = l.x(this.dVN) == 4 ? 2 : 1;
}
switch (l.x(this.dVN)) {
case 1:
case 2:
kiVar.rdq = 1;
break;
case 4:
kiVar.rdq = 3;
break;
case 6:
kiVar.rdq = 5;
break;
default:
kiVar.rdq = 2;
break;
}
if (kiVar.rmB == 3) {
kiVar.rdq = 4;
}
x.i(l.f(this.dVN), "getCdnAuthInfo: mediaid:%s thumbwidth:%d, thumbheight:%d,MsgSource:%s,touser:%s aeskey[%s], imgLocalId[%d], msgLocalId[%d], getBigImgPath()[%s], fullpath[%s], prereq.CRC32[%d] prereq.MsgForwardType[%d], prereq.Source[%d]", str, Integer.valueOf(kiVar.rmo), Integer.valueOf(kiVar.rmp), kiVar.rco, kiVar.jTu, kiVar.rmy, Long.valueOf(l.c(this.dVN)), Long.valueOf(l.D(this.dVN)), d.dTL, o, Integer.valueOf(kiVar.rmA), Integer.valueOf(kiVar.rmB), Integer.valueOf(kiVar.rdq));
com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a();
aVar.dIG = kiVar;
aVar.dIH = new bwj();
aVar.uri = "/cgi-bin/micromsg-bin/uploadmsgimg";
aVar.dIF = 625;
aVar.dII = 9;
aVar.dIJ = 1000000009;
com.tencent.mm.ab.b KT = aVar.KT();
c Lr = l.E(this.dVN).Lr();
String f = l.f(this.dVN);
String str2 = "getCdnAuthInfo login:%s";
Object[] objArr = new Object[1];
objArr[0] = Lr == null ? "acc == null" : Boolean.valueOf(Lr.Ln());
x.i(f, str2, objArr);
if (Lr == null || !Lr.Ln()) {
x.e(l.f(this.dVN), "getCdnAuthInfo accinfo return null. clientimgid:%s", kiVar.rmn);
return;
}
if (s.a(Lr.DE(), Lr.Lm(), Lr.Lo(), KT.KV(), byteArrayOutputStream, Lr.Lp())) {
x.d(l.f(this.dVN), "getCdnAuthInfo successed.clientimgid:%s", kiVar.rmn);
} else {
x.e(l.f(this.dVN), "getCdnAuthInfo failed. clientimgid:%s", kiVar.rmn);
}
}
public final byte[] i(String str, byte[] bArr) {
PInt pInt = new PInt();
kj kjVar = new kj();
try {
byte[] a = u.a(bArr, com.tencent.mm.kernel.g.Eh().dpP.dJs.Lr().DE(), pInt, kjVar);
x.i(l.f(this.dVN), "decodePrepareResponse aeskey[%s], fileid[%s], clientimgid[%s]", kjVar.rmy, kjVar.rmC, kjVar.rmn);
l.b(this.dVN, kjVar.rmy);
x.i(l.f(this.dVN), "decodePrepareResponse, clientmediaid:%s, ret:%d", str, Integer.valueOf(pInt.value));
return a;
} catch (Exception e) {
x.e(l.f(this.dVN), "decodePrepareResponse Exception:%s", e);
l.b(this.dVN, null);
return null;
}
}
}
|
package Controller;
import Model.ClientClass;
import View.Classes.*;
import sun.security.pkcs11.wrapper.Constants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Objects;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class ChangePage {
private JFrame actualPage = null;
// private String nextPage = null;
public ChangePage(){};
public ChangePage(JFrame actualPage, String nextPage){
this.actualPage = actualPage;
// this.nextPage = nextPage;
}
void newPanel(){
actualPage.dispose();
actualPage.setVisible(false);
//nextPage.main(null);
}
public void goToMainPersonPanel(JFrame actualWindow){
actualPage = actualWindow;
actualPage.dispose();
actualPage.setVisible(false);
ReturnRole role = new ReturnRole();
if(Objects.equals(role.returnRole(), "A"))
AdminPanel.main(null);
else if (Objects.equals(role.returnRole(),"M" ))
ManagerPanel.main(null);
else if(Objects.equals(role.returnRole(), "W"))
WorkerPanel.main(null);
else if((Objects.equals(role.returnRole(), "U")))
ClientPanel.main(null);
else
LoginViewClass.main(null);
}
}
|
package boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_14501_퇴사 {
private static int N;
private static int max = Integer.MIN_VALUE;
private static int[] T;
private static int[] P;
private static boolean[] visited;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
T = new int[N+1];
P = new int[N+1];
visited = new boolean[N];
for (int i = 1; i <= N; i++) {
st = new StringTokenizer(br.readLine());
T[i] = Integer.parseInt(st.nextToken());
P[i] = Integer.parseInt(st.nextToken());
}
//System.out.println(Arrays.toString(T));
//System.out.println(Arrays.toString(P));
bfs(new Pair(1,0));
System.out.println(max);
}
public static void bfs(Pair p) {
Queue<Pair> queue = new LinkedList<>();
queue.offer(p);
while(!queue.isEmpty()) {
Pair tmp = queue.poll();
//System.out.println(tmp.price);
max = Math.max(max, tmp.price);
for (int i = tmp.r; i < P.length; i++) {
int currentR = i + (T[i]-1);
int currentPrice = tmp.price + P[i];
//System.out.println("R"+currentR);
//System.out.println("P"+currentPrice);
if(currentR > N) continue;
queue.offer(new Pair(currentR+1, currentPrice));
}
}
}
public static class Pair{
int r;
int price;
public Pair(int r, int price) {
this.r = r;
this.price = price;
}
}
}
|
package com.android.netperf_new.tasks;
import android.util.Log;
import com.android.netperf_new.model.PingerItem;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Created by Peace on 7/16/2017.
*/
public class NameResolver implements Runnable {
private String hostname;
final ArrayList<PingerItem> items;
public NameResolver(String hostname, ArrayList<PingerItem> items) {
this.hostname = hostname;
this.items = items;
}
public void run() {
Log.v("multiping", "NameResolver " + hostname);
// InetAddress ia;
try {
InetAddress inetAddress = InetAddress.getByName(hostname);
for (PingerItem pingerItem: items) {
if(pingerItem.hostname.equals(hostname)){
Log.v("multiping", "NameResolver " + hostname + " resolved:" + inetAddress);
pingerItem.ia = inetAddress;
break;
}
}
// for(int i=0; i<items.size(); i++)
// {
// PingerItem pi = items.get(i);
// if(pi.hostname.equals(hostname)) {
// Log.v("multiping","NameResolver "+hostname + " resolved:" + ia);
// pi.ia = ia;
// items.set(i,pi);
// }
// }
} catch (UnknownHostException e) {
//FIXME: We should not hide exceptions, either print or handle ;-)
} catch (Exception e) {
//FIXME: We should not hide exceptions, either print or handle ;-)
}
}
}
|
package com.tencent.mm.ui.tools;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
class MMGestureGallery$d extends SimpleOnGestureListener {
final /* synthetic */ MMGestureGallery uAo;
private MMGestureGallery$d(MMGestureGallery mMGestureGallery) {
this.uAo = mMGestureGallery;
}
/* synthetic */ MMGestureGallery$d(MMGestureGallery mMGestureGallery, byte b) {
this(mMGestureGallery);
}
public final boolean onDoubleTap(MotionEvent motionEvent) {
return true;
}
}
|
/*
* 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 cl.duoc.ptf8502.app.business;
import cl.duoc.ptf8502.ejb.entity.GuiaDespacho;
import cl.duoc.ptf8502.ejb.entity.GuiaDespachoDetalle;
import cl.duoc.ptf8502.ejb.entity.GuiaDespachoDetalleRfid;
import cl.duoc.ptf8502.ejb.entity.GuiaDespachoDetalleRfidPK;
import cl.duoc.ptf8502.ejb.entity.Operario;
import cl.duoc.ptf8502.ejb.entity.PreparacionPicking;
import cl.duoc.ptf8502.ejb.entity.Producto;
import cl.duoc.ptf8502.ejb.entity.Usuario;
import cl.duoc.ptf8502.ejb.exception.ValidationException;
import cl.duoc.ptf8502.ejb.util.DateUtiles;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
import test.Hash;
/**
*
* @author Mauri
*/
public class Controlador {
private static Controlador instance;
private Controlador() {
}
public static Controlador getInstance() {
if (instance == null) {
instance = new Controlador();
}
return instance;
}
public Usuario doLogin(String usuario, String clave) {
Conexion conexion = new Conexion();
PreparedStatement prepareStatement;
ResultSet resultSet;
Usuario u;
try {
prepareStatement = conexion.getConnection().prepareStatement("select * from usuario where usuario = ? and clave = ?");
prepareStatement.setString(1, usuario);
prepareStatement.setString(2, Hash.SHA1(clave));
resultSet = prepareStatement.executeQuery();
if (resultSet.next()) {
u = new Usuario(resultSet.getString("USUARIO"), resultSet.getString("CLAVE"));
u.setOperario(new Operario(resultSet.getInt("OPERARIO")));
return u;
} else {
return null;
}
} catch (SQLException e) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, e);
return null;
} finally {
conexion.closeConnection();
conexion = null;
prepareStatement = null;
resultSet = null;
u = null;
}
}
public List<Producto> buscarProductos(Integer sku, String nombre) {
if (sku == null && nombre == null) {
return new ArrayList<>();
} else {
String sql = "select * from PRODUCTO ";
List<String> where = new ArrayList<>();
Conexion conexion = new Conexion();
ResultSet resultSet;
List<Producto> listado = new ArrayList<>();
if (sku != null) {
where.add("cast(SKU as varchar(50)) like '" + sku + "%'");
}
if (nombre != null) {
where.add("upper(NOMBRE) like upper('%" + nombre + "%')");
}
sql += "where " + StringUtils.join(where, " and ");
try {
resultSet = conexion.getConnection().createStatement().executeQuery(sql);
while (resultSet.next()) {
Producto producto = new Producto(resultSet.getInt("ID"));
producto.setNombre(resultSet.getString("NOMBRE"));
producto.setSku(resultSet.getInt("SKU"));
listado.add(producto);
}
return listado;
} catch (SQLException ex) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
return new ArrayList<>();
} finally {
sql = null;
where.clear();
where = null;
conexion.closeConnection();
conexion = null;
resultSet = null;
listado = null;
}
}
}
public void insertGuiaDespacho(GuiaDespacho guiaDespacho) throws ValidationException {
Conexion conexion = new Conexion();
Statement statement;
ResultSet resultSet;
try {
conexion.getConnection().setAutoCommit(false);
resultSet = conexion.getConnection().createStatement().executeQuery("select id from GUIA_DESPACHO where NUMERO = " + guiaDespacho.getNumero());
if (resultSet.next()) {
throw new ValidationException("La guía de despacho ya existe");
}
resultSet = conexion.getConnection().createStatement().executeQuery("select gen_id(gen_guia_despacho_id,1) as id from rdb$database");
resultSet.next();
guiaDespacho.setId(resultSet.getInt("ID"));
statement = conexion.getConnection().createStatement();
statement.executeUpdate(""
+ "insert into GUIA_DESPACHO (ID,FECHA_INGRESO,NUMERO) "
+ "values (" + guiaDespacho.getId() + ", 'NOW', " + guiaDespacho.getNumero() + ")"
+ "");
statement = conexion.getConnection().createStatement();
for (GuiaDespachoDetalle detalle : guiaDespacho.getGuiaDespachoDetalleList()) {
resultSet = conexion.getConnection().createStatement().executeQuery("select gen_id(gen_guia_despacho_detalle_id,1) as id from rdb$database");
resultSet.next();
detalle.setId(resultSet.getInt("ID"));
statement.addBatch(""
+ "insert into GUIA_DESPACHO_DETALLE (ID,GUIA_DESPACHO,PRODUCTO,CANTIDAD) "
+ "values (" + detalle.getId() + ", " + detalle.getGuiaDespacho().getId() + ", " + detalle.getProducto().getId() + ", " + detalle.getCantidad() + ")"
+ "");
for (GuiaDespachoDetalleRfid detalleRfid : detalle.getGuiaDespachoDetalleRfidList()) {
detalleRfid.getGuiaDespachoDetalleRfidPK().setGuiaDespachoDetalle(detalle.getId());
statement.addBatch(""
+ "insert into GUIA_DESPACHO_DETALLE_RFID (GUIA_DESPACHO_DETALLE,RFID) "
+ "values (" + detalleRfid.getGuiaDespachoDetalleRfidPK().getGuiaDespachoDetalle() + ", '" + detalleRfid.getGuiaDespachoDetalleRfidPK().getRfid() + "')"
+ "");
}
}
statement.executeBatch();
conexion.getConnection().commit();
} catch (SQLException e) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, e);
try {
conexion.getConnection().rollback();
} catch (SQLException ex) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
}
throw new ValidationException("No se pudo ingresar la guía de despacho");
} finally {
conexion.closeConnection();
conexion = null;
statement = null;
resultSet = null;
}
}
public GuiaDespacho buscarGuiaDespacho(Integer numero) throws ValidationException {
Conexion conexion = new Conexion();
ResultSet resultSet;
GuiaDespacho guiaDespacho = null;
ArrayList<GuiaDespachoDetalle> listaGuiaDespachoDetalle = new ArrayList<>();
try {
resultSet = conexion.getConnection().createStatement().executeQuery("select * from GUIA_DESPACHO where NUMERO = " + numero);
if (!resultSet.next()) {
return null;
} else {
guiaDespacho = new GuiaDespacho(resultSet.getInt("ID"));
guiaDespacho.setFechaIngreso(resultSet.getDate("FECHA_INGRESO"));
guiaDespacho.setNumero(resultSet.getInt("NUMERO"));
resultSet = conexion.getConnection().createStatement().executeQuery(""
+ "select * from GUIA_DESPACHO_DETALLE where GUIA_DESPACHO = " + guiaDespacho.getId() + ""
+ "");
while (resultSet.next()) {
GuiaDespachoDetalle guiaDespachoDetalle = new GuiaDespachoDetalle(resultSet.getInt("ID"));
guiaDespachoDetalle.setCantidad(resultSet.getInt("CANTIDAD"));
guiaDespachoDetalle.setGuiaDespacho(guiaDespacho);
guiaDespachoDetalle.setProducto(getProductoById(resultSet.getInt("PRODUCTO")));
listaGuiaDespachoDetalle.add(guiaDespachoDetalle);
ResultSet resultSet2 = conexion.getConnection().createStatement().executeQuery(""
+ "select * from GUIA_DESPACHO_DETALLE_RFID where GUIA_DESPACHO_DETALLE = " + guiaDespachoDetalle.getId() + ""
+ "");
ArrayList<GuiaDespachoDetalleRfid> listaGuiaDespachoDetalleRfid = new ArrayList<>();
while (resultSet2.next()) {
GuiaDespachoDetalleRfidPK guiaDespachoDetalleRfidPK = new GuiaDespachoDetalleRfidPK();
guiaDespachoDetalleRfidPK.setGuiaDespachoDetalle(guiaDespachoDetalle.getId());
guiaDespachoDetalleRfidPK.setRfid(resultSet2.getString("RFID"));
GuiaDespachoDetalleRfid guiaDespachoDetalleRfid = new GuiaDespachoDetalleRfid(guiaDespachoDetalleRfidPK);
guiaDespachoDetalleRfid.setGuiaDespachoDetalle1(guiaDespachoDetalle);
listaGuiaDespachoDetalleRfid.add(guiaDespachoDetalleRfid);
}
guiaDespachoDetalle.setGuiaDespachoDetalleRfidList(listaGuiaDespachoDetalleRfid);
}
guiaDespacho.setGuiaDespachoDetalleList(listaGuiaDespachoDetalle);
return guiaDespacho;
}
} catch (SQLException ex) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
conexion.closeConnection();
conexion = null;
resultSet = null;
guiaDespacho = null;
listaGuiaDespachoDetalle = null;
}
}
private Producto getProductoById(int id) {
Producto producto = null;
Conexion conexion = new Conexion();
ResultSet resultSet;
try {
resultSet = conexion.getConnection().createStatement().executeQuery("select * from PRODUCTO where id = " + id);
if (resultSet.next()) {
producto = new Producto(resultSet.getInt("ID"));
producto.setNombre(resultSet.getString("NOMBRE"));
producto.setSku(resultSet.getInt("SKU"));
}
return producto;
} catch (SQLException ex) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
return null;
} finally {
producto = null;
conexion.closeConnection();
conexion = null;
resultSet = null;
}
}
public void insertPreparacionPicking(List<PreparacionPicking> listaPreparacionPicking) throws ValidationException {
Conexion conexion = new Conexion();
Statement statement;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
conexion.getConnection().setAutoCommit(false);
statement = conexion.getConnection().createStatement();
for (PreparacionPicking preparacionPicking : listaPreparacionPicking) {
statement.addBatch(""
+ "insert into PREPARACION_PICKING "
+ "("
+ "AREA_PICKING,"
+ "CANTIDAD,"
+ "OPERARIO,"
+ "GUIA_DESPACHO_DETALLE,"
+ "FECHA_INGRESO"
+ ") "
+ "values "
+ "("
+ "" + preparacionPicking.getAreaPicking().getId() + ","
+ "" + preparacionPicking.getCantidad() + ","
+ "" + preparacionPicking.getOperario().getId() + ","
+ "" + preparacionPicking.getGuiaDespachoDetalle().getId() + ","
+ "'" + dateFormat.format(preparacionPicking.getFechaIngreso()) + "'"
+ ")"
+ "");
}
statement.executeBatch();
conexion.getConnection().commit();
} catch (SQLException e) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, e);
try {
conexion.getConnection().rollback();
} catch (SQLException ex) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, ex);
}
throw new ValidationException("No se pudo ingresar la preparación del área de picking");
} finally {
conexion.closeConnection();
conexion = null;
statement = null;
dateFormat = null;
}
}
public void validarPreparacionAreaPicking(GuiaDespacho guiaDespacho) throws ValidationException {
Conexion conexion = new Conexion();
Statement statement;
ResultSet resultSet;
Calendar calendarInicio = Calendar.getInstance();
Calendar calendarFin = Calendar.getInstance();
try {
calendarInicio.setTime(guiaDespacho.getFechaIngreso());
calendarFin.setTime(guiaDespacho.getFechaIngreso());
calendarInicio = DateUtiles.setInicioDia(calendarInicio);
calendarFin = DateUtiles.setFinDia(calendarFin);
statement = conexion.getConnection().createStatement();
resultSet = statement.executeQuery(""
+ "select * "
+ "from AREA_PICKING_PREPARACION_PORCEN "
+ "("
+ "'" + DateUtiles.formatEnglish(calendarInicio.getTime(), true) + "', "
+ "'" + DateUtiles.formatEnglish(calendarFin.getTime(), true) + "', "
+ "null, "
+ "null, "
+ "null, "
+ "" + guiaDespacho.getId() + ""
+ ")"
+ "");
if (resultSet.next()) {
int total = resultSet.getInt("TOTAL");
int cumplidos = resultSet.getInt("CUMPLIDOS");
if (cumplidos >= total) {
throw new ValidationException("Ya se ha llevado a cabo la preparación del área de picking para esta guia de despacho");
}
}
} catch (SQLException e) {
Logger.getLogger(Controlador.class.getName()).log(Level.SEVERE, null, e);
} finally {
conexion.closeConnection();
conexion = null;
statement = null;
resultSet = null;
calendarInicio = null;
calendarFin = null;
}
}
}
|
package com.tencent.mm.ui.transmit;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class SelectConversationUI$18 implements OnClickListener {
final /* synthetic */ SelectConversationUI uEC;
SelectConversationUI$18(SelectConversationUI selectConversationUI) {
this.uEC = selectConversationUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
}
}
|
package com.velue.distance.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.velue.distance.application.MyApplication;
import com.velue.distance.db.DistanceInfoDao;
import com.velue.distance.impl.DistanceComputeImpl;
import com.velue.distance.impl.DistanceComputeInterface;
import com.velue.distance.model.DistanceInfo;
import com.velue.distance.model.GpsLocation;
import com.velue.distance.utils.BDLocation2GpsUtil;
import com.velue.distance.utils.FileUtils;
import com.velue.distance.utils.LogUtil;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by win7 on 2017/2/27.
* 描述:
* 作者:小智 win7
*/
public class LocationService extends Service {
public static final String FILE_NAME = "log.txt";
LocationClient mLocClient;
private Object lock = new Object();
private volatile GpsLocation prevGpsLocation = new GpsLocation(); //定位数据
private volatile GpsLocation currentGpsLocation = new GpsLocation();
private MyLocationListenner myListener = new MyLocationListenner();
private volatile int discard = 1;
private DistanceInfoDao mDistanceInfoDao;
private ExecutorService executor = Executors.newSingleThreadExecutor();
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mDistanceInfoDao = new DistanceInfoDao(this);
//LogUtil.info(LocationService.class, "Thread id ----------->:" + Thread.currentThread().getId());
mLocClient = new LocationClient(this);
mLocClient.registerLocationListener(myListener);
//定位参数设置
LocationClientOption option = new LocationClientOption();
option.setCoorType("bd09ll"); //返回的定位结果是百度经纬度,默认值gcj02
option.setAddrType("all"); //返回的定位结果包含地址信息
option.setScanSpan(5000); //设置发起定位请求的间隔时间为5000ms
option.disableCache(true); //禁止启用缓存定位
option.setProdName("app.ui.activity");
option.setOpenGps(true);
option.setPriority(LocationClientOption.GpsFirst); //设置GPS优先
mLocClient.setLocOption(option);
mLocClient.start();
mLocClient.requestLocation();
}
@Override
@Deprecated
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
if (null != mLocClient) {
mLocClient.stop();
}
startService(new Intent(this, LocationService.class));
}
private class Task implements Callable<String> {
private BDLocation location;
public Task(BDLocation location) {
this.location = location;
}
/**
* 检测是否在原地不动
*
* @param distance
* @return
*/
private boolean noMove(float distance) {
if (distance < 0.01) {
return true;
}
return false;
}
/**
* 检测是否在正确的移动
*
* @param distance
* @return
*/
private boolean checkProperMove(float distance) {
if (distance <= 0.1 * discard) {
return true;
} else {
return false;
}
}
/**
* 检测获取的数据是否是正常的
*
* @param location
* @return
*/
private boolean checkProperLocation(BDLocation location) {
if (location != null && location.getLatitude() != 0 && location.getLongitude() != 0) {
return true;
}
return false;
}
@Override
public String call() throws Exception {
synchronized (lock) {
if (!checkProperLocation(location)) {
LogUtil.info(LocationService.class, "location data is null");
discard++;
return null;
}
if (MyApplication.orderDealInfoId != -1) {
DistanceInfo mDistanceInfo = mDistanceInfoDao.getById(MyApplication.orderDealInfoId);
LogUtil.info(LocationService.class, mDistanceInfo + "");
if (mDistanceInfo != null) {
LogUtil.info(LocationService.class, "行驶中......");
GpsLocation tempGpsLocation = BDLocation2GpsUtil.convertWithBaiduAPI(location);
if (tempGpsLocation != null) {
currentGpsLocation = tempGpsLocation;
} else {
discard++;
}
//日志
String logMsg = "(plat:--->" + prevGpsLocation.lat + " plgt:--->" + prevGpsLocation.lng + ")\n" +
"(clat:--->" + currentGpsLocation.lat + " clgt:--->" + currentGpsLocation.lng + ")";
LogUtil.info(LocationService.class, logMsg);
/** 计算距离 */
float distance = 0.0f;
DistanceComputeInterface distanceComputeInterface = DistanceComputeImpl.getInstance();
distance = (float) distanceComputeInterface.getLongDistance(prevGpsLocation.lat, prevGpsLocation.lng, currentGpsLocation.lat, currentGpsLocation.lng);
if (!noMove(distance)) { //是否在移动
if (checkProperMove(distance)) { //合理的移动
float drivedDistance = mDistanceInfo.getDistance();
mDistanceInfo.setDistance(distance + drivedDistance); //拿到数据库原始距离值, 加上当前值
mDistanceInfo.setLongitude(currentGpsLocation.lng); //经度
mDistanceInfo.setLatitude(currentGpsLocation.lat); //纬度
//日志记录
FileUtils.saveToSDCard(FILE_NAME, "移动距离--->:" + distance + drivedDistance + "\n" + "数据库中保存的距离" + mDistanceInfo.getDistance());
mDistanceInfoDao.updateDistance(mDistanceInfo);
discard = 1;
}
}
prevGpsLocation = currentGpsLocation;
}
}
return null;
}
}
}
/**
* 定位SDK监听函数
*/
public class MyLocationListenner implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
executor.submit(new Task(location));
LogUtil.info(LocationService.class, "经度:" + location.getLongitude());
LogUtil.info(LocationService.class, "纬度:" + location.getLatitude());
if (MyApplication.lng <= 0 && MyApplication.lat <= 0) {
MyApplication.lng = location.getLongitude();
MyApplication.lat = location.getLatitude();
}
}
public void onReceivePoi(BDLocation poiLocation) {
if (poiLocation == null) {
return;
}
}
}
}
|
/*
* Copyright 2017-present The Material Motion Authors. All Rights Reserved.
*
* 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.google.android.reactive.motion.operators;
import android.graphics.RectF;
import android.support.annotation.VisibleForTesting;
import com.google.android.reactive.motion.MotionObservable.MapOperation;
import com.google.android.reactive.motion.MotionObservable.Operation;
public final class FloatArrayOperators {
@VisibleForTesting
FloatArrayOperators() {
throw new UnsupportedOperationException();
}
/**
* Extract the x value from the incoming Float[] stream.
*/
public static Operation<Float[], Float> x() {
return new MapOperation<Float[], Float>() {
@Override
public Float transform(Float[] value) {
return value[0];
}
};
}
/**
* Extract the y value from the incoming Float[] stream.
*/
public static Operation<Float[], Float> y() {
return new MapOperation<Float[], Float>() {
@Override
public Float transform(Float[] value) {
return value[1];
}
};
}
/**
* For an incoming translational Float[] stream, overwrites the x value with the given xValue.
*/
public static Operation<Float[], Float[]> lockToYAxis(final float xValue) {
return new MapOperation<Float[], Float[]>() {
@Override
public Float[] transform(Float[] value) {
float x = xValue;
float y = value[1];
return new Float[]{x, y};
}
};
}
/**
* For an incoming translational Float[] stream, overwrites the y value with the given yValue.
*/
public static Operation<Float[], Float[]> lockToXAxis(final float yValue) {
return new MapOperation<Float[], Float[]>() {
@Override
public Float[] transform(Float[] value) {
float x = value[0];
float y = yValue;
return new Float[]{x, y};
}
};
}
/**
* Applies resistance to values that fall outside of the given rect. Resistance increases until
* the distance reaches length, where resistance becomes infinite.
*/
public static Operation<Float[], Float[]> rubberBanded(final RectF rect, final float length) {
return new MapOperation<Float[], Float[]>() {
@Override
public Float[] transform(Float[] value) {
float x = rubberBand(value[0], rect.left, rect.right, length);
float y = rubberBand(value[1], rect.top, rect.bottom, length);
return new Float[]{x, y};
}
};
}
private static float rubberBand(float value, float min, float max, float bandLength) {
if (value >= min && value <= max) {
// While we're within range we don't rubber band the value.
return value;
}
if (bandLength <= 0) {
// The rubber band doesn't exist, return the minimum value so that we stay put.
return min;
}
if (value > max) {
return band(value - max, bandLength) + max;
} else if (value < min) {
return min - band(min - value, bandLength);
}
return value;
}
/**
* Accepts values from [0...+inf] and ensures that f(x) < bandLength for all values.
*/
private static float band(float value, float bandLength) {
float rubberBandCoefficient = 0.55f;
float demoninator = value * rubberBandCoefficient / bandLength + 1;
return bandLength * (1 - 1 / demoninator);
}
}
|
package cnn;
import main.VisualEdge;
/**
* Repräsentiert eine Kante zwischen 2 Neuronen
*
* @author Jens Krüger
* @author Niklas Bruns
* @author Marc Seibel
*
* @author Florian Determann
* @author Jonas Jansen
*
* @version 1.1
*
*/
public class Edge {
private double currentWeight;
private double lastInputValue;
private Neuron previousNeuron;
private Neuron nextNeuron;
private VisualEdge visualEdge;
/**
* @param previousNeuron Das Neuron, von welchem die Kante ausgeht.
* @param nextNeuron Das Neuron, zu dem die Kante zeigt.
*/
public Edge(Neuron previousNeuron, Neuron nextNeuron) {
currentWeight = Math.random() - 0.5d; // MUSS NOCH GEÄNDERT WERDEN DAMIT DIE GEWICHTE DIE AUS DER DB GELADEN
// WERDEN NICHT WIEDER GELÖSCHT WERDEN
this.previousNeuron = previousNeuron;
this.nextNeuron = nextNeuron;
}
public double getCurrentWeight() {
return currentWeight;
}
public Neuron getNextNeuron() {
return nextNeuron;
}
public Neuron getPreviousNeuron() {
return previousNeuron;
}
public VisualEdge getVisualEdge() {
return visualEdge;
}
/**
* Berechnet das neue Gewicht der Kante mittels Back Propagation. Muss immer von
* dem Neuron aufgerufen werden, das hinter der Kante ist.
*
* @param smallDelta Der Kleindelta Wert aus dem nächsten Neuron.
* @param ableitung Die Ableitung des Input-wertes des nächsten Neurons.
*/
public void modWeight(Double smallDelta, Double ableitung) {
double edgeInput = previousNeuron.getLastOutputValue();
Double bigDelta = smallDelta * ableitung * NetworkController.epsilon * edgeInput;
currentWeight += bigDelta;
}
/**
* Empfängt einen Input vom vorherigen Neuron und sendet es an das nächste
* Neuron weiter.
*
* @param lastInputValue Der Wert, die vom vorherigen Neuron übergeben wird.
*/
public void receiveInput(double lastInputValue) {
this.lastInputValue = lastInputValue;
sendToNextLayer();
}
/**
* Multipliziert das Gewicht der Kante mit dem Input-wert
*/
private void sendToNextLayer() {
double valueToPassOn = lastInputValue * currentWeight;
nextNeuron.receiveInput(valueToPassOn);
}
public void setNewWeight(Double newWeight) {
currentWeight = newWeight;
}
public void setVisualEdge(VisualEdge visualEdge) {
this.visualEdge = visualEdge;
}
}
|
package com.bts.essentials;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by wagan8r on 3/18/18.
*/
@RunWith(SpringRunner.class)
public abstract class BaseUnitTest {
}
|
package org.bashemera.openfarm.model;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "Animal_types")
public class AnimalType {
@Id
private String id;
@Size(min = 3, max = 50)
@NotBlank
private String name;
public AnimalType(String name) {
super();
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "AnimalType [id=" + id + ", name=" + name + "]";
}
}
|
package com.accp.utils;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtils {
// 构建mybatis会话工厂的对象
static SqlSessionFactoryBuilder builder = null;
static SqlSessionFactory factory = null;
static {
builder = new SqlSessionFactoryBuilder();
try {
InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
// 创建mybatis工厂对象
factory = builder.build(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static SqlSession getSession() {
// 创建会话对象
SqlSession session = factory.openSession();
return session;
}
}
|
package auth.pack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ConfirmationServlet
*/
@WebServlet("/confirmar")
public class ConfirmationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
PrintWriter out = response.getWriter();
if (AuthHelpers.validate(id)) {
out.append("confirmacion completada");
} else {
out.append("error al confirmar");
}
}
}
|
package com.thomaster.ourcloud.services.request.marker;
public enum PreQueryRequestValidationType {
PREFLIGHT_UPLOAD_FLIGHT,
UPLOAD_FILE,
UPLOAD_FOLDER,
DELETE;
}
|
package com.bih.nic.saathi.Model;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import java.io.Serializable;
import java.util.Hashtable;
public class WardList implements KvmSerializable, Serializable
{
private static final long serialVersionUID = 1L;
public static Class<WardList> PACS_CLASS = WardList.class;
private String _Ward_Code = "";
private String _Ward_Name = "";
private String _block_code = "";
public WardList(SoapObject obj)
{
this._Ward_Code = obj.getProperty("DistCode").toString();
this._Ward_Name = obj.getProperty("DistNameEn").toString();
this._block_code = obj.getProperty("DistNameEn").toString();
}
public WardList()
{
}
@Override
public Object getProperty(int arg0)
{
// TODO Auto-generated method stub
return null;
}
@Override
public int getPropertyCount()
{
// TODO Auto-generated method stub
return 3;
}
@Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2)
{
// TODO Auto-generated method stub
}
@Override
public void setProperty(int arg0, Object arg1)
{
// TODO Auto-generated method stub
}
public String get_Ward_Code()
{
return _Ward_Code;
}
public void set_Ward_Code(String _Ward_Code)
{
this._Ward_Code = _Ward_Code;
}
public String get_Ward_Name()
{
return _Ward_Name;
}
public void set_Ward_Name(String _Ward_Name)
{
this._Ward_Name = _Ward_Name;
}
public String get_block_code()
{
return _block_code;
}
public void set_block_code(String _block_code)
{
this._block_code = _block_code;
}
}
|
package cn.chinaunicom.monitor.http;
/**
* Created by yfyang on 2017/8/3.
*/
public enum ActionType {
Login("/openapi/mobile/login"), //登录
Chart("/openapi/zabbix/appdata"), //图形:折线图和柱状图
MainframeDetailChart("/openapi/zabbix/listtimevalues"), //图形:折线图和柱状图
CenterList("/openapi/hsf/dropcentervalue"), //中心标志列表
EnvirAndCateList("/openapi/hsf/dropvalues"), //环境和归属列表
MainframeList("/openapi/hsf/ipSearchByApp"), //主机列表
DeployCateAndAppbelong("/openapi/hsf/dropappvalue"), //部署情况中应用归属和应用大类
DeployList("/openapi/hsf/searchAllApp"), //部署情况列表
MainframeDetail("/openapi/zabbix/itemsbyhost"), //主机详情
//AlarmCategory("/openapi/pushmsg/unchecklastdata"), //告警分类 未使用
//AlarmCategory("/openapi/pushmsg/unchecklastdatanew"), //告警分类 测试用
AlarmCategory("/openapi/notification/getcontents"), //告警分类
PostJPushAlias("/openapi/pushmsg/getandroidtoken"), //向服务器推送JPush需要的别名 Alias
UnCheckAlarmDetail("/openapi/pushmsg/uncheckdata"), //获得未查看的告警信息,请求之后才会加到历史告警里面
//UnCheckAlarmDetail("/openapi/pushmsg/uncheckdatanew"), //获得未查看的告警信息,请求之后才会加到历史告警里面
GridInCenter("/openapi/zabbix/reqparams"), //下载所有图的参数,以及每个中心的gridview
Logout("/openapi/androidlogout"), //登出
DataSetIp("/openapi/zabbix/hosts"), //数据归集IP
DataSetCharts("/openapi/zabbix/hostdata"), //数据归集折线图
Reports("/openapi/androidgetreports"), //晨检报告
//测试接口
ConnectHost("/openapi/connecthost"), //链接主机
ExcuteCommand("/openapi/excutecommand"), //执行命令
HostIPs("/openapi/gethostconfig"), //服务器ip
DisconnectServer("/openapi/exitconsole"); //断开控制台链接
public final String actionUrl;
ActionType(String actionUrl) {
this.actionUrl = actionUrl;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import android.graphics.Bitmap;
import android.graphics.Rect;
import com.tencent.map.lib.basemap.data.GeoPoint;
public class kc extends kb {
boolean I;
private float P;
private float Q;
private float R;
private float S;
private int T;
private int U;
private boolean V;
private Bitmap W;
private boolean X;
private boolean Y;
private boolean Z;
private a aa;
private boolean ab;
private boolean ac;
private boolean ad;
private pb ae;
private final byte[] af;
private boolean ag;
private boolean ah;
private Bitmap ai;
private Bitmap aj;
private Bitmap ak;
private int al;
private int am;
public kc(ks ksVar) {
super(ksVar);
this.P = 0.0f;
this.Q = 0.0f;
this.R = 0.0f;
this.S = 0.0f;
this.T = 0;
this.U = 0;
this.V = false;
this.W = null;
this.X = false;
this.Y = true;
this.Z = true;
this.aa = a.a;
this.ab = false;
this.ac = true;
this.ad = false;
this.ae = null;
this.af = new byte[0];
this.ag = false;
this.ah = false;
this.al = 0;
this.am = 0;
this.I = a();
this.t = true;
}
public void a(float f, float f2, float f3, float f4) {
synchronized (this.af) {
this.P = f;
this.Q = f2;
this.R = f3;
this.S = f4;
this.T = (int) Math.abs(this.Q - this.P);
this.U = (int) Math.abs(this.S - this.R);
synchronized (this) {
if (this.V) {
this.V = false;
}
}
}
}
public void a(pb pbVar) {
super.a(pbVar);
this.ae = pbVar;
}
public void c(boolean z) {
this.ac = z;
}
public synchronized void a(boolean z, boolean z2) {
h(true);
if (z && z2) {
this.V = false;
} else {
this.V = true;
}
if (this.ac) {
if (z) {
this.aa = a.a;
}
if (!this.ad) {
this.aa = a.d;
}
if (z && this.A != null && this.A.b()) {
this.A.a();
if (this.z != null) {
this.z.b();
}
}
if (this.aa == a.a) {
this.aa = a.c;
if (this.w.g != null) {
a(this.w.g);
g();
}
}
if (this.aa == a.c) {
this.aa = a.d;
if (this.w.i != null) {
a(this.w.i);
g();
} else {
e();
f();
this.ab = true;
this.w.getMap().a();
}
}
if (this.aa == a.d) {
this.aa = a.b;
if (this.w.h != null) {
a(this.w.h);
g();
}
}
} else {
e();
f();
this.ab = true;
this.w.getMap().a();
}
}
protected void h() {
if (this.aa == a.d) {
e();
f();
this.w.getMap().a();
}
if (this.aa != a.b) {
a(false, false);
return;
}
this.ab = true;
this.w.getMap().a();
}
public void d(boolean z) {
this.ad = z;
}
public void e(boolean z) {
this.ab = z;
}
public void e() {
synchronized (this.d) {
if (!(this.ak == null || this.ak.isRecycled())) {
this.c = true;
}
}
}
public void b(Bitmap bitmap) {
if (bitmap != null) {
synchronized (this.d) {
this.b = bitmap;
}
synchronized (this.af) {
if (!this.ah) {
a(bitmap);
}
}
synchronized (this.d) {
if (this.ab) {
e();
}
}
}
}
public void a(GeoPoint geoPoint) {
this.p = geoPoint;
}
public void b(GeoPoint geoPoint) {
if (geoPoint != null) {
if (this.o == null) {
this.o = new GeoPoint(geoPoint.getLatitudeE6(), geoPoint.getLongitudeE6());
} else {
this.o.setLatitudeE6(geoPoint.getLatitudeE6());
this.o.setLongitudeE6(geoPoint.getLongitudeE6());
}
if (this.a != null) {
this.a.a(this.o);
}
if (this.ab) {
f();
}
}
}
public void i() {
if (this.b != null) {
this.b = null;
}
if (this.W != null) {
this.W = null;
}
if (this.ai != null) {
this.ai = null;
}
if (this.aj != null) {
this.aj = null;
}
synchronized (this.d) {
if (this.ak != null) {
this.ak = null;
}
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public void f(boolean r3) {
/*
r2 = this;
r1 = r2.af;
monitor-enter(r1);
r0 = r2.ag; Catch:{ all -> 0x002d }
if (r0 != r3) goto L_0x0009;
L_0x0007:
monitor-exit(r1); Catch:{ all -> 0x002d }
L_0x0008:
return;
L_0x0009:
r2.ag = r3; Catch:{ all -> 0x002d }
monitor-exit(r1); Catch:{ all -> 0x002d }
r0 = r2.a;
if (r0 == 0) goto L_0x0030;
L_0x0010:
r0 = r2.w;
r0 = r0.g;
if (r0 == 0) goto L_0x0030;
L_0x0016:
r0 = r2.Z;
if (r0 != 0) goto L_0x0030;
L_0x001a:
r0 = new com.tencent.tencentmap.mapsdk.a.kc$1;
r0.<init>(r2, r3);
r2.a(r0);
r0 = r2.w;
r0 = r0.g;
r2.a(r0);
r2.g();
goto L_0x0008;
L_0x002d:
r0 = move-exception;
monitor-exit(r1); Catch:{ all -> 0x002d }
throw r0;
L_0x0030:
r0 = 0;
r2.Z = r0;
r2.i(r3);
r2.j(r3);
goto L_0x0008;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.tencentmap.mapsdk.a.kc.f(boolean):void");
}
public void c(Bitmap bitmap) {
if (bitmap != null) {
synchronized (this.d) {
this.ai = bitmap;
}
synchronized (this.af) {
if (this.ah) {
a(bitmap);
}
}
synchronized (this.d) {
if (this.ab) {
e();
}
}
}
}
public void d(Bitmap bitmap) {
if (bitmap != null) {
this.aj = bitmap;
}
}
public boolean g(boolean z) {
boolean z2 = this.X == z;
this.X = z;
if (this.X && !this.ab) {
this.X = false;
}
return !z2;
}
public void h(boolean z) {
this.Y = z;
this.w.getMap().a();
}
public boolean j() {
return this.Y;
}
public Rect a(hh hhVar) {
Rect a;
synchronized (this.af) {
if (this.a != null) {
i(false);
k(false);
a = this.a.a(hhVar);
i(this.ah);
k(this.ah);
} else {
a = new Rect(0, 0, 0, 0);
}
}
return a;
}
public Rect b(hh hhVar) {
Rect a;
synchronized (this.af) {
if (this.a != null) {
i(true);
k(true);
a = this.a.a(hhVar);
i(this.ah);
k(this.ah);
} else {
a = new Rect(0, 0, 0, 0);
}
}
return a;
}
public iy k() {
return this.a;
}
public void b(int i, int i2) {
this.al = i;
this.am = i2;
l(false);
}
private void j(boolean z) {
synchronized (this.af) {
this.ah = z;
}
synchronized (this.d) {
if (z) {
if (this.ai != null) {
a(this.ai);
}
} else if (this.b != null) {
a(this.b);
}
if (this.ab) {
e();
}
}
a(this.w.h);
g();
}
private void k(boolean z) {
synchronized (this.d) {
if (z) {
if (this.ai != null) {
a(this.ai);
}
} else if (this.b != null) {
a(this.b);
}
}
}
public void i(boolean z) {
l(z);
if (this.a != null) {
this.a.a(this.E, this.F);
}
}
private void l(boolean z) {
int i = this.m;
if (this.ai != null) {
i = this.ai.getHeight();
}
if (i == 0) {
i = 1;
}
if (z) {
this.F = (-(((float) this.am) + 5.0f)) / ((float) i);
} else {
this.F = ((((float) this.al) + 5.0f) + ((float) i)) / ((float) i);
}
}
}
|
package _base.api_helpers;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.LaxRedirectStrategy;
import java.io.IOException;
import java.io.InputStream;
public class ApiService {
private CloseableHttpClient httpClient;
public ApiService() {
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
.setRedirectStrategy(new LaxRedirectStrategy())
.setDefaultCookieStore(new BasicCookieStore()).build();
}
/**
* This function will execute REST get request
* and return a Gson - JsonObject
* @param url
* @return
* @throws IOException
*/
public JsonObject get(String url) throws IOException {
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String body = IOUtils.toString(is, "UTF-8");
is.close();
try {
return new Gson().fromJson(body, JsonObject.class);
}catch (JsonSyntaxException ex){
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.