text stringlengths 10 2.72M |
|---|
package com.sparknetworks.loveos.domain;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RangeTest {
@Test
void should_return_false_when_value_passed_is_not_within_range_of_two_set_numbers() {
Range<Integer> range = Range.of(1, 4);
assertFalse(range.isWithinRange(0));
assertFalse(range.isWithinRange(5));
}
@Test
void should_return_true_when_value_passed_is_within_range_of_two_set_numbers() {
Range<Integer> range = Range.of(1, 4);
assertTrue(range.isWithinRange(1));
assertTrue(range.isWithinRange(2));
assertTrue(range.isWithinRange(3));
assertTrue(range.isWithinRange(4));
}
} |
package com.kodilla.patterns.strategy.social;
public class Millenials extends User {
public Millenials(String personName) {
super(personName);
this.socialPublisher = new FacebookPublisher();
}
}
|
package com.hawk.application.model;
import org.hibernate.validator.constraints.NotEmpty;
public class LoginVo {
@NotEmpty(message="{not.null}")
protected String email;
@NotEmpty(message="{not.null}")
protected String password;
@NotEmpty(message="{not.null}")
protected String checkCode;
protected String error;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCheckCode() {
return checkCode;
}
public void setCheckCode(String checkCode) {
this.checkCode = checkCode;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
|
package com.espendwise.manta.model.view;
// Generated by Hibernate Tools
import com.espendwise.manta.model.ValueObject;
import com.espendwise.manta.model.data.GenericReportData;
import com.espendwise.manta.model.data.GroupData;
import java.util.List;
/**
* UserGroupInformationView generated by hbm2java
*/
public class UserGroupInformationView extends ValueObject implements java.io.Serializable {
private static final long serialVersionUID = -1;
public static final String GROUP = "group";
public static final String APPLICATION_FUNCTION_NAMES = "applicationFunctionNames";
public static final String REPORTS = "reports";
private GroupData group;
private List<String> applicationFunctionNames;
private List<GenericReportData> reports;
public UserGroupInformationView() {
}
public UserGroupInformationView(GroupData group) {
this.setGroup(group);
}
public UserGroupInformationView(GroupData group, List<String> applicationFunctionNames, List<GenericReportData> reports) {
this.setGroup(group);
this.setApplicationFunctionNames(applicationFunctionNames);
this.setReports(reports);
}
public GroupData getGroup() {
return this.group;
}
public void setGroup(GroupData group) {
this.group = group;
setDirty(true);
}
public List<String> getApplicationFunctionNames() {
return this.applicationFunctionNames;
}
public void setApplicationFunctionNames(List<String> applicationFunctionNames) {
this.applicationFunctionNames = applicationFunctionNames;
setDirty(true);
}
public List<GenericReportData> getReports() {
return this.reports;
}
public void setReports(List<GenericReportData> reports) {
this.reports = reports;
setDirty(true);
}
}
|
package day3_variables_dataTypes;
public class PrimitiveVariables {
public static void main(String[] args) {
// TODO Auto-generated method stub
byte b1=25;
byte b2=-18;
byte b3=-16;
System.out.println("b1= " + b1);
System.out.println("b2= " + b2);
short b4=- 32678;
short b5= 3276;
System.out.println("b4= "+ b5);
System.out.println("b5= "+ b5);
int i3=100_000;
System.out.println("i3= "+ i3);
long l5=758385736465364646L; // L is mandotory because out if literal
long l6=5000; // L is optional. because is of int range
long creditCardNumber= 9870_7866_8760_9734l;
System.out.println("l5= " + l5);
System.out.println("l6= " + l6);
System.out.println("CreditCardNumber = " + creditCardNumber);
// Floating Number; Default is Double
float f1= 2.1f;
float f2= 45445422.6535f;
System.out.println("Float Number= " + f1);
System.out.println("Float NUmber= "+ f2);
char c1='A';
char c2= 65;
System.out.println(c2);
System.out.println(c1);
char c3=36 ;
System.out.println("I have only 36"+ c3);
boolean status= true;
boolean status2= false;
System.out.println("You are eligible to tka the exam: " + status);
System.out.println("You are eligible to tka the exam: " + status2);
char c8='B';
System.out.println(c8);
String name="Omer Ozdil";
System.out.println("My name is"+ name);
String name2="Busra";
System.out.println("My love name is "+ name2);
String age="12";
}
}
|
package ba.bitcamp.LabS13D02.threads;
import java.util.Scanner;
public class ThreadInterupt {
public static void main(String[] args) {
System.out.println("Start");
final Thread thread = new Thread() {
public void run() {
try {
sleep(3000);
System.out.println("Good Morning");
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
};
Thread thread2 = new Thread() {
public void run() {
try {
sleep(1500);
thread.interrupt();
System.out.println("Wakey wakey");
} catch (InterruptedException e) {
System.err.println(e.getMessage());
}
}
};
thread.setDaemon(true);
// thread2.setDaemon(false);
thread.start();
thread2.start();
Scanner scan = new Scanner(System.in);
scan.nextLine();
System.out.println("End");
}
}
|
package com.tencent.mm.plugin.appbrand.wxawidget.console;
import android.view.View;
import android.view.View.OnFocusChangeListener;
class ConsolePanel$5 implements OnFocusChangeListener {
final /* synthetic */ ConsolePanel gQy;
ConsolePanel$5(ConsolePanel consolePanel) {
this.gQy = consolePanel;
}
public final void onFocusChange(View view, boolean z) {
if (!z) {
f.ck(view);
}
}
}
|
package ru.dias.springdatainterview.persistence.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import ru.dias.springdatainterview.persistence.entities.Student;
import java.util.UUID;
@Repository
public interface StudentRepository extends JpaRepository<Student, UUID> {
}
|
package ordon.marek.adventofcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Day4_2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String line;
int id = 0;
String[] tab;
String[] tab2;
while(scanner.hasNextLine()){
line = scanner.nextLine();
tab = line.split("\\[");
tab2 = tab[0].split("-");
id = Integer.parseInt(tab2[tab2.length-1]);
tab2 = Arrays.copyOfRange(tab2, 0, tab2.length-1);
id = id%26;
String output = "";
for (int i = 0; i < tab2.length; i++) {
output += cipher(tab2[i],id);
output += " ";
}
if (output.contains("north")) {
System.out.println(line);
System.out.println(output + " " + id);
}
}
}
private static String cipher(String msg, int shift){
String s = "";
int len = msg.length();
for(int x = 0; x < len; x++){
char c = (char)(msg.charAt(x) + shift);
if (c > 'z')
s += (char)(msg.charAt(x) - (26-shift));
else
s += (char)(msg.charAt(x) + shift);
}
return s;
}
}
|
package test.SuiteLogin;
import org.testng.annotations.Test;
public class LoginTestLogout extends SuiteLogin{
@Test
public void nada2(){
System.out.println("Não faz nada 2");
navegador.get("http://www.globo.com");
System.out.println("Não faz nada 2");
}
}
|
package com.prashanth.sunvalley.Model;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class LocationListDTO {
private List<LocationDTO> locations;
}
|
package org.tomat.agnostic.graphs.printer;
import org.jgraph.JGraph;
import org.jgraph.graph.AttributeMap;
import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;
import org.jgrapht.DirectedGraph;
import org.jgrapht.ListenableGraph;
import org.jgrapht.ext.JGraphModelAdapter;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultListenableGraph;
import org.jgrapht.graph.DirectedMultigraph;
import org.tomat.agnostic.components.AgnosticComponent;
import org.tomat.agnostic.graphs.AgnosticGraph;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.Random;
/**
* Created by Kiuby88 on 30/10/14.
*/
public class JGraphAdapterPrinter
extends JApplet implements Runnable{
private static final long serialVersionUID = 3256444702936019250L;
private static final Color DEFAULT_BG_COLOR = Color.decode("#FAFBFF");
private static final Dimension DEFAULT_SIZE = new Dimension(530, 320);
private JGraphModelAdapter<String, DefaultEdge> jgAdapter;
private AgnosticGraph agnosticGraph;
Thread t;
public JGraphAdapterPrinter(AgnosticGraph agnosticGraph) {
this.agnosticGraph = agnosticGraph;
}
public void init() {
ListenableGraph<String, DefaultEdge> g =
new ListenableDirectedMultigraph<>(
DefaultEdge.class);
jgAdapter = new JGraphModelAdapter<>(g);
JGraph jgraph = new JGraph(jgAdapter);
adjustDisplaySettings(jgraph);
getContentPane().add(jgraph);
resize(DEFAULT_SIZE);
this.setName("TOMAT. Agnostic Graph Viewer");
addVertex(g);
addEdges(g);
randomizeLocations();
t=new Thread(this);
t.start();
}
private void addVertex(ListenableGraph<String, DefaultEdge> g){
for (AgnosticComponent agnosticComponentSource : agnosticGraph.getVertexSet()) {
g.addVertex(agnosticComponentSource.getId());
}
}
private void addEdges(ListenableGraph<String, DefaultEdge> g){
for (AgnosticComponent agnosticComponentSource : agnosticGraph.getVertexSet()) {
addOutcomingEdgesOfAVertex(g, agnosticComponentSource);
}
}
private void addOutcomingEdgesOfAVertex(ListenableGraph<String, DefaultEdge> g, AgnosticComponent agnosticComponentSource) {
if (agnosticGraph.getOutcomigngVertexOf(agnosticComponentSource) != null) {
for (AgnosticComponent target : agnosticGraph.getOutcomigngVertexOf(agnosticComponentSource)) {
g.addEdge(agnosticComponentSource.getId(), target.getId());
}
}
}
private void adjustDisplaySettings(JGraph jg) {
jg.setPreferredSize(DEFAULT_SIZE);
Color c = DEFAULT_BG_COLOR;
String colorStr = null;
try {
colorStr = getParameter("bgcolor");
} catch (Exception e) {
}
if (colorStr != null) {
c = Color.decode(colorStr);
}
jg.setBackground(c);
}
public void randomizeLocations() {
int H,W;
Random r = new Random();
H=this.getHeight();
W=this.getWidth();
for(AgnosticComponent agnosticComponentSource : agnosticGraph.getVertexSet()){
positionVertexAt(agnosticComponentSource.getId(),r.nextInt(W),r.nextInt(H));
}
}
@SuppressWarnings("unchecked") // FIXME hb 28-nov-05: See FIXME below
private void positionVertexAt(Object vertex, int x, int y) {
DefaultGraphCell cell = jgAdapter.getVertexCell(vertex);
AttributeMap attr = cell.getAttributes();
Rectangle2D bounds = GraphConstants.getBounds(attr);
Rectangle2D newBounds =
new Rectangle2D.Double(
x,
y,
bounds.getWidth(),
bounds.getHeight());
GraphConstants.setBounds(attr, newBounds);
// TODO: Clean up generics once JGraph goes generic
AttributeMap cellAttr = new AttributeMap();
cellAttr.put(cell, attr);
jgAdapter.edit(cellAttr, null, null, null);
}
@Override
public void run() {
}
/**
* a listenable directed multigraph that allows loops and parallel edges.
*/
private static class ListenableDirectedMultigraph<V, E>
extends DefaultListenableGraph<V, E>
implements DirectedGraph<V, E> {
private static final long serialVersionUID = 1L;
ListenableDirectedMultigraph(Class<E> edgeClass) {
super(new DirectedMultigraph<V, E>(edgeClass));
}
}
}
|
package idv.jack;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.java.iPet.R;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;
import idv.randy.me.MembersVO;
import idv.randy.ut.Me;
public class ApdotionActivity extends AppCompatActivity {
private final static String TAG = "ApdotionActivity";
private MyTask caseTask;
List<Case> csLists;
private SpotGetImageTask spotGetImageTask;
private FloatingActionButton fabtn;
private SwipeRefreshLayout swipeRefreshLayout;
private CaseAdapter caseAdapter;
private MyTask sendtask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apdotion);
swipeRefreshLayout =
(SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
getpetList();
caseAdapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
}
});
RecyclerView csRecycleView = (RecyclerView) findViewById(R.id.lvPet);
csRecycleView.setLayoutManager(new LinearLayoutManager(this));
getpetList();
caseAdapter = new CaseAdapter(this);
csRecycleView.setAdapter(caseAdapter);
fabtn = (FloatingActionButton) findViewById(R.id.btnAdd);
// getMbName();
}
private void getpetList() {
if (Common.networkConnected(this)) {
String url = Common.URL;
List<Case> cases = null;
try {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("param", "getAll");
String jsonOut = jsonObject.toString();
caseTask = new MyTask(url, jsonOut);
String jsonIn = caseTask.execute().get();
Log.d(TAG, jsonIn);
// Gson gson = new Gson();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
Type listType = new TypeToken<List<Case>>() {
}.getType();
csLists = gson.fromJson(jsonIn, listType);
Log.e(TAG, "csLists.size = " + csLists.size());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
if (cases == null || cases.isEmpty()) {
// Common.showToast(this, R.string.msg_NoSpotsFound);
} else {
// csListView.setAdapter(new CaseAdapter(this, cases));
}
} else {
Common.showToast(this, R.string.msg_NoNetwork);
}
}
@Override
public void onStart() {
super.onStart();
getpetList();
caseAdapter.notifyDataSetChanged();
}
private class CaseAdapter extends RecyclerView.Adapter<CaseAdapter.MyViewHolder> {
private LayoutInflater layoutInflater;
private int imageSize;
CaseAdapter(Context context) {
layoutInflater = LayoutInflater.from(context);
/* 螢幕寬度除以4當作將圖的尺寸 */
imageSize = getResources().getDisplayMetrics().widthPixels / 4;
}
@Override
public int getItemCount() {
return csLists.size();
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.item_view, parent, false);
return new MyViewHolder(itemView);
}
//要抓值設定UI顯示的寫在這裡
@Override
public void onBindViewHolder(MyViewHolder myViewHolder, int position) {
final Case cs = csLists.get(position);
spotGetImageTask = new SpotGetImageTask(Common.URL, cs.getPetNo(), imageSize, myViewHolder.tvImg);
spotGetImageTask.execute();
myViewHolder.tvSituation.setText(cs.getSituation());
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// petInformation fragment = new petInformation();
Intent intent = new Intent(ApdotionActivity.this,petInformation.class);
Bundle bundle = new Bundle();
bundle.putSerializable("cs", cs);
intent.putExtras(bundle);
startActivity(intent);
// fragment.setArguments(bundle);
// petinformation.beginTransaction().replace(R.id.flMainActivity, fragment).addToBackStack(null).commit();
}
});
fabtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences pref = getSharedPreferences("UserData", MODE_PRIVATE);
if (!pref.getBoolean("login", false)) {
Toast.makeText(Me.gc(), "請先登入", Toast.LENGTH_SHORT).show();
return;
}
// ApdoInsert fai = new ApdoInsert();
// ApdoInsert.beginTransaction().replace(R.id.flapdoinsert, fai).addToBackStack(null).commit();
Intent intent = new Intent(ApdotionActivity.this,ApdoInsertActivity.class);
startActivity(intent);
}
});
}
//要用的UI宣告在這裡
class MyViewHolder extends RecyclerView.ViewHolder {
ImageView tvImg;
TextView tvSituation,tvmore;
MyViewHolder(View itemView) {
super(itemView);
tvSituation = (TextView) itemView.findViewById(R.id.tvSituation);
tvImg = (ImageView) itemView.findViewById(R.id.tvImg);
tvmore =(TextView) itemView.findViewById(R.id.tvmore);
}
}
}
}
|
package com.philschatz.checklist;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;
import com.philschatz.checklist.notifications.CompleteNotificationService;
import com.philschatz.checklist.notifications.Snooze20Minutes;
import com.philschatz.checklist.notifications.Snooze5Minutes;
/*
* This generates the homescreen notification for checklist items that have a reminder
*/
public class TodoNotificationService extends IntentService {
public TodoNotificationService() {
super("TodoNotificationService");
}
// !!! Make sure you add an entry to AndroidManifest.xml
private Notification.Action buildSnooze(Class intentService, String label, ToDoItem item, String listKey, String itemKey, int icon) {
Intent snoozeIntent = new Intent(this, intentService);
snoozeIntent.putExtra(Const.TODOITEMSNAPSHOT, item);
snoozeIntent.putExtra(Const.TODOLISTKEY, listKey);
snoozeIntent.putExtra(Const.TODOITEMKEY, itemKey);
int hashCode = itemKey.hashCode();
PendingIntent snoozePendingIntent = PendingIntent.getService(this, hashCode, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Action snoozeAction = new Notification.Action.Builder(icon, label, snoozePendingIntent)
.build();
return snoozeAction;
}
protected void onHandleIntent(Intent intent) {
// mTodoText = intent.getStringExtra(TODOTEXT);
// mTodoUUID = intent.getStringExtra(TODOUUID);
// mTodoRemindAt = (Date) intent.getSerializableExtra(TODOREMINDAT);
// if (mTodoRemindAt == null) {
// throw new RuntimeException("BUG: Missing remindAt");
// }
ToDoItem item = (ToDoItem) intent.getSerializableExtra(Const.TODOITEMSNAPSHOT);
ToDoList list = (ToDoList) intent.getSerializableExtra(Const.TODOLISTSNAPSHOT);
String listKey = intent.getStringExtra(Const.TODOLISTKEY);
String itemKey = intent.getStringExtra(Const.TODOITEMKEY);
if (item == null) {
throw new RuntimeException("Missing " + Const.TODOITEMSNAPSHOT);
}
if (list == null) {
throw new RuntimeException("Missing " + Const.TODOLISTSNAPSHOT);
}
if (listKey == null) {
throw new RuntimeException("Missing " + Const.TODOLISTKEY);
}
if (itemKey == null) {
throw new RuntimeException("Missing " + Const.TODOITEMKEY);
}
final int hashCode = itemKey.hashCode();
Log.d("OskarSchindler", "onHandleIntent called");
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent editReminderIntent = new Intent(this, AddToDoItemActivity.class);
editReminderIntent.putExtra(Const.TODOITEMSNAPSHOT, item);
editReminderIntent.putExtra(Const.TODOLISTKEY, listKey);
editReminderIntent.putExtra(Const.TODOITEMKEY, itemKey);
// Intent completeIntent = new Intent(this, CompleteNotificationService.class);
// completeIntent.putExtra(Const.TODOITEMSNAPSHOT, item);
// completeIntent.putExtra(Const.TODOLISTKEY, listKey);
// completeIntent.putExtra(Const.TODOITEMKEY, itemKey);
Intent snooze20 = new Intent(this, Snooze20Minutes.class);
snooze20.putExtra(Const.TODOITEMSNAPSHOT, item);
snooze20.putExtra(Const.TODOLISTKEY, listKey);
snooze20.putExtra(Const.TODOITEMKEY, itemKey);
if (!item.hasReminder()) {
throw new RuntimeException("BUG: just making sure the item has a reminder");
}
Notification notification = new Notification.Builder(this)
.setAutoCancel(false) // hide the notification when an action is performed?
.setCategory(Notification.CATEGORY_REMINDER)
.setPriority(Notification.PRIORITY_HIGH) // Useful for the heads up notification so people are reminded
.setColor(list.getColor())
.setSmallIcon(R.drawable.ic_done_white_24dp)
.setContentTitle(item.getTitle())
.setContentText(list.getTitle())
.setUsesChronometer(true) // Starts ticking up to show how much more reddit time you're spending (beyond the alotted 20min or whatever)
.setDefaults(Notification.DEFAULT_SOUND)
.setContentIntent(PendingIntent.getActivity(this, hashCode, editReminderIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setDeleteIntent(PendingIntent.getService(this, hashCode, snooze20, PendingIntent.FLAG_UPDATE_CURRENT))
.addAction(buildSnooze(Snooze5Minutes.class, "5 min", item, listKey, itemKey, R.drawable.ic_snooze_white_24dp))
.addAction(buildSnooze(CompleteNotificationService.class, "complete", item, listKey, itemKey, R.drawable.ic_done_white_24dp))
.setWhen(item.remindAt())
.build();
manager.notify(hashCode, notification);
// Uri defaultRingone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// MediaPlayer mp = new MediaPlayer();
// try{
// mp.setDataSource(this, defaultRingone);
// mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
// mp.prepare();
// mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
// @Override
// public void onCompletion(MediaPlayer mp) {
// mp.release();
// }
// });
// mp.start();
//
// }
// catch (Exception e){
// e.printStackTrace();
// }
}
}
|
// SCJPP313Exercise10
// Chapter 4: Operators
interface Vessel { void method1(); } |
package com.example.library.activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputType;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.example.library.R;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
//<editor-fold desc="--Declaration--">
private TextView textView;
private EditText edtName, edtLastName, edtEmail, edtPassword;
private Button btnRegister;
private ImageView imgPassword;
private String name, lastName, email, pass;
private Animation animation;
//</editor-fold>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
findViews();
animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.anim_txt);
textView.setAnimation(animation);
btnRegister.setOnClickListener(this);
imgPassword.setOnClickListener(this);
btnRegister.setBackgroundResource(R.drawable.shape_btn);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.btn_register:
if (isNetworkConnected()) {
name = edtName.getText().toString().trim();
lastName = edtLastName.getText().toString().trim();
email = edtEmail.getText().toString().trim();
pass = edtPassword.getText().toString().trim();
// if (name.isEmpty()) {
// edtName.setError("Please enter name");
// } else if (lastName.isEmpty()) {
// edtLastName.setError("Please enter lastName");
// } else if (email.isEmpty()) {
// edtEmail.setError("Please enter email");
// } else if (pass.isEmpty()) {
// edtPassword.setError("Please enter password");
// } else
if (!email.isEmpty()) {
validateEmail();
}
} else {
showDialog();
}
break;
case R.id.img_password:
if (IsPasswordType(RegisterActivity.this, edtPassword)) {
edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_CLASS_TEXT);
imgPassword.setImageResource(R.drawable.ic_baseline_visibility_off);
} else {
edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
imgPassword.setImageResource(R.drawable.ic_baseline_visibility);
}
edtPassword.setSelection(edtPassword.getText().toString().length());
break;
}
}
private void retrieveSharedPreferences() {
SharedPreferences.Editor editor = getSharedPreferences("register", MODE_PRIVATE).edit();
editor.putString("name", name);
editor.putString("lastName", lastName);
editor.putString("email", email);
editor.putString("pass", pass);
editor.putBoolean("isRegister", true);
editor.apply();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
private boolean validateEmail() {
String val = edtEmail.getText().toString().trim();
String checkEmail = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
// if (val.isEmpty()) {
// edtEmail.setError("Field can not be empty");
// return false;
// }
if (!val.matches(checkEmail)) {
edtEmail.setError("Please enter the correct email");
return false;
} else {
edtEmail.setError(null);
retrieveSharedPreferences();
return true;
}
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
private void showDialog() {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setMessage("لطفا به اینترنت متصل شوید");
ad.setCancelable(false);
ad.setPositiveButton("اتصال به اینترنت", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
});
ad.setNegativeButton("بستن", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
ad.create().show();
}
public static boolean IsPasswordType(Context context, EditText editText) {
boolean type = false;
final int inputType = editText.getInputType();
switch (inputType) {
case (InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT): {
type = true;
}
break;
case (InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_CLASS_TEXT): {
type = false;
}
break;
}
return type;
}
private void findViews() {
textView = findViewById(R.id.txt_register);
edtName = findViewById(R.id.edt_name_register);
edtLastName = findViewById(R.id.edt_last_name_register);
edtEmail = findViewById(R.id.edt_email_register);
edtPassword = findViewById(R.id.edt_password_register);
imgPassword = findViewById(R.id.img_password);
btnRegister = findViewById(R.id.btn_register);
}
} |
package lab_9_problem2;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.lang.Integer;
public class StudentCourses {
public static void main(String[] args)
{
Scanner inputStream=null; //initializing the inputstream
String fileName="test.txt";
try //opening up the file
{
inputStream=new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening file "+fileName+"!");
System.exit(0);
}
HashMap<Integer, ArrayList<String>> students=new HashMap<Integer, ArrayList<String>>(); //initializing the hashmap
int id=0; //will be used to store the id numbers for each student
String course=new String(); //will be used to store the courses for each student
String temp=new String(); //used to cut the string into two parts, ID and course
String string=new String(); //used to extract the text from the file
while(inputStream.hasNextLine())
{
string=inputStream.nextLine();
temp=string.substring(0,2); //grabbing the ID number from the input
temp=temp.trim(); //deleting extraneous spaces
id=Integer.parseInt(temp); //translating the string to a integer
course=string.substring(2); //grabbing the course from the input
course=course.trim(); //deleting extraneous spaces
if(id==-1)//breaks out of the loop if the ID number is -1
break;
if(students.get(id)==null) //activates if there is no entry with the student's ID number yet
{
students.put(id,new ArrayList<String>()); //gets the individual student initialized
students.get(id).add(course); //drops the course number into the arraylist
}
else
students.get(id).add(course); //drops the course number into the arraylist
}
int size=students.size(); //used to break out of the loop
int i=0; //will be used to increment inside the following while loop
System.out.println("All student data:");
System.out.println("-----------------------------");
while(size>0)
{
if(students.containsKey(i))
{
System.out.println("Student ID: "+i);
System.out.println("Classes: ");
Object[] classes=students.get(i).toArray(); //this and the following for-loop are for printing out the courses for each student more cleanly
for(int j=0;j<classes.length;j++)
System.out.println(" "+classes[j]);
System.out.println();
size--;
}
i++;
}
System.out.println("-----------------------------");
System.out.println("End of program");
inputStream.close();
}
}
|
package evm.dmc.core.api;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
//import evm.dmc.core.arithmetic.AbstractArithmeticFunction.ArithmeticContext;
@Configuration
// @ComponentScan(basePackages="evm.dmc.core.arithmetic")
// @ComponentScan(basePackageClasses={/*AbstractArithmeticFunction.class,
// ArithmeticContext.class*/})
@ComponentScan( basePackages="evm.dmc.core.api")
//@Import({evm.dmc.weka.DMCWekaConfig.class})
public class DMCCoreApiConfig {
}
|
package com.tencent.mm.plugin.sns.g;
import com.tencent.mm.protocal.c.alh;
import com.tencent.mm.protocal.c.ate;
import com.tencent.mm.protocal.c.atg;
import com.tencent.mm.protocal.c.cj;
import com.tencent.mm.protocal.c.dx;
import com.tencent.mm.protocal.c.dy;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.bl;
import com.tencent.mm.sdk.platformtools.x;
import java.util.LinkedList;
import java.util.Map;
public final class a {
private static int MO(String str) {
int i = 0;
try {
return bi.getInt(str, 0);
} catch (Exception e) {
x.e("MicroMsg.AlbumBgHelper", "parserInt error " + str);
return i;
}
}
private static float ne(String str) {
float f = 0.0f;
if (str == null) {
return f;
}
try {
return bi.getFloat(str, 0.0f);
} catch (Exception e) {
x.e("MicroMsg.AlbumBgHelper", "parseFloat error " + str);
return f;
}
}
private static String nf(String str) {
if (str == null) {
return "";
}
return str;
}
public static cj MP(String str) {
Map z = bl.z(str, "albumList");
cj cjVar = new cj();
if (z == null) {
return cjVar;
}
cjVar.jRj = nf((String) z.get(".albumList.$lang"));
dx dxVar = new dx();
dxVar.jPe = nf((String) z.get(".albumList.album.author.name"));
dxVar.bHD = nf((String) z.get(".albumList.album.author.title"));
dxVar.rej = nf((String) z.get(".albumList.album.author.description"));
dxVar.rei = nf((String) z.get(".albumList.album.author.quote"));
dy dyVar = new dy();
atg p = p(z, ".albumList.album.author.icon.media");
String str2 = (String) z.get(".albumList.album.author.icon.media.id");
String str3 = (String) z.get(".albumList.album.author.icon.media.type");
String str4 = (String) z.get(".albumList.album.author.icon.media.title");
String str5 = (String) z.get(".albumList.album.author.icon.media.desc");
String str6 = (String) z.get(".albumList.album.author.icon.media.url");
String str7 = (String) z.get(".albumList.album.author.icon.media.private");
String str8 = (String) z.get(".albumList.album.author.icon.media.thumb");
String str9 = (String) z.get(".albumList.album.author.icon.media.url.$type");
String str10 = (String) z.get(".albumList.album.author.icon.media.thumb.$type");
ate ate = new ate();
ate.ksA = nf(str2);
ate.hcE = MO(str3);
ate.bHD = nf(str4);
ate.jOS = nf(str5);
ate.jPK = nf(str6);
ate.rVD = MO(str9);
ate.rVE = nf(str8);
ate.rVF = MO(str10);
ate.rVG = MO(str7);
ate.rVH = p;
dyVar.rel = ate;
dxVar.rek = dyVar;
cjVar.rcL = dxVar;
int i = 0;
while (true) {
Object obj;
int i2 = i;
alh alh = new alh();
if (i2 == 0) {
obj = ".albumList.album.groupList.group.name";
str4 = ".albumList.album.groupList.group.mediaList";
} else {
obj = ".albumList.album.groupList.group" + i2 + ".name";
str4 = ".albumList.album.groupList.group" + i2 + ".mediaList";
}
str2 = (String) z.get(obj);
if (str2 == null) {
return cjVar;
}
alh.jPe = nf(str2);
alh.ruA = q(z, str4);
cjVar.rcM.add(alh);
i = i2 + 1;
}
}
private static atg p(Map<String, String> map, String str) {
String str2 = str + ".size.$width";
String str3 = str + ".size.$height";
str2 = (String) map.get(str2);
str3 = (String) map.get(str3);
String str4 = (String) map.get(str + ".size.$totalSize");
atg atg = new atg();
atg.rWv = 0.0f;
atg.rWu = 0.0f;
atg.rWw = 0.0f;
if (str2 != null) {
atg.rWu = ne(str2);
}
if (str3 != null) {
atg.rWv = ne(str3);
}
if (str4 != null) {
atg.rWw = ne(str4);
}
return atg;
}
private static LinkedList<ate> q(Map<String, String> map, String str) {
LinkedList<ate> linkedList = new LinkedList();
int i = 0;
while (true) {
Object obj;
Object obj2;
Object obj3;
Object obj4;
Object obj5;
String str2;
String str3;
String str4;
String str5;
String str6;
Object obj6;
Object obj7;
Object obj8;
Object obj9;
String obj62;
String obj72;
String obj82;
String obj92;
if (i != 0) {
obj = str + ".media" + i + ".id";
obj2 = str + ".media" + i + ".type";
obj3 = str + ".media" + i + ".title";
obj4 = str + ".media" + i + ".desc";
obj5 = str + ".media" + i + ".url";
str2 = str + ".media" + i + ".thumb";
str3 = str + ".media" + i + ".url.$type";
str4 = str + ".media" + i + ".thumb.$type";
str5 = str + ".media" + i + ".private";
str6 = str + ".media" + i;
obj62 = str5;
obj72 = str4;
obj82 = str3;
obj92 = str2;
} else {
obj = str + ".media.id";
obj2 = str + ".media.type";
obj3 = str + ".media.title";
obj4 = str + ".media.desc";
obj5 = str + ".media.url";
str2 = str + ".media.thumb";
str3 = str + ".media.url.$type";
str4 = str + ".media.thumb.$type";
str5 = str + ".media.private";
str6 = str + ".media";
obj62 = str5;
obj72 = str4;
obj82 = str3;
obj92 = str2;
}
if (obj != null && obj2 != null) {
atg p = p(map, str6);
str6 = (String) map.get(obj);
str5 = (String) map.get(obj2);
str4 = (String) map.get(obj3);
str3 = (String) map.get(obj4);
str2 = (String) map.get(obj5);
obj62 = (String) map.get(obj62);
obj92 = (String) map.get(obj92);
obj82 = (String) map.get(obj82);
obj72 = (String) map.get(obj72);
if (str6 == null || str5 == null) {
break;
}
ate ate = new ate();
ate.ksA = nf(str6);
ate.hcE = MO(str5);
ate.bHD = nf(str4);
ate.jOS = nf(str3);
ate.jPK = nf(str2);
ate.rVD = MO(obj82);
ate.rVE = nf(obj92);
ate.rVF = MO(obj72);
ate.rVG = MO(obj62);
ate.rVH = p;
linkedList.add(ate);
i++;
} else {
break;
}
}
return linkedList;
}
}
|
package com.lee.config.service;
/**
* @author: Chill
* @Date: 2020/5/27 16:09
*/
public class HelloService {
}
|
package com.dsc.dw.rest;
//here is where I added ldap stuff
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchResult;
//import javax.servlet.ServletContext;
import javax.naming.NamingEnumeration;
import javax.naming.AuthenticationException;
import javax.naming.AuthenticationNotSupportedException;
import javax.naming.Context;
import javax.naming.NameClassPair;
//import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
//import org.apache.http.HttpEntity;
//import org.apache.http.util.EntityUtils;
import java.sql.Timestamp;
import java.util.Hashtable;
//ending lDAP stuff
//new import for json
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONObject;
import com.dsc.dw.internal.*;
@Path("/v1/dw")
public class DW {
@GET
@Produces(MediaType.TEXT_HTML)
public String returnTitle()
{
//ServletContext sc = getServletContext();
//String testNameValue = sc.getInitParameter("testName");
java.util.Date date= new java.util.Date();
/*
APIEvent R1 = new APIEvent( "Thread-1");
R1.start();
java.util.Date date= new java.util.Date();
System.out.println(" Return back to user at "+new Timestamp(date.getTime()));
*/
return "<p>Default Data Warehouse Service</p>"+new Timestamp(date.getTime());
}
//**************** Authenication Service
@Path("/whoami")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response whoami(JSONObject inputJsonObj) throws Exception {
java.util.Date date= new java.util.Date();
java.util.Date sdate=new Timestamp(date.getTime());
Response rb = null;
ldap vr = new ldap();
rb=vr.ldap(inputJsonObj);
return rb;
}
//**************** DSC WMS Volume
@Path("/dscwmsvolume")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response DSCWMSVolume(JSONObject inputJsonObj) throws Exception {
Response rb = null;
java.util.Date date= new java.util.Date();
java.util.Date sdate=new Timestamp(date.getTime());
DSCWMSVolume dscwmsvolume = new DSCWMSVolume();
rb=dscwmsvolume.DSCWMSVolume(inputJsonObj);
return rb;
}
//**************** DSC WMS Metric status
@Path("/loadstatus")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response LoadStatus(JSONObject inputJsonObj) throws Exception {
Response rb = null;
java.util.Date date= new java.util.Date();
java.util.Date sdate=new Timestamp(date.getTime());
LoadStatus lstatus = new LoadStatus();
rb=lstatus.LoadStatus(inputJsonObj);
return rb;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import java.util.Map;
public interface dw {
boolean a(String str, boolean z, long j, long j2, Map map, boolean z2);
}
|
package me.euler.problem001;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author elric.wang
*/
public class MultiplesOf3And5Test {
private Map<Integer, Integer> inputOutputMap;
@Before
public void init() {
inputOutputMap = new HashMap<Integer, Integer>();
inputOutputMap.put(4, 3);
inputOutputMap.put(5, 3);
inputOutputMap.put(6, 8);
inputOutputMap.put(10, 23);
inputOutputMap.put(15, 23 + 10 + 12);
inputOutputMap.put(16, 23 + 10 + 12 + 15);
}
@Test
public void shouldCalculateTheSumOfMultiples() {
for (int input : inputOutputMap.keySet()) {
int sumOfMultiples = calMultiples(input);
int expectedOutput = inputOutputMap.get(input);
assertEquals(expectedOutput, sumOfMultiples);
}
}
private int calMultiples(int input) {
MultiplesOf3And5 multiplesOf3And5 = new MultiplesOf3And5(input);
return multiplesOf3And5.calSumOfMultiples();
}
}
|
package com.kimkha.readability;
/**
*
*/
public class PageLinkInfo {
private double score;
private String linkText;
private String href;
public PageLinkInfo(double score, String linkText, String href) {
this.score = score;
this.linkText = linkText;
this.href = href;
}
public void setScore(double score) {
this.score = score;
}
public void incrementScore(double incr) {
score = score + incr;
}
public void setLinkText(String linkText) {
this.linkText = linkText;
}
public double getScore() {
return score;
}
public String getLinkText() {
return linkText;
}
public String getHref() {
return href;
}
@Override
public String toString() {
return "PageLinkInfo [score=" + score + ", linkText=" + linkText + ", href=" + href + "]";
}
}
|
package ibd.service;
import ibd.persistence.entity.Category;
import ibd.persistence.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CategoryService {
@Autowired
private CategoryRepository categoryRepository;
public List<Category> findAll(){
return categoryRepository.findAll();
}
public void save(Category category) {
categoryRepository.save(category);
}
public void remove(Long id) {
categoryRepository.delete(id);
}
public Category findOne(Long id) {
return categoryRepository.findOne(id);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.strategies;
import de.hybris.platform.commerceservices.enums.QuoteAction;
import de.hybris.platform.core.enums.QuoteState;
import de.hybris.platform.core.model.user.UserModel;
import java.util.Optional;
import java.util.Set;
/**
* Strategy to help select quote states
*/
public interface QuoteStateSelectionStrategy
{
/**
* Provides the list of quote states based on provided action.
*
* @param action
* quote action that is being performed
* @param userModel
* user used to determine the allowed states
* @return Set of quote states associated with the action. Empty set will be returned if none of the states is
* allowed.
* @throws IllegalArgumentException
* if any of the parameters is null
*/
Set<QuoteState> getAllowedStatesForAction(QuoteAction action, UserModel userModel);
/**
* Provides the list of actions based on the given state.
*
* @param state
* quote state that can allow one action
* @param userModel
* user used to determine the allowed actions
* @return Set of actions allowed by this state. Empty set will be returned if none of the actions is allowed.
* @throws IllegalArgumentException
* if any of the parameters is null
*/
Set<QuoteAction> getAllowedActionsForState(QuoteState state, UserModel userModel);
/**
* Provides a quote state that the quote should be in for the corresponding action.
*
* @param action
* quote action that is being performed
* @param userModel
* user used to determine the transition state
* @return quote state
* @throws IllegalArgumentException
* if any of the parameters is null
*/
Optional<QuoteState> getTransitionStateForAction(QuoteAction action, UserModel userModel);
}
|
package com.forsrc.filter;
import com.forsrc.utils.WebUtils;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* The type My character encoding filter.
*/
public class MyCharacterEncodingFilter extends CharacterEncodingFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
WebUtils.setContentType(request, response);
super.doFilterInternal(request, response, filterChain);
}
}
|
package ru.bm.eetp.exception;
import ru.bm.eetp.dto.RequestResult;
public class SimpleError extends RuntimeException {
RequestResult requestResult;
public SimpleError(RequestResult requestResult) {
super(requestResult.getresultBody());
this.requestResult = requestResult;
}
public RequestResult getRequestResult() {
return requestResult;
}
}
|
package jp.naist.se.codehash.sha1;
import java.nio.charset.StandardCharsets;
import jp.naist.se.codehash.TokenReader;
public class ByteArrayNgramReader {
private int ngramCount;
private TokenReader reader;
private byte[][] tokens;
public ByteArrayNgramReader(int N, TokenReader reader) {
this.tokens = new byte[N][];
this.reader = reader;
}
/**
* Proceed to the next n-gram.
* @return true if the next n-gram is available.
*/
public boolean next() {
boolean hasElement = false;
// Shift tokens
for (int i=0; i<tokens.length-1; ++i) {
tokens[i] = tokens[i+1];
if (tokens[i] != null) hasElement = true;
}
// Read a next token
if (reader.next()) {
String t = reader.getText();
tokens[tokens.length-1] = (t != null) ? t.getBytes(StandardCharsets.UTF_8): null;
hasElement = true;
} else {
tokens[tokens.length-1] = null;
}
if (hasElement) ngramCount++;
return hasElement;
}
/**
* @param i specifies an index (0 <= i < N).
* @return the content of i-th token. It may be null if the token is unavailable (at the begin/end of a file).
*/
public byte[] getToken(int i) {
return tokens[i];
}
/**
* @return The number of n-grams returned by the reader.
*/
public int getNgramCount() {
return ngramCount;
}
}
|
package com.pine.template.base.architecture.mvc.activity;
import com.pine.template.base.ui.BaseNoActionBarActivity;
public abstract class BaseMvcFullScreenStatusBarActivity extends BaseNoActionBarActivity {
}
|
package com.kitware.doc.vo;
public class DocVO {
private String doc_num;
private int doc_kind;
private String emp_num;
private String doc_state;
private String doc_title;
private String doc_content;
private String start_date;
private String rcv_dept;
private String coper_dept;
private String refer;
public DocVO(String doc_num, int doc_kind, String emp_num, String doc_state, String doc_title, String doc_content,
String start_date, String rcv_dept, String coper_dept, String refer) {
super();
this.doc_num = doc_num;
this.doc_kind = doc_kind;
this.emp_num = emp_num;
this.doc_state = doc_state;
this.doc_title = doc_title;
this.doc_content = doc_content;
this.start_date = start_date;
this.rcv_dept = rcv_dept;
this.coper_dept = coper_dept;
this.refer = refer;
}
public DocVO(String doc_num, String emp_num, String doc_state, String doc_title, String doc_content) {
super();
this.doc_num = doc_num;
this.emp_num = emp_num;
this.doc_state = doc_state;
this.doc_title = doc_title;
this.doc_content = doc_content;
}
public String getDoc_num() {
return doc_num;
}
public void setDoc_num(String doc_num) {
this.doc_num = doc_num;
}
public int getDoc_kind() {
return doc_kind;
}
public void setDoc_kind(int doc_kind) {
this.doc_kind = doc_kind;
}
public String getEmp_num() {
return emp_num;
}
public void setEmp_num(String emp_num) {
this.emp_num = emp_num;
}
public String getDoc_state() {
return doc_state;
}
public void setDoc_state(String doc_state) {
this.doc_state = doc_state;
}
public String getDoc_title() {
return doc_title;
}
public void setDoc_title(String doc_title) {
this.doc_title = doc_title;
}
public String getDoc_content() {
return doc_content;
}
public void setDoc_content(String doc_content) {
this.doc_content = doc_content;
}
public String getStart_date() {
return start_date;
}
public void setStart_date(String start_date) {
this.start_date = start_date;
}
public String getRcv_dept() {
return rcv_dept;
}
public void setRcv_dept(String rcv_dept) {
this.rcv_dept = rcv_dept;
}
public String getCoper_dept() {
return coper_dept;
}
public void setCoper_dept(String coper_dept) {
this.coper_dept = coper_dept;
}
public String getRefer() {
return refer;
}
public void setRefer(String refer) {
this.refer = refer;
}
} |
/*
* JBoss, Home of Professional Open Source
* Copyright 2008-13, Red Hat Middleware LLC, and others contributors as indicated
* by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.overlord.rtgov.samples.sla;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.overlord.rtgov.analytics.service.ResponseTime;
import org.overlord.rtgov.analytics.situation.Situation;
import org.overlord.rtgov.epn.EventList;
import org.overlord.rtgov.epn.Network;
import org.overlord.rtgov.epn.NotificationListener;
import org.overlord.rtgov.epn.embedded.EmbeddedEPNManager;
import org.overlord.rtgov.epn.util.NetworkUtil;
public class SLAEPNTest {
private static final EmbeddedEPNManager EPNM=new EmbeddedEPNManager();
private static final TestNotificationListener LISTENER=new TestNotificationListener();;
@BeforeClass
public static void setup() {
// Load network
Network network=null;
try {
java.io.InputStream is=ClassLoader.getSystemResourceAsStream("epn.json");
byte[] b=new byte[is.available()];
is.read(b);
is.close();
network = NetworkUtil.deserialize(b);
EPNM.register(network);
} catch (Exception e) {
fail("Failed to register network: "+e);
}
EPNM.addNotificationListener("Situations", LISTENER);
}
@Before
public void initTest() {
LISTENER.clear();
}
@Test
public void testSituationNone() {
java.util.List<java.io.Serializable> events=
new java.util.ArrayList<java.io.Serializable>();
ResponseTime rt=new ResponseTime();
rt.setServiceType("TestServiceType");
rt.setOperation("TestOperation");
rt.setAverage(150);
events.add(rt);
try {
EPNM.publish("ServiceResponseTimes", events);
synchronized (this) {
wait(1000);
}
} catch (Exception e) {
fail("Failed to publish events: "+e);
}
if (LISTENER.getEvents().size() > 0) {
fail("Expecting 0 situations: "+LISTENER.getEvents().size());
}
}
@Test
public void testSituationSeverityLow() {
java.util.List<java.io.Serializable> events=
new java.util.ArrayList<java.io.Serializable>();
ResponseTime rt=new ResponseTime();
rt.setServiceType("TestServiceType");
rt.setOperation("TestOperation");
rt.setAverage(250);
events.add(rt);
try {
EPNM.publish("ServiceResponseTimes", events);
synchronized (this) {
wait(1000);
}
} catch (Exception e) {
fail("Failed to publish events: "+e);
}
if (LISTENER.getEvents().size() != 1) {
fail("Expecting 1 situation: "+LISTENER.getEvents().size());
}
Situation sit=(Situation)LISTENER.getEvents().get(0);
if (sit.getSeverity() != Situation.Severity.Low) {
fail("Severity wasn't low: "+sit.getSeverity());
}
}
@Test
public void testSituationSeverityHigh() {
java.util.List<java.io.Serializable> events=
new java.util.ArrayList<java.io.Serializable>();
ResponseTime rt=new ResponseTime();
rt.setServiceType("TestServiceType");
rt.setOperation("TestOperation");
rt.setAverage(350);
events.add(rt);
try {
EPNM.publish("ServiceResponseTimes", events);
synchronized (this) {
wait(1000);
}
} catch (Exception e) {
fail("Failed to publish events: "+e);
}
if (LISTENER.getEvents().size() != 1) {
fail("Expecting 1 situation: "+LISTENER.getEvents().size());
}
Situation sit=(Situation)LISTENER.getEvents().get(0);
if (sit.getSeverity() != Situation.Severity.High) {
fail("Severity wasn't high: "+sit.getSeverity());
}
}
public static class TestNotificationListener implements NotificationListener {
private java.util.List<Object> _events=new java.util.ArrayList<Object>();
@Override
public void notify(String subject, EventList events) {
for (Object obj : events) {
_events.add(obj);
}
}
public void clear() {
_events.clear();
}
public java.util.List<Object> getEvents() {
return (_events);
}
}
}
|
package com.ojas.employee.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ojas.employee.model.Employee;
import com.ojas.employee.repository.EmployeeRepository;
import com.ojas.employee.response.EmployeeResponse;
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
EmployeeResponse employeeResponse = null;
@Override
public EmployeeResponse saveorupdateEmployee(Employee employee) {
EmployeeResponse employeeResponse = null;
if (employee == null) {
employeeResponse = new EmployeeResponse();
employeeResponse.setMessage("Employee not saved Successfully");
employeeResponse.setStatusCode("422");
employeeResponse.setData(null);
} else {
employeeResponse = new EmployeeResponse();
Employee save = employeeRepository.save(employee);
employeeResponse.setStatusCode("200");
employeeResponse.setMessage("Employee saved successfully");
employeeResponse.setData(save);
}
return employeeResponse;
}
@Override
public EmployeeResponse getEmployee(Integer id) {
employeeResponse = new EmployeeResponse();
Optional<Employee> findById = employeeRepository.findById(id);
if (findById.isPresent()) {
employeeResponse.setStatusCode("200");
employeeResponse.setMessage("Employee Record fetched successfully!!");
employeeResponse.setData(findById);
} else {
employeeResponse.setStatusCode("422");
employeeResponse.setMessage("Employee is not present with id :: " + id + " !!!");
employeeResponse.setData(null);
}
return employeeResponse;
}
@Override
public EmployeeResponse deleteEmployee(Integer id) {
employeeResponse = new EmployeeResponse();
Optional<Employee> findById = employeeRepository.findById(id);
if (findById.isPresent()) {
employeeRepository.delete(findById.get());
employeeResponse.setStatusCode("200");
employeeResponse.setMessage("Employee Record deleted successfully!!");
employeeResponse.setData(findById);
} else {
employeeResponse.setStatusCode("422");
employeeResponse.setMessage("Employee is not present with id :: " + id + " !!!");
employeeResponse.setData(null);
}
return employeeResponse;
}
@Override
public EmployeeResponse getAllEmployee() {
employeeResponse = new EmployeeResponse();
List<Employee> findAll = employeeRepository.findAll();
if (findAll != null) {
employeeResponse.setStatusCode("200");
employeeResponse.setMessage("Employee Records fetched successfully!!");
employeeResponse.setData(findAll);
} else {
employeeResponse.setStatusCode("422");
employeeResponse.setMessage("No records found");
employeeResponse.setData(null);
}
return employeeResponse;
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_1005_ACM_Craft {
private static int T,N,K,W;
//val: 건물 시간, ed: 진입차수, ans: 가중치
private static int[] val,ed,ans;
private static List<Integer>[] adlist;
private static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
T = Integer.parseInt(br.readLine());
for (int t = 0; t < T; t++) {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
val = new int[N];
for (int i = 0; i < N; i++) {
val[i] = Integer.parseInt(st.nextToken());
}
adlist = new ArrayList[N];
for (int i = 0; i < N; i++) {
adlist[i] = new ArrayList<>();
}
ed = new int[N];
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken())-1;
int y = Integer.parseInt(st.nextToken())-1;
adlist[x].add(y);
ed[y]++;
}
W = Integer.parseInt(br.readLine())-1;
// 정답은 우선 건물 짓는 시간을 초기화(해당점이 도착점일수 있기 때문에)
ans = new int[N];
for (int i = 0; i < N; i++) {
ans[i] = val[i];
}
// 위상 정렬
topologySort();
sb.append(ans[W] +"\n");
}
System.out.println(sb);
}
private static void topologySort() {
Queue<Integer> queue = new LinkedList<>();
// 주의점: 진입차수가 0인것은 여러개일수 있다(즉, 시작점이 여러개..)
for (int i = 0; i < ed.length; i++) {
if(ed[i] ==0) queue.offer(i);
}
while(!queue.isEmpty()) {
int p = queue.poll();
for (int i = 0; i < adlist[p].size(); i++) {
int c = adlist[p].get(i);
// 지난 가중치와 현재 건물짓는 시간 합이 가장 큰값이 현재 가중치가 된다
if(ans[c] < val[c] + ans[p]) {
ans[c] = val[c] + ans[p];
}
// 진입차수를 낮추고 만약 0이되면 큐에 합류
ed[c]--;
if(ed[c] == 0) {
// 해당점이 구하는 값이면 미리 끝내자
if(c == W) return;
queue.add(c);
}
}
}
}
}
|
class Solution {
class TrieNode {
char c;
int index;
HashMap<Character, TrieNode> children = new HashMap<>();
TrieNode(char c){
this.c = c;
}
}
class Trie {
String[] words;
TrieNode root;
Trie(){
root = new TrieNode('0');
}
void insert(String s, int index){
TrieNode curr = root;
for(char c: s.toCharArray()){
curr.children.putIfAbsent(c, new TrieNode(c));
curr = curr.children.get(c);
}
curr.index = index;
}
public String dfs(){
String ans = "";
Stack<TrieNode> st = new Stack<>();
st.push(root);
while(!st.isEmpty()){
TrieNode curr = st.pop();
if(curr.index > 0 || curr == root){
if(curr != root){
String word = words[curr.index - 1];
if(word.length() > ans.length() ||
word.length() == ans.length() && word.compareTo(ans) < 0){
ans = word;
}
}
for(TrieNode n: curr.children.values()){
st.push(n);
}
}
}
return ans;
}
}
public String longestWord(String[] words) {
Trie trie = new Trie();
int index = 0;
for(String word: words){
trie.insert(word, ++index);
}
trie.words = words;
return trie.dfs();
}
}
|
package com.solomon.controller;
import com.solomon.common.Constant;
import com.solomon.config.RabbitMqConfig;
import com.solomon.domain.ArticleForPost;
import com.solomon.domain.Keyword;
import com.solomon.repository.ArticleForPostRepo;
import com.solomon.vo.KeywordForm;
import com.solomon.domain.PageEntity;
import com.solomon.service.KeywordService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.validation.Valid;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by xuehaipeng on 2017/6/13.
*/
@RestController
@RequestMapping("/kw")
public class KeywordController {
private static ThreadLocal<Integer> count = ThreadLocal.withInitial(() -> 1);
@Autowired
private KeywordService keywordService;
@Autowired
private RestTemplate restTemplate;
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private ArticleForPostRepo articleForPostRepo;
@ApiOperation(value = "二级关键词采集发送接口", notes = "插入指定数量的关键词")
@ApiImplicitParam(name = "total", value = "关键词总数", required = true, dataType = "integer")
@GetMapping("/insertSecondaryKw")
public void insertKeywords(int total) {
final int totalPage = total/100 + 2;
for (int i = 1; i < totalPage; i++) {
Pageable pageable = new PageRequest(i, Constant.PAGE_SIZE_DB_QUERY, Constant.DB_ASC_SORT);
List<String> keywords = keywordService.getKeywordList(pageable);
keywords.forEach(kw -> {
List<Keyword> keywordList = keywordService.findSecondaryKeywords(kw);
keywordService.insertSecondaryKeywords(keywordList);
});
}
}
@ApiOperation(value = "二级关键词采集发送接口", notes = "")
@ApiImplicitParams({
@ApiImplicitParam(name = "pageSize", value = "每页数量", required = true, dataType = "integer"),
@ApiImplicitParam(name = "startPage", value = "起始页码", required = true, dataType = "integer")
})
@GetMapping("/secondaryKeyword")
public void secondaryKw(@RequestParam int pageSize, @RequestParam int startPage) {
PageEntity<LinkedHashMap> keywordPageEntity = this.restTemplate.getForObject(Constant.KEYWORD_QUERY_URL.replace("{1}", String.valueOf(pageSize))
.replace("{2}", String.valueOf(startPage)), PageEntity.class);
List<LinkedHashMap> keywords = keywordPageEntity.getDatas();
List<String> keywordList = keywords.stream().map(kw -> (String)kw.get("keyword")).collect(Collectors.toList());
keywordList.stream().forEach(kw -> {
restTemplate.postForObject(Constant.SECONDARY_KW_INSERT_URL, kw, String.class);
// rabbitTemplate.convertAndSend(RabbitMqConfig.queueName, "KW: " + kw);
});
}
@ApiOperation(value = "二级关键词采集发送接口", notes = "根据Form采集发送二级关键词")
@ApiImplicitParam(name = "keywordForm", value = "KeywordForm", required = true, dataType = "KeywordForm")
@PostMapping("/secondaryKeyword")
public String secondaryKwPost(@Valid KeywordForm keywordForm) {
PageEntity<LinkedHashMap> keywordPageEntity = this.restTemplate.getForObject(Constant.KEYWORD_QUERY_URL.replace("{1}", "20")
.replace("{2}", String.valueOf(keywordForm.getStartPage())), PageEntity.class);
List<LinkedHashMap> keywords = keywordPageEntity.getDatas();
List<String> keywordList = keywords.stream().map(kw -> (String)kw.get("keyword")).collect(Collectors.toList());
int count = 0;
keywordList.stream().skip(keywordForm.getPageOffset()).forEach(kw -> {
// restTemplate.postForObject(INSERT_URL, kw, String.class);
try {
Thread.sleep(400L);
} catch (InterruptedException e) {
e.printStackTrace();
}
rabbitTemplate.convertAndSend(RabbitMqConfig.queueName, "KW: " + kw);
});
return "redirect:/";
}
}
|
package org.csus.csc131;
import java.util.concurrent.ThreadLocalRandom;
import java.lang.String;
/**
* A class set device
* Use userID to contact server and add, check or set
* @author Hung Ming, Liang
* @version 26 April 2019
*/
public class device{
@SuppressWarnings("unused")
private int userID;
private server ser;
private double[] coordinate = new double[2];
public device()
{
ser = server.getInstance();
}
/**
* Initializes userID and server
* @param id is userID pass in
*/
public device(int id){
userID=id;
ser=new server();
}
/**
* Initializes userID and set server
* @param id is userID pass in
* @param se is server object pass in
*/
public device(int id,server se){
ser=se;
userID=id;
}
/**
* sent tagID and userID to server to add TAG
* @param tagID is tagID pass in
*/
public void addTag(int userID, int tagID){
server.addTag(userID,tagID);
}
/**
* sent userID to server to check TAG status
*/
public String checkStatus(int userID, int tagID){
return ser.checkTagStatus(tagID);
}
/**
* sent userID to server to set TAG lost
*/
public void setLost(int tagID){
ser.setLost(tagID);
}
/**
* generate two random double numbers
* store them in a double array
* return the array
*/
public double[] coordinateGenerator() {
coordinate[0] = ThreadLocalRandom.current().nextDouble(-85.0, 86.0);
coordinate[1] = ThreadLocalRandom.current().nextDouble(-180.0, 181.0);
return coordinate;
}
/**
* tag.getTagID() from user class
* send GPS coordinate and tagID to the server to update tag found
*/
public void tagFound(int tagID) {
ser.tagFound(tagID, coordinateGenerator());
}
//Sends user id to the server to determine if the user exists
public boolean logIn(int UID)
{
if(ser.userExists(UID) == true)
return true;
else
return false;
}
//sends user id to the server to register user in the database
public void createUser(int uid)
{
ser.addUser(uid);
}
}
|
package com.qimou.sb.web.entity;
import java.io.Serializable;
public class CustInventMan implements Serializable{
private static final long serialVersionUID = 1L;
private String customerID = null ;//客户ID
private String inventCountry = null ;//发明人所属国家
private String inventID = null ;//发明人PK
private String inventIDCode = null ;//发明人证件号
private String inventName = null ;//发明人名称
public String getCustomerID() {
return customerID;
}
public void setCustomerID(String customerID) {
this.customerID = customerID;
}
public String getInventCountry() {
return inventCountry;
}
public void setInventCountry(String inventCountry) {
this.inventCountry = inventCountry;
}
public String getInventID() {
return inventID;
}
public void setInventID(String inventID) {
this.inventID = inventID;
}
public String getInventIDCode() {
return inventIDCode;
}
public void setInventIDCode(String inventIDCode) {
this.inventIDCode = inventIDCode;
}
public String getInventName() {
return inventName;
}
public void setInventName(String inventName) {
this.inventName = inventName;
}
}
|
package com.company;
import java.util.ArrayList;
// Персонажи
public class Character {
String name;
int hp;
int mp;
int bank = 100; // Денег в кошельке
String state;
void about(){ // О персонаже
System.out.println(name + " (" + hp + " HP, " + mp + " MP)");
}
public int getBank(){ // Сколько денег в кошельке
return bank;
}
void useAbility(Abilities ability, Character target){ // Использовать умение или бутылёк
ability.result();
System.out.println(" -> " + target.name);
int hpPos = ability.getPosHpEffect();
int hpNeg = ability.getNegHpEffect();
int mpPos = ability.getPosMpEffect();
int mpNeg = ability.getNegMpEffect();
if (this.mp >= mpPos){ // Если есть мана на умение, то атакуем
target.hp += hpPos;
target.mp += mpPos;
if (target.mp < 0){
target.mp = 0;
}
this.hp += hpNeg;
this.mp += mpNeg;
ifIsDead(this, target); // Проверяем, убили ли
ability.count -= 1; // Для лимитированных умений и бутыльков
if (ability.count == 0) {
invItems.remove(ability); // Кончился - убрали
}
}
else{
System.out.println("Not enough mana"); // Если нет маны, то и атаковать не можем
}
}
ArrayList<Abilities> invItems = new ArrayList<>(); // Инвентарь
void showInventory(){ // Показать, что есть в инвентаре
for (Abilities invItem : invItems){
System.out.printf("[%d] This is %s:\n %2dHP, %2dMP to target\n %2dHP, %2dMP to executor\n",
invItems.indexOf(invItem)+1, invItem.name, invItem.hpPosEffect,
invItem.mpPosEffect, invItem.hpNegEffect, invItem.mpNegEffect);
}
}
void ifIsDead(Character character, Character target){ // Проверка жизней оппонента
if (target.hp <= 0){
Menu menu = new Menu();
menu.myMenu(target); // Написали победный текст
System.exit(0); // Закрыли программу
}
}
}
|
package com.cthulhu.web_service;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.security.PrivateKey;
import java.security.PublicKey;
public class EncrypterTests {
@Test
void testEncryptionMethod() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = "Hello world";
String encryptedMessage = Encrypter.encrypt(message, pk);
assertTrue(encryptedMessage != null);
}
@Test
void testEncryptionMethodWithNullMessage_ShouldBeNull() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = null;
String encryptedMessage = Encrypter.encrypt(message, pk);
assertEquals(null, encryptedMessage);
}
@Test
void testEncryptionMethodWithWrongKey_ShouldBeNull() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resourcs\\stic\\puc_key_Django.der");
String message = "Hello world";
String encryptedMessage = Encrypter.encrypt(message, pk);
assertEquals(null, encryptedMessage);
}
@Test
void testEncryptionMethodWithLongString_ShouldBeNull() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = "Helloworldfezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
String encryptedMessage = Encrypter.encrypt(message, pk);
assertEquals(null, encryptedMessage);
}
@Test
void testDecryptionMethod() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resources\\static\\private_key_Spring.der");
String message = "C5g2los3ZYTdrtTyybPBQpaeevoo0sm5Q8NnDTE+NKO0T9sHSsQBEr5nMC4zmEMlob/+CNpqtVuxC/UBJ6d6gRlNsUJlXd2IGUH+VF9INBjA1IeGxXaq47zdRD50YXsIWXtY7KQxcyijK4i9a5aj2B8Dm1hZ+qizeY9pET4MRJjtiXHw0dOVcZBlGEp4eaMRndCbks6UxuwViOm2rtmPtOBkLyObzjZLnHmVHzSHpd8o8Mh+7gdNot9DRsi/sJWdAufMt2uD3HnuDUCyzVDzJsxZNze+EtJZn0v6lZg8ASoMPHQz/MyE9caeloWOrDe422iny73ccec0mTWFcCx+OA==";
String decryptedMessage = Encrypter.decrypt(message, pk);
assertTrue(decryptedMessage != null);
}
@Test
void testDecryptionMethodWithNullMessage_ShouldBeNull() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resources\\static\\private_key_Spring.der");
String message = null;
String decryptedMessage = Encrypter.decrypt(message, pk);
assertEquals(null, decryptedMessage);
}
@Test
void testDecryptionMethodWithWrongKey_ShouldBeNull() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resourcs\\stic\\puc_key_Django.der");
String message = "Hello world";
String decryptedMessage = Encrypter.decrypt(message, pk);
assertEquals(null, decryptedMessage);
}
@Test
void testDecryptionMethodWithLongString_ShouldBeNull() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resources\\static\\private_key_Spring.der");
String message = "Helloworldfezzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
String decryptedMessage = Encrypter.decrypt(message, pk);
assertEquals(null, decryptedMessage);
}
@Test
void testSignatureMethod() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resources\\static\\private_key_Spring.der");
String message = "Hello world";
String signature = Encrypter.sign(message, pk);
assertTrue(signature != null);
}
@Test
void testSignatureMethodWithNullMessage_ShouldBeNull() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resources\\static\\private_key_Spring.der");
String message = null;
String signature = Encrypter.sign(message, pk);
assertEquals(null, signature);
}
@Test
void testSignatureMethodWithWrongKey_ShouldBeNull() {
PrivateKey pk = KeyLoader.getPrivateKey("src\\main\\resourcs\\stic\\puc_key_Django.der");
String message = "Hello world";
String signature = Encrypter.sign(message, pk);
assertEquals(null, signature);
}
@Test
void testVerificationMethod() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = "hShrgb0eto5d3oIYi0bMuBWAhKKe2U35gi49vUhx2o74castyvk7jcjVg6SL2KMuUrlhOiqAeazqTkLWsx2pTeLaz/UcMWwiC6yIGAThbb+Rg1+BnHm0aHQFq1OCUjntd1b/rwWa0JxyT0TdukAFNwG73tLCiJtOv7zmcRtyz59QzvBXz8uJdcvkT9dQj8gZj99sFJuASKBQ2YY1+n4iC2PuYfmxFuO0RLYBLlaoFF/4xAB1eYdB/gQ9ICUWgdJ0WS3Px28uNfl014T+t/WWp92Egs3lgDE4F4NhOxjYWodFdp04J0r0k4vl9fsPl4ssKp0et7GGdkusfjwL3whO1g==";
String signature = "Ft4hq1ub86WMZFcB/+SY4RDst2TtU2rwDEs8HjIZWmnILy4mPo4Aou6+P83maIuwXMLl3+unGvYALFA6mn/rVC27PePNr7+G9smHKpHB9OlAXeZ2V0FEiq2JMGCCyTQvYNy5H6wc46grGJ3wctVsDisS+yYEZBAXFjHpy9fFh3fBRpLM3OD4JRvHpIO27rJjGnLxzyYQAiPso3kGGBKXDyb3RzfTsUOYe8N3rt8u3VSqCbvpLN31JNaepmLQ2YEjpYan6VBpbK64a6pIWMLXgw1WpUqWngY955EkEebYqIWTp4FEO4aQUWISrbh74rlfzMWpfRSjWMjbqQ52sKBbnQ==";
boolean isVerified = Encrypter.verify(message, signature, pk);
assertTrue(isVerified);
}
@Test
void testVerificationMethodWithNullMessage_ShouldBeFalse() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = null;
String signature = "Ft4hq1ub86WMZFcB/+SY4RDst2TtU2rwDEs8HjIZWmnILy4mPo4Aou6+P83maIuwXMLl3+unGvYALFA6mn/rVC27PePNr7+G9smHKpHB9OlAXeZ2V0FEiq2JMGCCyTQvYNy5H6wc46grGJ3wctVsDisS+yYEZBAXFjHpy9fFh3fBRpLM3OD4JRvHpIO27rJjGnLxzyYQAiPso3kGGBKXDyb3RzfTsUOYe8N3rt8u3VSqCbvpLN31JNaepmLQ2YEjpYan6VBpbK64a6pIWMLXgw1WpUqWngY955EkEebYqIWTp4FEO4aQUWISrbh74rlfzMWpfRSjWMjbqQ52sKBbnQ==";
boolean isVerified = Encrypter.verify(message, signature, pk);
assertFalse(isVerified);
}
@Test
void testVerificationMethodWithNullSignature_ShouldBeFalse() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = "hShrgb0eto5d3oIYi0bMuBWAhKKe2U35gi49vUhx2o74castyvk7jcjVg6SL2KMuUrlhOiqAeazqTkLWsx2pTeLaz/UcMWwiC6yIGAThbb+Rg1+BnHm0aHQFq1OCUjntd1b/rwWa0JxyT0TdukAFNwG73tLCiJtOv7zmcRtyz59QzvBXz8uJdcvkT9dQj8gZj99sFJuASKBQ2YY1+n4iC2PuYfmxFuO0RLYBLlaoFF/4xAB1eYdB/gQ9ICUWgdJ0WS3Px28uNfl014T+t/WWp92Egs3lgDE4F4NhOxjYWodFdp04J0r0k4vl9fsPl4ssKp0et7GGdkusfjwL3whO1g==";
String signature = null;
boolean isVerified = Encrypter.verify(message, signature, pk);
assertFalse(isVerified);
}
@Test
void testVerificationMethodWithWrongSignature_ShoudBeFalse() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resources\\static\\public_key_Django.der");
String message = "C5g2los3ZYTdrtTyybPBQpaeevoo0sm5Q8NnDTE+NKO0T9sHSsQBEr5nMC4zmEMlob/+CNpqtVuxC/UBJ6d6gRlNsUJlXd2IGUH+VF9INBjA1IeGxXaq47zdRD50YXsIWXtY7KQxcyijK4i9a5aj2B8Dm1hZ+qizeY9pET4MRJjtiXHw0dOVcZBlGEp4eaMRndCbks6UxuwViOm2rtmPtOBkLyObzjZLnHmVHzSHpd8o8Mh+7gdNot9DRsi/sJWdAufMt2uD3HnuDUCyzVDzJsxZNze+EtJZn0v6lZg8ASoMPHQz/MyE9caeloWOrDe422iny73ccec0mTWFcCx+OA==";
String signature = "dfsdfs";
boolean isVerified = Encrypter.verify(message, signature, pk);
assertFalse(isVerified);
}
@Test
void testVerificationMethodWithWrongKey_ShouldBeNull() {
PublicKey pk = KeyLoader.getPublicKey("src\\main\\resourcs\\stic\\puc_key_Django.der");
String message = "hShrgb0eto5d3oIYi0bMuBWAhKKe2U35gi49vUhx2o74castyvk7jcjVg6SL2KMuUrlhOiqAeazqTkLWsx2pTeLaz/UcMWwiC6yIGAThbb+Rg1+BnHm0aHQFq1OCUjntd1b/rwWa0JxyT0TdukAFNwG73tLCiJtOv7zmcRtyz59QzvBXz8uJdcvkT9dQj8gZj99sFJuASKBQ2YY1+n4iC2PuYfmxFuO0RLYBLlaoFF/4xAB1eYdB/gQ9ICUWgdJ0WS3Px28uNfl014T+t/WWp92Egs3lgDE4F4NhOxjYWodFdp04J0r0k4vl9fsPl4ssKp0et7GGdkusfjwL3whO1g==";
String signature = "Ft4hq1ub86WMZFcB/+SY4RDst2TtU2rwDEs8HjIZWmnILy4mPo4Aou6+P83maIuwXMLl3+unGvYALFA6mn/rVC27PePNr7+G9smHKpHB9OlAXeZ2V0FEiq2JMGCCyTQvYNy5H6wc46grGJ3wctVsDisS+yYEZBAXFjHpy9fFh3fBRpLM3OD4JRvHpIO27rJjGnLxzyYQAiPso3kGGBKXDyb3RzfTsUOYe8N3rt8u3VSqCbvpLN31JNaepmLQ2YEjpYan6VBpbK64a6pIWMLXgw1WpUqWngY955EkEebYqIWTp4FEO4aQUWISrbh74rlfzMWpfRSjWMjbqQ52sKBbnQ==";
boolean isVerified = Encrypter.verify(message, signature, pk);
assertFalse(isVerified);
}
}
|
package com.steven.base.app;
/**
* @user steven
* @createDate 2019/3/4 16:03
* @description 自定义
*/
public class SharePConstant {
public static final String KEY_DREAM_DATA = "dream_data";
public static final String KEY_USER_INFO_DATA = "user_info_data";
public static final String KEY_USER_ADDRESS_DATA = "user_address_data";
public static final String KEY_SIGN_IN_NOTES = "key_sign_in_notes";
/**
* 用户动态列表
*/
public static final String KEY_USER_DYNAMIC_LIST = "key_user_dynamic_list";
}
|
import javax.swing.*;
import java.awt.*;
public class Form extends JPanel {
private String thePlayedStr = "";
public Form() {}
public void fillKey(String str) {
Graphics g = this.getGraphics();
g.setColor(Color.BLACK);
if(str.equals("c#")) {
g.fillRect(100, 0, 40, 200);
}
else if(str.equals("d#")) {
g.fillRect(220, 0, 40, 200);
}
else if(str.equals("f#")) {
g.fillRect(460, 0, 40, 200);
}
else if(str.equals("g#")) {
g.fillRect(580, 0, 40, 200);
}
else if(str.equals("a#")) {
g.fillRect(700, 0, 40, 200);
}
else if(str.equals("c")) {
g.fillRect(0, 0, 120, 300);
}
else if(str.equals("d")) {
g.fillRect(120, 0, 120, 300);
}
else if(str.equals("e")) {
g.fillRect(240, 0, 120, 300);
}
else if(str.equals("f")) {
g.fillRect(360, 0, 120, 300);
}
else if(str.equals("g")) {
g.fillRect(480, 0, 120, 300);
}
else if(str.equals("a")) {
g.fillRect(600, 0, 120, 300);
}
else if(str.equals("b")) {
g.fillRect(720, 0, 120, 300);
}
try {
Thread.sleep(2000);
} catch(Exception ex) {}
}
public void writeNotes(String str) {
Graphics g = this.getGraphics();
thePlayedStr = str + " " + thePlayedStr;
if(thePlayedStr.substring(thePlayedStr.length() - 1, thePlayedStr.length()).equals(" ")) {
thePlayedStr = thePlayedStr.substring(0, thePlayedStr.length() - 1);
}
g.fillRect(0, 301, 800, 361);
g.setColor(Color.WHITE);
g.setFont(new Font("arial",Font.PLAIN,24));
g.drawChars(thePlayedStr.toUpperCase().toCharArray(), 0, thePlayedStr.toUpperCase().toCharArray().length, 0, 330);
}
public void display() {
setBackground(Color.BLACK);
ImageIcon imageIcon = new ImageIcon(this.getClass().getResource("/piano.png"));
Image image = imageIcon.getImage();
Graphics g = this.getGraphics();
g.drawImage(image, 0, 0, 800, 300, null);
}
}
|
package com.example.InventoryManagementSystem;
import java.awt.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler {
private static Connection connection = null;
public static boolean init = false;
/*public static boolean checkDrivers() {
try {
Class.forName("org.sqlite.JDBC");
DriverManager.registerDriver(new org.sqlite.JDBC());
return true;
} catch (ClassNotFoundException | SQLException exception) {
System.err.println(exception.getMessage());
return false;
}
}*/
private static Path getDatabasePath() {
return Path.of(System.getProperty("user.dir"), "AppData", "inventory.db");
}
public static void backupDatabase(File dest) {
try {
Files.copy(getDatabasePath(), dest.toPath().resolve(Path.of("inventory.db")), StandardCopyOption.REPLACE_EXISTING);
Desktop.getDesktop().open(dest);
}
catch (Exception e) {
MyLogger.logErr(String.format("Failed to backup database - %s", e.getMessage()));
}
}
public static void exportToJson(File dest) {
try {
List<Asset> items = getAllAssets();
List<String> itemList = new ArrayList<>();
for (Asset item:
items) {
String currentItem = "{"
.concat(String.format("\"tag\": \"%s\", ", item.getTag()))
.concat(String.format("\"make\": \"%s\", ", item.getManufacturerName()))
.concat(String.format("\"model\": \"%s\", ", item.getModel()))
.concat(String.format("\"partNo\": \"%s\", ", item.getPartNo()))
.concat(String.format("\"range\": \"%s\", ", item.getRange()))
.concat(String.format("\"qty\": %d, ", item.getQty()))
.concat(String.format("\"location\": \"%s\"", item.getLocation()))
.concat("}");
itemList.add(currentItem);
}
String result = "["
.concat(String.join(", ", itemList))
.concat("]");
FileWriter file = new FileWriter(new File(dest, "inventory.json"));
file.write(result);
file.flush();
file.close();
Desktop.getDesktop().open(dest);
}
catch (Exception e) {
MyLogger.logErr(String.format("Failed to export database - %s", e.getMessage()));
}
}
public static void connectDatabase(String address) {
String filePath = address + "/inventory.db";
File dir = new File(address);
if (!dir.exists()) dir.mkdirs();
File file = new File(filePath);
try {
init = file.createNewFile();
}
catch (IOException e) {
System.err.println(e.getMessage());
}
try {
connection = DriverManager.getConnection("jdbc:sqlite:" + filePath);
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
System.out.println("Connection established!");
}
public static void initDatabase () {
try {
Statement statement = connection.createStatement();
String sql = "CREATE TABLE ASSETS" +
"(TAG TEXT PRIMARY KEY," +
" MAKE TEXT," +
" MODEL TEXT," +
" PARTNO TEXT," +
" RANGEMIN INT," +
" RANGEMAX INT," +
" RANGEUNIT TEXT," +
" QTY INT," +
" LOCATION TEXT," +
" REMARK TEXT);";
statement.executeUpdate(sql);
sql = "INSERT INTO ASSETS VALUES" +
"('root','','','',0,0,'',0,'','');";
statement.executeUpdate(sql);
sql = "CREATE TABLE ACCESSORIES" +
"(PARENTTAG TEXT," +
" CHILDTAG TEXT," +
" CONSTRAINT ACCESSORIES_PK PRIMARY KEY (PARENTTAG, CHILDTAG)," +
" CONSTRAINT ACCESSORIES_FK FOREIGN KEY (PARENTTAG, CHILDTAG) REFERENCES ASSETS(TAG, TAG));";
statement.executeUpdate(sql);
sql = "CREATE TABLE USER" +
"(USERNAME TEXT PRIMARY KEY," +
" PASSWORD TEXT);";
statement.executeUpdate(sql);
statement.close();
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static void closeDatabase () {
try {
connection.close();
System.out.println("Database closed");
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static ResultSet execCommandQuery(String sql) throws SQLException {
Statement statement = connection.createStatement();
return statement.executeQuery(sql);
}
public static void execCommandUpdate(String sql) throws SQLException {
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
statement.close();
}
public static Asset getRoot() {
return getAssetWithTag("root");
}
public static void registerUser(String username, String password) {
try {
execCommandUpdate(String.format("INSERT INTO USER VALUES('%s', '%s');", username, password));
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static boolean checkUser(String username, String password) {
try {
ResultSet rs = execCommandQuery(String.format("SELECT * FROM USER WHERE USERNAME=='%s' AND PASSWORD=='%s'", username, password));
return (!rs.isClosed());
}
catch (SQLException e) {
System.err.println(e.getMessage());
return false;
}
}
public static boolean findInDatabase(String tag) {
try {
ResultSet rs = execCommandQuery(String.format("SELECT * FROM ASSETS WHERE TAG=='%s';", tag));
return (rs.next());
}
catch (SQLException e) {
System.err.println(e.getMessage());
return false;
}
}
private static Asset getAssetFromResultSet(ResultSet rs) throws SQLException {
AssetDetails details = new AssetDetails(rs.getString("MAKE"),
rs.getString("MODEL"),
rs.getString("PARTNO"),
rs.getString("RANGEUNIT"),
rs.getString("LOCATION"),
rs.getString("REMARK").replace('\"', '\''),
rs.getInt("QTY"),
rs.getInt("RANGEMIN"),
rs.getInt("RANGEMAX"));
return new Asset(rs.getString("TAG"), details);
}
public static Asset getAssetWithTag(String tag) {
Asset asset = null;
try {
ResultSet rs = execCommandQuery(String.format("SELECT * FROM ASSETS WHERE TAG=='%s';", tag));
rs.next();
asset = getAssetFromResultSet(rs);
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
return asset;
}
public static List<Asset> getChildAssets(Asset parentAsset) {
List<Asset> assets = new ArrayList<>();
try {
ResultSet rs = execCommandQuery(String.format("SELECT * FROM ACCESSORIES WHERE PARENTTAG=='%s';", parentAsset.getTag()));
while (rs.next()) {
assets.add(getAssetWithTag(rs.getString("CHILDTAG")));
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
return assets;
}
public static List<Asset> getAllAssets() {
List<Asset> assets = new ArrayList<>();
try {
ResultSet rs = execCommandQuery("SELECT * FROM ASSETS WHERE TAG!='root';");
while (rs.next()) {
assets.add(getAssetFromResultSet(rs));
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
return assets;
}
public static boolean checkRelation(String parentTag, String childTag) {
try {
ResultSet rs = execCommandQuery(String.format("SELECT * FROM ACCESSORIES WHERE PARENTTAG=='%s' AND CHILDTAG=='%s';", parentTag, childTag));
return !rs.isClosed();
}
catch (SQLException e) {
System.err.println(e.getMessage());
return false;
}
}
public static void addAccessoriesRelation(String parentTag, String childTag) {
try {
execCommandUpdate(String.format("INSERT INTO ACCESSORIES VALUES('%s', '%s');", parentTag, childTag));
}
catch (SQLException e) {
System.err.println(e.getMessage());
MyLogger.logErr(String.format("Failed to add %s as the accessory of %s - %s", childTag, parentTag, e.getMessage()));
return;
}
MyLogger.logInfo(String.format("Succeeded to add %s as the accessory of %s", childTag, parentTag));
}
public static void copyAccessoriesRelation(String copiedAssetTag, String newAssetTag) {
try {
ResultSet rs1 = execCommandQuery(String.format("SELECT * FROM ACCESSORIES WHERE PARENTTAG=='%s';", copiedAssetTag));
while (rs1.next()) {
String childTag = rs1.getString("CHILDTAG");
addAccessoriesRelation(newAssetTag, childTag);
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
}
}
public static void addAccessory(Asset asset) {
try {
execCommandUpdate(String.format("INSERT INTO ASSETS VALUES ('%s','%s','%s','%s',%d,%d,'%s',%d,'%s','%s');",
asset.getTag(),
asset.getManufacturerName(),
asset.getModel(),
asset.getPartNo(),
asset.getRangeMin(),
asset.getRangeMax(),
asset.getRangeUnit(),
asset.getQty(),
asset.getLocation(),
asset.getRemark().replace('\'', '\"')));
}
catch (SQLException e) {
System.err.println(e.getMessage());
MyLogger.logErr(String.format("Failed to add asset %s - %s", asset.getTag(), e.getMessage()));
return;
}
MyLogger.logInfo(String.format("Succeeded to add asset %s", asset.getTag()));
}
public static boolean deleteAccessory(String parentAssetTag, String childAssetTag) {
try {
execCommandUpdate(String.format("DELETE FROM ACCESSORIES WHERE PARENTTAG=='%s' AND CHILDTAG=='%s';", parentAssetTag, childAssetTag));
if (!execCommandQuery(String.format("SELECT * FROM ACCESSORIES WHERE CHILDTAG=='%s';", childAssetTag)).next()) {
//This accessory doesn't belong to any asset
try {
execCommandUpdate(String.format("DELETE FROM ASSETS WHERE TAG=='%s';", childAssetTag)); //Delete from asset table
ResultSet rs = execCommandQuery(String.format("SELECT * FROM ACCESSORIES WHERE PARENTTAG=='%s';", childAssetTag));
while (rs.next()) {
String childTag = rs.getString("CHILDTAG");
deleteAccessory(childAssetTag, childTag);
}
MyLogger.logInfo(String.format("Succeeded to delete asset %s", childAssetTag));
}
catch (SQLException e) {
System.err.println(e.getMessage());
MyLogger.logErr(String.format("Failed to delete asset %s - %s", childAssetTag, e.getMessage()));
throw e;
}
}
}
catch (SQLException e) {
System.err.println(e.getMessage());
MyLogger.logErr(String.format("Failed to delete %s as the accessory of %s - %s", childAssetTag, parentAssetTag, e.getMessage()));
return false;
}
MyLogger.logInfo(String.format("Succeeded to delete %s as the accessory of %s", childAssetTag, parentAssetTag));
return true;
}
public static boolean deleteAsset(String assetTag) {
try {
execCommandUpdate(String.format("DELETE FROM ACCESSORIES WHERE CHILDTAG=='%s';", assetTag)); //Delete from accessories list table
execCommandUpdate(String.format("DELETE FROM ASSETS WHERE TAG=='%s';", assetTag)); //Delete from asset table
ResultSet rs = execCommandQuery(String.format("SELECT * FROM ACCESSORIES WHERE PARENTTAG=='%s';", assetTag));
while (rs.next()) {
String childTag = rs.getString("CHILDTAG");
deleteAccessory(assetTag, childTag);
}
MyLogger.logInfo(String.format("Succeeded to delete asset %s completely", assetTag));
return true;
}
catch (SQLException e) {
System.err.println(e.getMessage());
MyLogger.logErr(String.format("Failed to delete asset %s completely - %s", assetTag, e.getMessage()));
return false;
}
}
public static boolean updateAsset(Asset asset) {
try {
execCommandUpdate(String.format("UPDATE ASSETS SET MAKE='%s',MODEL='%s',PARTNO='%s',RANGEMIN=%d,RANGEMAX=%d,RANGEUNIT='%s',QTY=%d,LOCATION='%s',REMARK='%s' WHERE TAG=='%s';",
asset.getManufacturerName(),
asset.getModel(),
asset.getPartNo(),
asset.getRangeMin(),
asset.getRangeMax(),
asset.getRangeUnit(),
asset.getQty(),
asset.getLocation(),
asset.getRemark().replace('\'', '\"'),
asset.getTag()));
}
catch (SQLException e) {
System.err.println(e.getMessage());
MyLogger.logErr(String.format("Failed to update asset %s - %s", asset.getTag(), e.getMessage()));
return false;
}
MyLogger.logInfo(String.format("Succeeded to update asset %s", asset.getTag()));
return true;
}
}
|
//计算圆的面积
public class Area {
public static void main(String args[]) {
double pi, r, a;
r = 0.3;// 半径
pi = 3.1416;
a = pi * r * r;// 面积
System.out.println("面积为:" + a);
}
}
|
package fr.ptut.treflerie.controller;
/**
* Created by benja on 14/12/2017.
*/
public class Configuration {
public static final String TEL_SERVEUR_DEFAUT = "+33782572437";
public static final String TEL_PIERRICK ="+33676867872";
public static final String TEL_lOGAN = "+33695169087";
public static final String TEL_BENJAMIN = "+33648651531";
public static final String SMS_SOLDE = "S?";
public static final String SMS_DERNIERE = "D?";
public static final String SMS_MOIS = "V?";
public static final double MONTANT_MAX_DEFAUT = 250.0;
public static final String NOM_DEFAUT = "Nouveau compte";
public static final double SOLDE_DEFAUT = 0.0;
public static final String MESSAGE_VIDE_DEFAUT = "0";
}
|
package hr.mealpler.client.activities;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import hr.mealpler.client.activities.R;
import hr.mealpler.client.controller.Constants;
import hr.mealpler.client.exceptions.HealthBuddyException;
import hr.mealpler.common.util.FitnessUtility;
import hr.mealpler.database.entities.Category;
import hr.mealpler.database.entities.User;
import hr.mealpler.database.entities.UserHistory;
import hr.mealpler.database.helpers.ProductServerResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;
public class ProgressActivity extends Activity {
private TableLayout progressTable;
private TextView usernameTextView;
private User user = new User();
private Long userId;
private String username, password;
private String gender;
private Date birthDate;
private List<UserHistory> historyList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
setTitle("My progress");
findViewsById();
getDataFromJSON();
getDataFromUserObject();
fillTable();
}
private void findViewsById() {
progressTable = (TableLayout) findViewById(R.id.tableLayout1);
usernameTextView = (TextView) findViewById(R.id.textView1);
}
private void getDataFromJSON() {
Bundle extras = this.getIntent().getExtras();
String userObjectJSON = extras.getString("user");
password = extras.getString("password");
Log.w("USER JSON", userObjectJSON);
JsonElement element = null;
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
element = parser.parse(userObjectJSON);
user = gson.fromJson(element, User.class);
}
private void getDataFromUserObject() {
userId = user.getId();
username = user.getUsername();
gender = user.getGender();
birthDate = user.getBirthDate();
}
private void fillTable() {
new ProgressTask(ProgressActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
private HealthBuddyException e;
public ProgressTask(Activity activity) {
context = activity;
dialog = new ProgressDialog(context);
}
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Fetching user history...");
this.dialog.show();
}
@Override
protected void onPostExecute(final String historyListJSON) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (historyListJSON == null) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG)
.show();
} else {
usernameTextView.setText(username);
JsonElement element = null;
JsonParser parser = new JsonParser();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd")
.create();
element = parser.parse(historyListJSON);
historyList = gson.fromJson(element,
new TypeToken<List<UserHistory>>() {
}.getType());
for (int i = 0; i < historyList.size(); i++) {
UserHistory userHistory = historyList.get(i);
Date historyDate = userHistory.getDate();
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd");
cal.setTime(historyDate);
int atYear = cal.get(Calendar.YEAR);
int atMonth = cal.get(Calendar.MONTH) + 1;
int atDay = cal.get(Calendar.DAY_OF_MONTH);
cal = Calendar.getInstance();
cal.setTime(birthDate);
int yearDOB = cal.get(Calendar.YEAR);
int monthDOB = cal.get(Calendar.MONTH) + 1;
int dayDOB = cal.get(Calendar.DAY_OF_MONTH);
int age = FitnessUtility.calculateAgeAtDate(yearDOB,
monthDOB, dayDOB, atYear, atMonth, atDay);
int height = userHistory.getHeight();
int weight = userHistory.getWeight();
int activityLevel = userHistory.getActivityLevel();
String goal = userHistory.getGoal();
int bmr = FitnessUtility.calculateBMR(gender, weight,
height, age);
float bmi = FitnessUtility.calculateBMI(weight, height);
int bf = FitnessUtility.calculateBF(gender, bmi, age);
int calories = FitnessUtility.calculateDailyCaloriesNeeded(
bmr, activityLevel);
String[] activityLevels = getResources().getStringArray(
R.array.activity_values);
String[] activityLevelsDB = getResources().getStringArray(
R.array.activity_values_numbers);
String activityLevelString = null;
for (int j = 0; j < activityLevelsDB.length; j++) {
if (activityLevel == Integer
.valueOf(activityLevelsDB[j]))
activityLevelString = activityLevels[j];
}
String goalString = null;
String[] weightGoals = getResources().getStringArray(R.array.weight_values);
String[] weightGoalsDB = getResources().getStringArray(R.array.weight_valuesDB);
for (int k = 0; k < weightGoalsDB.length; k++) {
if (goal.equals(weightGoalsDB[k]))
goalString = weightGoals[k];
}
String caloriesString;
if (goal.equals("loss")) {
calories = (int) Math.round(calories - calories * 0.2);
caloriesString = String.valueOf(calories);
} else if (goal.equals("gain")) {
int min = calories + 250;
int max = calories + 500;
caloriesString = String.valueOf(min) + "-"
+ String.valueOf(max);
}
else {
caloriesString = String.valueOf(calories);
}
// date, weight, activity level, goal, bmr, bmi, bf,
// calories
// Date
TableRow tr = new TableRow(context);
tr.setId(50 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView dateNameTV = new TextView(context);
dateNameTV.setId(100 + i);
dateNameTV.setBackgroundColor(Color.parseColor("#ff0000"));
dateNameTV.setText("DATE");
dateNameTV.setTypeface(null, Typeface.BOLD);
dateNameTV.setTextColor(Color.BLACK);
dateNameTV.setPadding(5, 5, 5, 5);
TableRow.LayoutParams params = new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
dateNameTV.setLayoutParams(params);
tr.addView(dateNameTV);
TextView dateValueTV = new TextView(context);
dateValueTV.setId(150 + i);
dateValueTV.setBackgroundColor(Color.parseColor("#ff0000"));
dateValueTV.setText(historyDate.toString());
dateValueTV.setTypeface(null, Typeface.BOLD);
dateValueTV.setTextColor(Color.BLACK);
dateValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
dateValueTV.setLayoutParams(params);
tr.addView(dateValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Age
tr = new TableRow(context);
tr.setId(500 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView ageNameTV = new TextView(context);
ageNameTV.setId(550 + i);
ageNameTV.setBackgroundColor(Color.parseColor("#eeeeee"));
ageNameTV.setText("Age:");
ageNameTV.setTextColor(Color.BLACK);
ageNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
ageNameTV.setLayoutParams(params);
tr.addView(ageNameTV);
TextView ageValueTV = new TextView(context);
ageValueTV.setId(600 + i);
ageValueTV.setBackgroundColor(Color.parseColor("#eeeeee"));
ageValueTV.setText(age + " years old");
ageValueTV.setTextColor(Color.BLACK);
ageValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
ageValueTV.setLayoutParams(params);
tr.addView(ageValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Weight
tr = new TableRow(context);
tr.setId(200 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView weightNameTV = new TextView(context);
weightNameTV.setId(250 + i);
weightNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
weightNameTV.setText("Weight:");
weightNameTV.setTextColor(Color.BLACK);
weightNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
weightNameTV.setLayoutParams(params);
tr.addView(weightNameTV);
TextView weightValueTV = new TextView(context);
weightValueTV.setId(300 + i);
weightValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
weightValueTV.setText(weight + " kg");
weightValueTV.setTextColor(Color.BLACK);
weightValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
weightValueTV.setLayoutParams(params);
tr.addView(weightValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Height
tr = new TableRow(context);
tr.setId(350 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView heightNameTV = new TextView(context);
heightNameTV.setId(400 + i);
heightNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
heightNameTV.setText("Height:");
heightNameTV.setTextColor(Color.BLACK);
heightNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
heightNameTV.setLayoutParams(params);
tr.addView(heightNameTV);
TextView heightValueTV = new TextView(context);
heightValueTV.setId(450 + i);
heightValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
heightValueTV.setText(height + " cm");
heightValueTV.setTextColor(Color.BLACK);
heightValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
heightValueTV.setLayoutParams(params);
tr.addView(heightValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Activity Level
tr = new TableRow(context);
tr.setId(650 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView actNameTV = new TextView(context);
actNameTV.setId(700 + i);
actNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
actNameTV.setText("Activity Level:");
actNameTV.setTextColor(Color.BLACK);
actNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
actNameTV.setLayoutParams(params);
tr.addView(actNameTV);
TextView actValueTV = new TextView(context);
actValueTV.setId(750 + i);
actValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
actValueTV.setText(activityLevelString);
actValueTV.setTextColor(Color.BLACK);
actValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
actValueTV.setLayoutParams(params);
tr.addView(actValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// goal
tr = new TableRow(context);
tr.setId(800 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView goalNameTV = new TextView(context);
goalNameTV.setId(850 + i);
goalNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
goalNameTV.setText("Goal:");
goalNameTV.setTextColor(Color.BLACK);
goalNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
goalNameTV.setLayoutParams(params);
tr.addView(goalNameTV);
TextView goalValueTV = new TextView(context);
goalValueTV.setId(900 + i);
goalValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
goalValueTV.setText(goalString);
goalValueTV.setTextColor(Color.BLACK);
goalValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
goalValueTV.setLayoutParams(params);
tr.addView(goalValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Body mass index
tr = new TableRow(context);
tr.setId(950 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView bmiNameTV = new TextView(context);
bmiNameTV.setId(1000 + i);
bmiNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
bmiNameTV.setText("Body mass index:");
bmiNameTV.setTextColor(Color.BLACK);
bmiNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
bmiNameTV.setLayoutParams(params);
tr.addView(bmiNameTV);
TextView bmiValueTV = new TextView(context);
bmiValueTV.setId(1050 + i);
bmiValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
bmiValueTV.setText(String.valueOf(bmi));
bmiValueTV.setTextColor(Color.BLACK);
bmiValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
bmiValueTV.setLayoutParams(params);
tr.addView(bmiValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Basal metabolic rate
tr = new TableRow(context);
tr.setId(1100 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView bmrNameTV = new TextView(context);
bmrNameTV.setId(1150 + i);
bmrNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
bmrNameTV.setText("Basal metabolic rate:");
bmrNameTV.setTextColor(Color.BLACK);
bmrNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
bmrNameTV.setLayoutParams(params);
tr.addView(bmrNameTV);
TextView bmrValueTV = new TextView(context);
bmrValueTV.setId(1200 + i);
bmrValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
bmrValueTV.setText(String.valueOf(bmr) + " kcal/day");
bmrValueTV.setTextColor(Color.BLACK);
bmrValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
bmrValueTV.setLayoutParams(params);
tr.addView(bmrValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Body fat
tr = new TableRow(context);
tr.setId(1250 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView bfNameTV = new TextView(context);
bfNameTV.setId(1300 + i);
bfNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
bfNameTV.setText("Body fat:");
bfNameTV.setTextColor(Color.BLACK);
bfNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
bfNameTV.setLayoutParams(params);
tr.addView(bfNameTV);
TextView bfValueTV = new TextView(context);
bfValueTV.setId(1350 + i);
bfValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
bfValueTV.setText(String.valueOf(bf) + " %");
bfValueTV.setTextColor(Color.BLACK);
bfValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
bfValueTV.setLayoutParams(params);
tr.addView(bfValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Calories
tr = new TableRow(context);
tr.setId(1400 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView calNameTV = new TextView(context);
calNameTV.setId(1450 + i);
calNameTV
.setBackgroundColor(Color.parseColor("#eeeeee"));
calNameTV.setText("Calories needed:");
calNameTV.setTextColor(Color.BLACK);
calNameTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
calNameTV.setLayoutParams(params);
tr.addView(calNameTV);
TextView calValueTV = new TextView(context);
calValueTV.setId(1500 + i);
calValueTV.setBackgroundColor(Color
.parseColor("#eeeeee"));
calValueTV.setText(caloriesString + " kcal/day");
calValueTV.setTextColor(Color.BLACK);
calValueTV.setPadding(5, 5, 5, 5);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
calValueTV.setLayoutParams(params);
tr.addView(calValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Empty row
tr = new TableRow(context);
tr.setId(5000 + i);
tr.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
TextView emptyNameTV = new TextView(context);
emptyNameTV.setId(5050 + i);
emptyNameTV.setText("");
emptyNameTV.setTextColor(Color.BLACK);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
emptyNameTV.setLayoutParams(params);
tr.addView(emptyNameTV);
TextView emptyValueTV = new TextView(context);
emptyValueTV.setId(5100 + i);
emptyValueTV.setText("");
emptyValueTV.setTextColor(Color.BLACK);
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
emptyValueTV.setLayoutParams(params);
tr.addView(emptyValueTV);
// Add the TableRow to the TableLayout
progressTable.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
}
}
protected String doInBackground(final String... args) {
String historyListJSON = null;
try {
do {
historyListJSON = Constants.controller.getUserHistory(username, password);
} while (historyListJSON == null);
} catch (HealthBuddyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.e = e;
}
return historyListJSON;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_progress, menu);
return true;
}
}
|
package com.zys52712.magictower;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class TeleportActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teleport);
}
public void jump(View view){
EditText floorNum = findViewById(R.id.floorBox);
int floor = Integer.parseInt(floorNum.getText().toString());
GameActivity.useTeleporter(floor);
finish();
}
} |
package org.slevin.dao.service;
import org.slevin.common.Ilce;
import org.slevin.dao.IlceDao;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class IlceService extends EntityService<Ilce> implements IlceDao {
}
|
package file;
import com.java8.lambda.file.FileService;
import org.junit.Test;
import java.io.IOException;
/**
* 自定义函数式接口
*/
public class FileServiceTest {
@Test
public void fileHandle() throws IOException {
FileService fileService = new FileService();
fileService.executeFile("/Users/easterfan/Desktop/java8functionalProgramming" +
"/src/test/java/file/FileServiceTest.java",
fileContent -> System.out.println(fileContent));
}
}
|
package great_class28;
/**
* Created by likz on 2023/4/20
*
* @author likz
*/
public class Problem_0014_LongestCommonPrefix {
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
char[] str0 = strs[0].toCharArray();
if(str0.equals("")){
return "";
}
int index = str0.length;
for (int i = 1; i < strs.length; i++) {
char[] str = strs[i].toCharArray();
int pos = 0;
while(pos < str.length && pos < str0.length && pos <= index && str[pos] == str0[pos]){
pos++;
}
if (pos == 0 ){
return "";
}
index = Math.min(pos, index);
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < index; i++) {
res.append(str0[i]);
}
return res.toString();
}
}
|
package com.design.pattern.listener.source;
import com.design.pattern.listener.handler.EventListener;
/**
* @author zhangbingquan
* @desc 事件源接口
* @time 2019/8/23 0:43
*/
public interface EventSource {
/**
* @author zhangbingquan
* @desc 增加监听器
* @time 2019/8/23 0:43
*/
void addListener(EventListener listener);
/**
* @author zhangbingquan
* @desc 通知监听器
* @time 2019/8/23 0:44
*/
void notifyListener();
}
|
package parser;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.util.SAXHelper;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
public class XlsxParser
{
OPCPackage xlsxPackage;
SheetContentsHandler SheetHandler;
public XlsxParser(OPCPackage pkg, SheetContentsHandler SheetHandler)
{
this.xlsxPackage = pkg;
this.SheetHandler = SheetHandler;
}
public void process() throws IOException, SAXException, OpenXML4JException
{
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
while(iter.hasNext())
{
InputStream stream = iter.next();
processSheet(styles, strings, SheetHandler, stream);
stream.close();
}
}
public void processSheet(StylesTable styles, ReadOnlySharedStringsTable strings,
SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, SAXException
{
DataFormatter formatter = new DataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try
{
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
}
catch (ParserConfigurationException e)
{
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
}
|
package edu.byu.cs.tweeter.presenter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.IOException;
import edu.byu.cs.tweeter.model.domain.Status;
import edu.byu.cs.tweeter.model.domain.User;
import edu.byu.cs.tweeter.model.service.PostService;
import edu.byu.cs.tweeter.model.service.request.PostRequest;
import edu.byu.cs.tweeter.model.service.response.PostResponse;
public class PostPresenterTest {
private PostRequest request;
private PostResponse response;
private PostService mockPostService;
private PostPresenter presenter;
@BeforeEach
public void setup() throws IOException {
User currentUser = new User("FirstName", "LastName", null);
User resultUser1 = new User("FirstName1", "LastName1",
"https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/donald_duck.png");
User resultUser2 = new User("FirstName2", "LastName2",
"https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png");
User resultUser3 = new User("FirstName3", "LastName3",
"https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png");
Status status1 = new Status("hello @James how are you? https://google.com", resultUser1, "Jan 1, 2021");
request = new PostRequest(status1);
response = new PostResponse(true, "successfully posted");
// Create a mock PostService
mockPostService = Mockito.mock(PostService.class);
Mockito.when(mockPostService.sendPostRequest(request)).thenReturn(response);
// Wrap a PostPresenter in a spy that will use the mock service.
presenter = Mockito.spy(new PostPresenter(new PostPresenter.View() {}));
Mockito.when(presenter.getPostService()).thenReturn(mockPostService);
}
@Test
public void testGetPost_returnsServiceResult() throws IOException {
Mockito.when(mockPostService.sendPostRequest(request)).thenReturn(response);
// Assert that the presenter returns the same response as the service (it doesn't do
// anything else, so there's nothing else to test).
Assertions.assertEquals(response, presenter.sendPostRequest(request));
}
@Test
public void testGetPost_serviceThrowsIOException_presenterThrowsIOException() throws IOException {
Mockito.when(mockPostService.sendPostRequest(request)).thenThrow(new IOException());
Assertions.assertThrows(IOException.class, () -> {
presenter.sendPostRequest(request);
});
}
}
|
package exercicio_104;
import java.util.Scanner;
public class Exercicio_104 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
String nome;
char sexo;
int idade;
//o que o programa faz
System.out.println("Imprime o nome de uma "
+ "mulher que tem menos que 25 anos");
//entrada de dados
System.out.print("Digite o nome: ");
nome = teclado.next();
System.out.print("Digite o sexo[M/F]: ");
sexo = teclado.next().toUpperCase().charAt(0);
System.out.print("Digite a idade: ");
idade = teclado.nextInt();
//processamento e saida
if ((sexo == 'F') && (idade < 25)) {
System.out.println(nome + " ACEITA");
} else {
System.out.println(nome + " NÃO ACEITA");
}
}
}
|
package com.tencent.mm.plugin.facedetect.e;
import com.tencent.mm.plugin.facedetect.e.a.1.1;
import com.tencent.mm.plugin.facedetect.e.a.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class a$1$1$1 implements Runnable {
final /* synthetic */ long iSH;
final /* synthetic */ 1 iSI;
a$1$1$1(1 1, long j) {
this.iSI = 1;
this.iSH = j;
}
public final void run() {
synchronized (a.a(this.iSI.iSG.iSF)) {
x.i("MicroMsg.FaceVideoRecorder", "hy: connect cost %s ms", new Object[]{Long.valueOf(bi.bI(this.iSH))});
long VG = bi.VG();
a.a(this.iSI.iSG.iSF, a.e(this.iSI.iSG.iSF).ZO());
a.g(this.iSI.iSG.iSF).setFilePath(a.f(this.iSI.iSG.iSF));
a.g(this.iSI.iSG.iSF).Hr(a.h(this.iSI.iSG.iSF));
a.g(this.iSI.iSG.iSF).bes();
a.g(this.iSI.iSG.iSF).p(a.i(this.iSI.iSG.iSF), a.j(this.iSI.iSG.iSF), this.iSI.iSG.iSD, this.iSI.iSG.iSE);
a.g(this.iSI.iSG.iSF).sQ(a.k(this.iSI.iSG.iSF));
a.g(this.iSI.iSG.iSF).a(a.l(this.iSI.iSG.iSF));
a.e(this.iSI.iSG.iSF, a.iSO);
x.i("MicroMsg.FaceVideoRecorder", "hy: init in main thread cost %d ms", new Object[]{Long.valueOf(bi.bI(VG))});
}
}
}
|
package com.ryit.service;
import java.util.List;
import com.ryit.entity.Plot;
public interface PlotService {
//添加小区信息
public String addPlot(Plot p);
//指定删除小区的信息
public String delPlot(int id);
//查询所有小区的信息
public List<Plot> selectAll();
//获取小区名称
public List<Plot> findPname(String pname);
//修改
public String updatePlot(Plot p);
}
|
package io.netty.example.time;
import java.util.Date;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class TimeServerHandler extends ChannelHandlerAdapter {
private int counter;
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
/*final ByteBuf time = ctx.alloc().buffer(4);
//int rs = (int)(System.currentTimeMillis()/1000L+2208988800L);
time.writeInt(new UnixTime().value());
final ChannelFuture f = ctx.writeAndFlush(time);
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture paramF) throws Exception {
assert f == paramF;
ctx.close();
}
});*/
ChannelFuture f = ctx.writeAndFlush(new UnixTime());
//f.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.readBytes(bytes);
String body = new String(bytes,"UTF-8")
.substring(0, bytes.length-System.getProperty("line.separator").length());
System.out.println("The time server receive order :"+body+
"; the counter is :"+(++counter));
String currentTime = "QUERY TIME ORDER".equals(body)?
new Date(System.currentTimeMillis()).toString():
"BAD ORDER";
ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
ctx.writeAndFlush(resp);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
cause.printStackTrace();
ctx.close();
}
}
|
package com.android.internal.util.fantasy;
import java.util.ArrayList;
public class QSConstants {
public static final String TILE_USER = "toggleUser";
public static final String TILE_BATTERY = "toggleBattery";
public static final String TILE_SETTINGS = "toggleSettings";
public static final String TILE_WIFI = "toggleWifi";
public static final String TILE_GPS = "toggleGPS";
public static final String TILE_BLUETOOTH = "toggleBluetooth";
public static final String TILE_BRIGHTNESS = "toggleBrightness";
public static final String TILE_RINGER = "toggleSound";
public static final String TILE_SYNC = "toggleSync";
public static final String TILE_WIFIAP = "toggleWifiAp";
public static final String TILE_SCREENTIMEOUT = "toggleScreenTimeout";
public static final String TILE_MOBILEDATA = "toggleMobileData";
public static final String TILE_LOCKSCREEN = "toggleLockScreen";
public static final String TILE_NETWORKMODE = "toggleNetworkMode";
public static final String TILE_AUTOROTATE = "toggleAutoRotate";
public static final String TILE_AIRPLANE = "toggleAirplane";
public static final String TILE_TORCH = "toggleFlashlight"; // Keep old string for compatibility
public static final String TILE_SLEEP = "toggleSleepMode";
public static final String TILE_LTE = "toggleLte";
public static final String TILE_WIMAX = "toggleWimax";
public static final String TILE_PROFILE = "toggleProfile";
public static final String TILE_PERFORMANCE_PROFILE = "togglePerformanceProfile";
public static final String TILE_NFC = "toggleNfc";
public static final String TILE_USBTETHER = "toggleUsbTether";
public static final String TILE_QUIETHOURS = "toggleQuietHours";
public static final String TILE_VOLUME = "toggleVolume";
public static final String TILE_EXPANDEDDESKTOP = "toggleExpandedDesktop";
public static final String TILE_CAMERA = "toggleCamera";
public static final String TILE_NETWORKADB = "toggleNetworkAdb";
public static final String TILE_COMPASS = "toggleCompass";
public static final String TILE_CPUFREQ = "toggleCPUFreq";
public static final String TILE_POWER = "togglePowerMenu";
public static final String TILE_HALO = "toggleHalo";
public static final String TILE_THEMES = "toggleThemes";
public static final String TILE_DELIMITER = "|";
public static ArrayList<String> TILES_DEFAULT = new ArrayList<String>();
static {
TILES_DEFAULT.add(TILE_USER);
TILES_DEFAULT.add(TILE_BRIGHTNESS);
TILES_DEFAULT.add(TILE_SETTINGS);
TILES_DEFAULT.add(TILE_WIFI);
TILES_DEFAULT.add(TILE_MOBILEDATA);
TILES_DEFAULT.add(TILE_GPS);
TILES_DEFAULT.add(TILE_TORCH);
TILES_DEFAULT.add(TILE_BATTERY);
TILES_DEFAULT.add(TILE_AIRPLANE);
TILES_DEFAULT.add(TILE_BLUETOOTH);
TILES_DEFAULT.add(TILE_AUTOROTATE);
}
}
|
package agh.queueFreeShop.controller;
import agh.queueFreeShop.exception.ForbiddenException;
import agh.queueFreeShop.exception.NotFoundException;
import agh.queueFreeShop.model.Receipt;
import agh.queueFreeShop.repository.ReceiptRepository;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Simply returns receipts.
*/
@RestController
@RequestMapping(path = "/receipts")
@ApiResponses(@ApiResponse(code = 401, message = "Unauthorized"))
public class ReceiptController {
private final ReceiptRepository receiptRepository;
ReceiptController(ReceiptRepository receiptRepository) {
this.receiptRepository = receiptRepository;
}
@GetMapping("/{id}")
@ApiOperation(value = "Get receipt by id", notes = "Receipt must be owned by user making request.")
@ApiResponses({
@ApiResponse(code = 404, message = "Receipt not found"),
@ApiResponse(code = 403, message = "Access forbidden")})
public Receipt getById(@PathVariable Long id) {
Receipt receipt = receiptRepository.getById(id);
if (receipt == null)
throw new NotFoundException("Receipt not found");
if (!receipt.getUser().getId().equals(getUserId()))
throw new ForbiddenException("Access forbidden");
return receipt;
}
@GetMapping("")
@ApiOperation(value = "Get all receipts", notes = "Returns all receipts owned by user.")
public List<Receipt> getAllByUser() {
return receiptRepository.getAllByUserId(getUserId());
}
private Long getUserId() {
UserDetails user = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return Long.parseLong(user.getUsername());
}
}
|
package zm.gov.moh.common.submodule.form.model.widgetModel;
public class DefaultCameraButtonModel extends AbstractLabelModel{
public DefaultCameraButtonModel(){
super();
}
}
|
//import java.awt.EventQueue;
//import java.awt.Graphics;
//import java.awt.event.MouseEvent;
//import java.awt.event.MouseListener;
//import javax.swing.JFrame;
//import javax.swing.JOptionPane;
public class start {
boolean rodando = true;
int fps = 60;
public static void main(String[] args) throws InterruptedException {
janela l = new janela(); // cria e instancia o objeto l da classe janela
l.rodar();// chama o rodar
}
}
|
package com.adm.tools.common.sdk.request;
import com.adm.tools.common.sdk.Client;
public class GetLabRunEntityDataRequest extends GetRequest {
public GetLabRunEntityDataRequest(Client client, String runId) {
super(client, runId);
}
@Override
protected String getSuffix() {
return String.format("procedure-runs/%s", _runId);
}
} |
/**
* Copyright 2013 Cloudera Inc.
*
* 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.kitesdk.data.hbase.impl;
import java.util.ArrayList;
import java.util.List;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.kitesdk.data.PartitionKey;
import org.kitesdk.data.hbase.filters.EntityFilter;
import org.kitesdk.data.hbase.filters.RegexEntityFilter;
import org.kitesdk.data.hbase.filters.SingleFieldEntityFilter;
/**
* An abstract class that EntityScanner implementations should extend to offer a
* builder interface. Implementations only need to implement the build method.
*
* @param <K>
* The underlying key record type
* @param <E>
* The entity type this canner scans
*/
public abstract class EntityScannerBuilder<E> {
private HTablePool tablePool;
private String tableName;
private PartitionKey startKey;
private PartitionKey stopKey;
private boolean startInclusive = true;
private boolean stopInclusive = false;
private int caching;
private EntityMapper<E> entityMapper;
private List<ScanModifier> scanModifiers = new ArrayList<ScanModifier>();
private boolean passAllFilters = true;
private List<Filter> filterList = new ArrayList<Filter>();
/**
* This is an abstract Builder object for the Entity Scanners, which will
* allow users to dynamically construct a scanner object using the Builder
* pattern. This is useful when the user doesn't have all the up front
* information to create a scanner. It's also easier to add more options later
* to the scanner, this will be the preferred method for users to create
* scanners.
*
* @param <K>
* The underlying key record type.
* @param <E>
* The entity type this scanner scans.
*/
public EntityScannerBuilder(HTablePool tablePool, String tableName,
EntityMapper<E> entityMapper) {
this.tablePool = tablePool;
this.tableName = tableName;
this.entityMapper = entityMapper;
}
/**
* Get The HBase Table Pool
*
* @return String
*/
HTablePool getTablePool() {
return tablePool;
}
/**
* Get The HBase Table Name
*
* @return String
*/
String getTableName() {
return tableName;
}
/**
* Get The Entity Mapper
*
* @return EntityMapper
*/
EntityMapper<E> getEntityMapper() {
return entityMapper;
}
/**
* Get The Start StorageKey
*
* @return StorageKey
*/
PartitionKey getStartKey() {
return startKey;
}
/**
* Set The Start StorageKey.
*
* @param startKey
* The start key for this scan
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> setStartKey(PartitionKey startKey) {
this.startKey = startKey;
return this;
}
/**
* Get The Start StorageKey
*
* @return StorageKey
*/
PartitionKey getStopKey() {
return stopKey;
}
/**
* Set The Stop StorageKey.
*
* @param stopKey
* The stop key for this scan
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> setStopKey(PartitionKey stopKey) {
this.stopKey = stopKey;
return this;
}
/**
* Returns true if the scan should include the row pointed to by the start
* key, or start right after it..
*
* @return startInclusive
*/
boolean getStartInclusive() {
return startInclusive;
}
/**
* Set the startInclusive parameter.
*
* @param startInclusive
* The startInclusive setting.
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> setStartInclusive(boolean startInclusive) {
this.startInclusive = startInclusive;
return this;
}
/**
* Returns true if the scan should include the row pointed to by the stop key,
* or stop just short of it.
*
* @return stopInclusive
*/
boolean getStopInclusive() {
return stopInclusive;
}
/**
* Set the startInclusive parameter.
*
* @param stopInclusive
* The stopInclusive setting.
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> setStopInclusive(boolean stopInclusive) {
this.stopInclusive = stopInclusive;
return this;
}
/**
* Get the scanner caching value
*
* @return the caching value
*/
int getCaching() {
return caching;
}
/**
* Set The Scanner Caching Level
*
* @param caching
* caching amount for scanner
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> setCaching(int caching) {
this.caching = caching;
return this;
}
/**
* Add an Equality Filter to the Scanner, Will Filter Results Not Equal to the
* Filter Value
*
* @param fieldName
* The name of the column you want to apply the filter on
* @param filterValue
* The value for comparison
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addEqualFilter(String fieldName,
Object filterValue) {
SingleFieldEntityFilter singleFieldEntityFilter = new SingleFieldEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, filterValue, CompareFilter.CompareOp.EQUAL);
filterList.add(singleFieldEntityFilter.getFilter());
return this;
}
/**
* Add an Inequality Filter to the Scanner, Will Filter Results Not Equal to
* the Filter Value
*
* @param fieldName
* The name of the column you want to apply the filter on
* @param filterValue
* The value for comparison
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addNotEqualFilter(String fieldName,
Object filterValue) {
SingleFieldEntityFilter singleFieldEntityFilter = new SingleFieldEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, filterValue, CompareFilter.CompareOp.NOT_EQUAL);
filterList.add(singleFieldEntityFilter.getFilter());
return this;
}
/**
* Add a Regex Equality Filter to the Scanner, Will Filter Results Not Equal
* to the Filter Value
*
* @param fieldName
* The name of the column you want to apply the filter on
* @param filterValue
* The regular expression to use for comparison
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addRegexMatchFilter(String fieldName,
String regexString) {
RegexEntityFilter regexEntityFilter = new RegexEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, regexString);
filterList.add(regexEntityFilter.getFilter());
return this;
}
/**
* Add a Regex Inequality Filter to the Scanner, Will Filter Results Not Equal
* to the Filter Value
*
* @param fieldName
* The name of the column you want to apply the filter on
* @param filterValue
* The regular expression to use for comparison
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addRegexNotMatchFilter(String fieldName,
String regexString) {
RegexEntityFilter regexEntityFilter = new RegexEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, regexString, false);
filterList.add(regexEntityFilter.getFilter());
return this;
}
/**
* Do not include rows which have no value for fieldName
*
* @param fieldName
* The field to check nullity
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addNotNullFilter(String fieldName) {
RegexEntityFilter regexEntityFilter = new RegexEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, ".+");
filterList.add(regexEntityFilter.getFilter());
return this;
}
/**
* Only include rows which have an empty value for this field
*
* @param fieldName
* The field to check nullity
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addIsNullFilter(String fieldName) {
RegexEntityFilter regexEntityFilter = new RegexEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, ".+", false);
filterList.add(regexEntityFilter.getFilter());
return this;
}
/**
* Only include rows which are missing this field, this was the only possible
* way to do it.
*
* @param fieldName
* The field which should be missing
* @return ScannerBuilder
*/
public EntityScannerBuilder<E> addIsMissingFilter(String fieldName) {
SingleFieldEntityFilter singleFieldEntityFilter = new SingleFieldEntityFilter(
entityMapper.getEntitySchema(), entityMapper.getEntitySerDe(),
fieldName, "++++NON_SHALL_PASS++++", CompareFilter.CompareOp.EQUAL);
SingleColumnValueFilter filter = (SingleColumnValueFilter) singleFieldEntityFilter
.getFilter();
filter.setFilterIfMissing(false);
filterList.add(filter);
return this;
}
/**
* Check If All Filters Must Pass
*
* @return boolean
*/
boolean getPassAllFilters() {
return passAllFilters;
}
public EntityScannerBuilder<E> setPassAllFilters(boolean passAllFilters) {
this.passAllFilters = passAllFilters;
return this;
}
/**
* Get The List Of Filters For This Scanner
*
* @return List
*/
List<Filter> getFilterList() {
return filterList;
}
/**
* Add HBase Filter To Scan Object
*
* @param filter
* EntityFilter object created by user
*/
public EntityScannerBuilder<E> addFilter(EntityFilter filter) {
filterList.add(filter.getFilter());
return this;
}
/**
* Get the ScanModifiers
*
* @return List of ScanModifiers
*/
List<ScanModifier> getScanModifiers() {
return scanModifiers;
}
/**
* Add the ScanModifier to the list of ScanModifiers.
*
* @param scanModifier
* The ScanModifier to add
*/
public EntityScannerBuilder<E> addScanModifier(ScanModifier scanModifier) {
scanModifiers.add(scanModifier);
return this;
}
/**
* Build and return a EntityScanner object using all of the information
* the user provided.
*
* @return ScannerBuilder
*/
public abstract EntityScanner<E> build();
}
|
package fundamentos;
import java.util.Scanner;
public class Class03Primitivos {
//psvm + TAB
public static void main(String[] args) {
int numero = 30;
numero = 99;
//LOS TIPOS CHAR SE IGUALAN CON COMILLA SIMPLE
char letra = 'A';
//String es una clase, no es un primitivo
//Pero es un Wrapper, con igualar a un valor
//ya se crea/instancia el objeto
String texto = "Hoy es lunes";
//boolean se establece con true/false
boolean respuesta = true;
//El compilador detecta si nos hemos pasado
//en la capacidad de la variable
byte bite = 127;
//Object es la clase BASE de Java
//Todas las clases en Java heredan de algo.
//La herencia quiere decir que un objeto no comienza
//de Zero, sino que ya tiene unos métodos y propiedades.
//La clase BASE es la clase de dónde hereda un objeto
//directamente
//Un Object puede almacenar cualquier dato
//y es un Wrapper
Object obj = "Esto es un texto";
Object obj2 = 78899;
//CONVERSION IMPLICITA
//UN DOUBLE TIENE MAS CAPACIDAD QUE UN INT
//NO NOS FIJAMOS EN EL VALOR, SINO EN LA CAPACIDAD
//DEL TIPO
double mayor;
int menor = 19;
//SI ALMACENAMOS UN TIPO MENOR EN MAYOR
//LA CONVERSION ES AUTOMATICA
mayor = menor;
//CONVERSION CASTING
//SE REALIZA ENTRE PRIMITIVOS
byte bytemenor;
int intmayor = 99;
//QUEREMOS GUARDAR UN TIPO DE MAYOR CAPACIDAD
//LA CONVERSION SIEMPRE AL TIPO DE LA IZQUIERDA
bytemenor = (byte) intmayor;
//CONVERSION STRING A PRIMITIVO
//SE UTILIZAN LOS METODOS PARSE
//POR CADA PRIMITIVO, TENEMOS UNA CLASE
//DE SU TIPO: double --> Double
// int --> Integer, boolean --> Boolean
String dato = "78";
int num;
//QUEREMOS GUARDAR EL TEXTO NUMERO EN INT
num = Integer.parseInt(dato);
double d = Double.parseDouble(dato);
//CONVERSION DE OBJETOS A STRING
String cadena;
int num1 = 99;
//PARA CONVERTIR A STRING LOS
//PRIMITIVOS SE UTILIZA EL METODO
// valueOf DE LA CLASE STRING
cadena = String.valueOf(num1);
//OTRA OPCION SON LAS CONVERSIONES
//IMPLICITAS DE PRIMITIVOS
//sout + TAB
System.out.println("Número " + num1);
//PARA UTILIZAR SCANNER...
//1) TODA LA RUTA
Scanner teclado = new Scanner(System.in);
System.out.println("Introduzca su nombre:");
//SIEMPRE DEVUELVE STRING
String nombre = teclado.nextLine();
System.out.println("Su nombre es: "
+ nombre);
}
}
|
import java.sql.*;
public class prova {
public static void main(String[] args) {
try { Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql:postgres","postgres","diegoAmico");
Statement stmt = con.createStatement();
String que="select*from persone";
String queAuto="select*from auto";
String createAuto ="CREATE TABLE auto(id bigserial not null,modello varchar(30) not null)";
String inserisci = "insert into auto (modello) values('mercedes')";
String aggiorna = "UPDATE auto SET modello ='porsche' where id=3";
stmt.executeUpdate(aggiorna);
ResultSet setCar = stmt.executeQuery(queAuto);
while(setCar.next()){
System.out.println(setCar.getString("id")+" " +setCar.getString("modello"));
}
}catch (SQLException e)
{e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} |
package com.facebook.react.devsupport;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;
import com.a;
import com.facebook.common.e.a;
import com.facebook.i.a.a;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.common.network.OkHttpCallUtil;
import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener;
import com.facebook.react.devsupport.interfaces.PackagerStatusCallback;
import com.facebook.react.devsupport.interfaces.StackFrame;
import com.facebook.react.modules.systeminfo.AndroidInfoHelpers;
import com.facebook.react.packagerconnection.FileIoHandler;
import com.facebook.react.packagerconnection.JSPackagerClient;
import com.facebook.react.packagerconnection.NotificationOnlyHandler;
import com.facebook.react.packagerconnection.ReconnectingWebSocket;
import com.facebook.react.packagerconnection.RequestOnlyHandler;
import com.facebook.react.packagerconnection.Responder;
import g.q;
import g.x;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import okhttp3.ac;
import okhttp3.ad;
import okhttp3.ae;
import okhttp3.af;
import okhttp3.e;
import okhttp3.f;
import okhttp3.j;
import okhttp3.w;
import okhttp3.y;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class DevServerHelper {
private final BundleDownloader mBundleDownloader;
public InspectorPackagerConnection.BundleStatusProvider mBundlerStatusProvider;
private final y mClient;
public InspectorPackagerConnection mInspectorPackagerConnection;
private y mOnChangePollingClient;
public boolean mOnChangePollingEnabled;
public OnServerContentChangeListener mOnServerContentChangeListener;
public final String mPackageName;
public JSPackagerClient mPackagerClient;
public final Handler mRestartOnChangePollingHandler;
public final DevInternalSettings mSettings;
public DevServerHelper(DevInternalSettings paramDevInternalSettings, String paramString, InspectorPackagerConnection.BundleStatusProvider paramBundleStatusProvider) {
this.mSettings = paramDevInternalSettings;
this.mBundlerStatusProvider = paramBundleStatusProvider;
this.mClient = (new y.a()).a(5000L, TimeUnit.MILLISECONDS).b(0L, TimeUnit.MILLISECONDS).c(0L, TimeUnit.MILLISECONDS).a();
this.mBundleDownloader = new BundleDownloader(this.mClient);
this.mRestartOnChangePollingHandler = new Handler();
this.mPackageName = paramString;
}
private String createBundleURL(String paramString, BundleType paramBundleType) {
return createBundleURL(paramString, paramBundleType, this.mSettings.getPackagerConnectionSettings().getDebugServerHost());
}
private String createBundleURL(String paramString1, BundleType paramBundleType, String paramString2) {
return a.a(Locale.US, "http://%s/%s.%s?platform=android&dev=%s&minify=%s", new Object[] { paramString2, paramString1, paramBundleType.typeID(), Boolean.valueOf(getDevMode()), Boolean.valueOf(getJSMinifyMode()) });
}
private String createLaunchJSDevtoolsCommandUrl() {
return a.a(Locale.US, "http://%s/launch-js-devtools", new Object[] { this.mSettings.getPackagerConnectionSettings().getDebugServerHost() });
}
private String createOnChangeEndpointUrl() {
return a.a(Locale.US, "http://%s/onchange", new Object[] { this.mSettings.getPackagerConnectionSettings().getDebugServerHost() });
}
private static String createOpenStackFrameURL(String paramString) {
return a.a(Locale.US, "http://%s/open-stack-frame", new Object[] { paramString });
}
private static String createPackagerStatusURL(String paramString) {
return a.a(Locale.US, "http://%s/status", new Object[] { paramString });
}
private static String createResourceURL(String paramString1, String paramString2) {
return a.a(Locale.US, "http://%s/%s", new Object[] { paramString1, paramString2 });
}
private static String createSymbolicateURL(String paramString) {
return a.a(Locale.US, "http://%s/symbolicate", new Object[] { paramString });
}
private void enqueueOnChangeEndpointLongPolling() {
ac ac = (new ac.a()).a(createOnChangeEndpointUrl()).a(this).c();
((y)a.b(this.mOnChangePollingClient)).a(ac).a(new f() {
public void onFailure(e param1e, IOException param1IOException) {
if (DevServerHelper.this.mOnChangePollingEnabled) {
a.a("ReactNative", "Error while requesting /onchange endpoint", param1IOException);
DevServerHelper.this.mRestartOnChangePollingHandler.postDelayed(new Runnable() {
public void run() {
DevServerHelper.this.handleOnChangePollingResponse(false);
}
}, 5000L);
}
}
public void onResponse(e param1e, ae param1ae) throws IOException {
boolean bool;
DevServerHelper devServerHelper = DevServerHelper.this;
if (param1ae.c == 205) {
bool = true;
} else {
bool = false;
}
devServerHelper.handleOnChangePollingResponse(bool);
}
});
}
private boolean getDevMode() {
return this.mSettings.isJSDevModeEnabled();
}
private String getHostForJSProxy() {
String str = (String)a.b(this.mSettings.getPackagerConnectionSettings().getDebugServerHost());
return (str.lastIndexOf(':') >= 0) ? str : "localhost";
}
private boolean getJSMinifyMode() {
return this.mSettings.isJSMinifyEnabled();
}
public void attachDebugger(final Context context, final String title) {
(new AsyncTask<Void, String, Boolean>() {
protected Boolean doInBackground(Void... param1VarArgs) {
return Boolean.valueOf(doSync());
}
public boolean doSync() {
try {
String str = DevServerHelper.this.getInspectorAttachUrl(title);
(new y()).a((new ac.a()).a(str).c()).b();
return true;
} catch (IOException iOException) {
a.c("ReactNative", "Failed to send attach request to Inspector", iOException);
return false;
}
}
protected void onPostExecute(Boolean param1Boolean) {
if (!param1Boolean.booleanValue()) {
String str = context.getString(1980104708);
_lancet.com_ss_android_ugc_aweme_lancet_DesignBugFixLancet_show(Toast.makeText(context, str, 1));
}
}
class null {}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])new Void[0]);
}
public void closeInspectorConnection() {
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... param1VarArgs) {
if (DevServerHelper.this.mInspectorPackagerConnection != null) {
DevServerHelper.this.mInspectorPackagerConnection.closeQuietly();
DevServerHelper.this.mInspectorPackagerConnection = null;
}
return null;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])new Void[0]);
}
public void closePackagerConnection() {
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... param1VarArgs) {
if (DevServerHelper.this.mPackagerClient != null) {
DevServerHelper.this.mPackagerClient.close();
DevServerHelper.this.mPackagerClient = null;
}
return null;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])new Void[0]);
}
public void disableDebugger() {
InspectorPackagerConnection inspectorPackagerConnection = this.mInspectorPackagerConnection;
if (inspectorPackagerConnection != null)
inspectorPackagerConnection.sendEventToAllConnections("{ \"id\":1,\"method\":\"Debugger.disable\" }");
}
public void downloadBundleFromURL(DevBundleDownloadListener paramDevBundleDownloadListener, File paramFile, String paramString, BundleDownloader.BundleInfo paramBundleInfo) {
this.mBundleDownloader.downloadBundleFromURL(paramDevBundleDownloadListener, paramFile, paramString, paramBundleInfo);
}
public File downloadBundleResourceFromUrlSync(String paramString, File paramFile) {
String str = createResourceURL(this.mSettings.getPackagerConnectionSettings().getDebugServerHost(), paramString);
ac ac = (new ac.a()).a(str).c();
try {
ae ae = this.mClient.a(ac).b();
try {
Exception exception;
boolean bool = ae.a();
if (!bool)
return null;
try {
x x = q.a(paramFile);
} finally {
exception = null;
}
if (ac != null)
ac.close();
throw exception;
} finally {
ac = null;
}
} catch (Exception exception) {
a.c("ReactNative", "Failed to fetch resource synchronously - resourcePath: \"%s\", outputFile: \"%s\"", new Object[] { paramString, paramFile.getAbsolutePath(), exception });
return null;
}
}
public String getDevServerBundleURL(String paramString) {
BundleType bundleType;
if (this.mSettings.isBundleDeltasEnabled()) {
bundleType = BundleType.DELTA;
} else {
bundleType = BundleType.BUNDLE;
}
return createBundleURL(paramString, bundleType, this.mSettings.getPackagerConnectionSettings().getDebugServerHost());
}
public String getInspectorAttachUrl(String paramString) {
return a.a(Locale.US, "http://%s/nuclide/attach-debugger-nuclide?title=%s&app=%s&device=%s", new Object[] { AndroidInfoHelpers.getServerHost(), paramString, this.mPackageName, AndroidInfoHelpers.getFriendlyDeviceName() });
}
public String getInspectorDeviceUrl() {
return a.a(Locale.US, "http://%s/inspector/device?name=%s&app=%s", new Object[] { this.mSettings.getPackagerConnectionSettings().getInspectorServerHost(), AndroidInfoHelpers.getFriendlyDeviceName(), this.mPackageName });
}
public String getJSBundleURLForRemoteDebugging(String paramString) {
return createBundleURL(paramString, BundleType.BUNDLE, getHostForJSProxy());
}
public String getSourceMapUrl(String paramString) {
return createBundleURL(paramString, BundleType.MAP);
}
public String getSourceUrl(String paramString) {
BundleType bundleType;
if (this.mSettings.isBundleDeltasEnabled()) {
bundleType = BundleType.DELTA;
} else {
bundleType = BundleType.BUNDLE;
}
return createBundleURL(paramString, bundleType);
}
public String getWebsocketProxyURL() {
return a.a(Locale.US, "ws://%s/debugger-proxy?role=client", new Object[] { this.mSettings.getPackagerConnectionSettings().getDebugServerHost() });
}
public void handleOnChangePollingResponse(boolean paramBoolean) {
if (this.mOnChangePollingEnabled) {
if (paramBoolean)
UiThreadUtil.runOnUiThread(new Runnable() {
public void run() {
if (DevServerHelper.this.mOnServerContentChangeListener != null)
DevServerHelper.this.mOnServerContentChangeListener.onServerContentChanged();
}
});
enqueueOnChangeEndpointLongPolling();
}
}
public void isPackagerRunning(final PackagerStatusCallback callback) {
String str = createPackagerStatusURL(this.mSettings.getPackagerConnectionSettings().getDebugServerHost());
ac ac = (new ac.a()).a(str).c();
this.mClient.a(ac).a(new f() {
public void onFailure(e param1e, IOException param1IOException) {
StringBuilder stringBuilder = new StringBuilder("The packager does not seem to be running as we got an IOException requesting its status: ");
stringBuilder.append(param1IOException.getMessage());
a.b("ReactNative", stringBuilder.toString());
callback.onPackagerStatusFetched(false);
}
public void onResponse(e param1e, ae param1ae) throws IOException {
if (!param1ae.a()) {
StringBuilder stringBuilder = new StringBuilder("Got non-success http code from packager when requesting status: ");
stringBuilder.append(param1ae.c);
a.c("ReactNative", stringBuilder.toString());
callback.onPackagerStatusFetched(false);
return;
}
af af = param1ae.g;
if (af == null) {
a.c("ReactNative", "Got null body response from packager when requesting status");
callback.onPackagerStatusFetched(false);
return;
}
if (!"packager-status:running".equals(af.string())) {
StringBuilder stringBuilder = new StringBuilder("Got unexpected response from packager when requesting status: ");
stringBuilder.append(af.string());
a.c("ReactNative", stringBuilder.toString());
callback.onPackagerStatusFetched(false);
return;
}
callback.onPackagerStatusFetched(true);
}
});
}
public void launchJSDevtools() {
ac ac = (new ac.a()).a(createLaunchJSDevtoolsCommandUrl()).c();
this.mClient.a(ac).a(new f() {
public void onFailure(e param1e, IOException param1IOException) {}
public void onResponse(e param1e, ae param1ae) throws IOException {}
});
}
public void openInspectorConnection() {
if (this.mInspectorPackagerConnection != null) {
a.b("ReactNative", "Inspector connection already open, nooping.");
return;
}
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... param1VarArgs) {
DevServerHelper devServerHelper = DevServerHelper.this;
devServerHelper.mInspectorPackagerConnection = new InspectorPackagerConnection(devServerHelper.getInspectorDeviceUrl(), DevServerHelper.this.mPackageName, DevServerHelper.this.mBundlerStatusProvider);
DevServerHelper.this.mInspectorPackagerConnection.connect();
return null;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])new Void[0]);
}
public void openPackagerConnection(final String clientId, final PackagerCommandListener commandListener) {
if (this.mPackagerClient != null) {
a.b("ReactNative", "Packager connection already open, nooping.");
return;
}
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... param1VarArgs) {
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
hashMap.put("reload", new NotificationOnlyHandler() {
public void onNotification(Object param2Object) {
commandListener.onPackagerReloadCommand();
}
});
hashMap.put("devMenu", new NotificationOnlyHandler() {
public void onNotification(Object param2Object) {
commandListener.onPackagerDevMenuCommand();
}
});
hashMap.put("captureHeap", new RequestOnlyHandler() {
public void onRequest(Object param2Object, Responder param2Responder) {
commandListener.onCaptureHeapCommand(param2Responder);
}
});
hashMap.put("pokeSamplingProfiler", new RequestOnlyHandler() {
public void onRequest(Object param2Object, Responder param2Responder) {
commandListener.onPokeSamplingProfilerCommand(param2Responder);
}
});
hashMap.putAll((new FileIoHandler()).handlers());
ReconnectingWebSocket.ConnectionCallback connectionCallback = new ReconnectingWebSocket.ConnectionCallback() {
public void onConnected() {
commandListener.onPackagerConnected();
}
public void onDisconnected() {
commandListener.onPackagerDisconnected();
}
};
DevServerHelper devServerHelper = DevServerHelper.this;
devServerHelper.mPackagerClient = new JSPackagerClient(clientId, devServerHelper.mSettings.getPackagerConnectionSettings(), hashMap, connectionCallback);
DevServerHelper.this.mPackagerClient.init();
return null;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[])new Void[0]);
}
public void openStackFrameCall(StackFrame paramStackFrame) {
String str = createOpenStackFrameURL(this.mSettings.getPackagerConnectionSettings().getDebugServerHost());
ac ac = (new ac.a()).a(str).a(ad.create(w.a("application/json"), paramStackFrame.toJSON().toString())).c();
((e)a.b(this.mClient.a(ac))).a(new f() {
public void onFailure(e param1e, IOException param1IOException) {
StringBuilder stringBuilder = new StringBuilder("Got IOException when attempting to open stack frame: ");
stringBuilder.append(param1IOException.getMessage());
a.b("ReactNative", stringBuilder.toString());
}
public void onResponse(e param1e, ae param1ae) throws IOException {}
});
}
public void startPollingOnChangeEndpoint(OnServerContentChangeListener paramOnServerContentChangeListener) {
if (this.mOnChangePollingEnabled)
return;
this.mOnChangePollingEnabled = true;
this.mOnServerContentChangeListener = paramOnServerContentChangeListener;
this.mOnChangePollingClient = (new y.a()).a(new j(1, 120000L, TimeUnit.MINUTES)).a(5000L, TimeUnit.MILLISECONDS).a();
enqueueOnChangeEndpointLongPolling();
}
public void stopPollingOnChangeEndpoint() {
this.mOnChangePollingEnabled = false;
this.mRestartOnChangePollingHandler.removeCallbacksAndMessages(null);
y y1 = this.mOnChangePollingClient;
if (y1 != null) {
OkHttpCallUtil.cancelTag(y1, this);
this.mOnChangePollingClient = null;
}
this.mOnServerContentChangeListener = null;
}
public void symbolicateStackTrace(Iterable<StackFrame> paramIterable, final SymbolicationListener listener) {
try {
String str = createSymbolicateURL(this.mSettings.getPackagerConnectionSettings().getDebugServerHost());
JSONArray jSONArray = new JSONArray();
Iterator<StackFrame> iterator = paramIterable.iterator();
while (iterator.hasNext())
jSONArray.put(((StackFrame)iterator.next()).toJSON());
ac ac = (new ac.a()).a(str).a(ad.create(w.a("application/json"), (new JSONObject()).put("stack", jSONArray).toString())).c();
((e)a.b(this.mClient.a(ac))).a(new f() {
public void onFailure(e param1e, IOException param1IOException) {
StringBuilder stringBuilder = new StringBuilder("Got IOException when attempting symbolicate stack trace: ");
stringBuilder.append(param1IOException.getMessage());
a.b("ReactNative", stringBuilder.toString());
listener.onSymbolicationComplete(null);
}
public void onResponse(e param1e, ae param1ae) throws IOException {
try {
listener.onSymbolicationComplete(Arrays.asList(StackTraceHelper.convertJsStackTrace((new JSONObject(param1ae.g.string())).getJSONArray("stack"))));
return;
} catch (JSONException jSONException) {
listener.onSymbolicationComplete(null);
return;
}
}
});
return;
} catch (JSONException jSONException) {
StringBuilder stringBuilder = new StringBuilder("Got JSONException when attempting symbolicate stack trace: ");
stringBuilder.append(jSONException.getMessage());
a.b("ReactNative", stringBuilder.toString());
return;
}
}
enum BundleType {
BUNDLE("bundle"),
DELTA("delta"),
MAP("map");
private final String mTypeID;
static {
}
BundleType(String param1String1) {
this.mTypeID = param1String1;
}
public final String typeID() {
return this.mTypeID;
}
}
public static interface OnServerContentChangeListener {
void onServerContentChanged();
}
public static interface PackagerCommandListener {
void onCaptureHeapCommand(Responder param1Responder);
void onPackagerConnected();
void onPackagerDevMenuCommand();
void onPackagerDisconnected();
void onPackagerReloadCommand();
void onPokeSamplingProfilerCommand(Responder param1Responder);
}
public static interface SymbolicationListener {
void onSymbolicationComplete(Iterable<StackFrame> param1Iterable);
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\devsupport\DevServerHelper.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
import java.io.IOException;
public class LaunchGame {
public static void main(String[] args) throws IOException {
new Rules();
int[][]comp= new int[10][10];
int[][]player= new int[10][10];
createBattlefield(comp);
createBattlefield(player);
System.out.println("Поля для битвы созданы.");
new DevelopTactics(comp);
System.out.println("Корабли нарисованы.");
System.out.println("В бой!");
System.out.println("");
while(true){
new Shot(player);
new PlayerShot(comp);
}
}
private static void createBattlefield(int[][] battlefield) {
for (int i =0; i<battlefield.length; i++){
for (int j=0; j <10; j++){
battlefield[j][i]=0;
}
}
}
}
|
import java.util.*;
/**
* Created by alexanderhughes on 2/22/16.
*/
public class Exercise04 {
public static void main(String[] args) {
String sentence = "To be or not to be, that is the question.";
sentence = sentence.toLowerCase();
sentence = sentence.replace(",", "").replace(".","");
System.out.println(sentence);
String[] words = sentence.split(" ");System.out.println();
List<String> wordList = Arrays.asList(words);
Set<String> wordSet = new LinkedHashSet<String>(wordList);
ArrayList<String> frequencies = new ArrayList<>();//LinkedHashSet does not allow duplicate values
for (String word : words) {
if(!frequencies.contains(word)) { //or (!frequencies.containsKey(word))
frequencies.add(word);
}
}
System.out.println(String.join(" ", frequencies));
}
}
|
public class LLDriver {
public static void main(String[] args){
MyLinkedList L = new MyLinkedList();
L.add("A");
L.add("B");
L.add("C");
System.out.println(L.get(1));
L.add("D");
L.set(1, "Apple");
L.add("E");
System.out.println(L);
System.out.println(L.find("Apple"));
}
}
|
package com.tencent.mm.ac;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.am;
import com.tencent.mm.network.b;
import com.tencent.mm.sdk.platformtools.at.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.c;
import com.tencent.mm.sdk.platformtools.x;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
class m$b implements a {
public byte[] dHe = null;
private final String dMB;
private final String url;
public m$b(String str, String str2) {
this.dMB = str;
this.url = str2;
}
public final boolean Kr() {
if (bi.oW(this.dMB) || bi.oW(this.url)) {
return false;
}
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream n = b.n(this.url, 3000, 5000);
if (n == null) {
return false;
}
byte[] bArr = new byte[1024];
while (true) {
int read = n.read(bArr);
if (read == -1) {
break;
}
byteArrayOutputStream.write(bArr, 0, read);
}
n.close();
this.dHe = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
if (bi.bC(this.dHe)) {
x.e("MicroMsg.BrandLogic", "imgBuff null brand:" + this.dMB);
return false;
}
if (g.Eg().Dx()) {
am.a.dBs.aY(this.dHe.length, 0);
m.a Ni = z.Ni();
String str = this.dMB;
String str2 = this.url;
byte[] bArr2 = this.dHe;
try {
str2 = str + str2;
Bitmap bs = c.bs(bArr2);
c.a(bs, 100, CompressFormat.PNG, m.a.kW(str2), false);
Ni.g(str, bs);
x.i("MicroMsg.BrandLogic", "update brand icon for " + str + ", done");
Ni.dMy.remove(str);
} catch (Throwable e) {
x.e("MicroMsg.BrandLogic", "exception:%s", new Object[]{bi.i(e)});
}
}
return true;
} catch (Throwable e2) {
x.e("MicroMsg.BrandLogic", "exception:%s", new Object[]{bi.i(e2)});
x.e("MicroMsg.BrandLogic", "get url:" + this.url + " failed.");
this.dHe = null;
return false;
}
}
public final boolean Ks() {
m.a Ni = z.Ni();
String str = this.dMB;
int i = 0;
while (i < Ni.dMx.size()) {
try {
((m$a$a) Ni.dMx.get(i)).kX(str);
i++;
} catch (Throwable e) {
x.e("MicroMsg.BrandLogic", "exception:%s", new Object[]{bi.i(e)});
}
}
return false;
}
}
|
package HelloWorldController;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import HelloWorldModel.HelloWorldModel;
import HelloWorldView.HelloWorldView;
public class HelloWorldController {
private HelloWorldModel model;
private HelloWorldView view;
public HelloWorldController(HelloWorldModel model, HelloWorldView view) {
this.model = model;
this.view = view;
this.view.addActionListener(new PressActionListener());
}
class PressActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String message = "";
try{
message = view.getInput();
model.setMessage(message);
view.setResult();
}
catch(Exception ex){
System.out.println("Not a sentence!");
}
}
}
}
|
package com.hb.rssai.util;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import com.hb.rssai.constants.Constant;
import com.hb.util.SdUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageUtil {
// 缩放比例
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
System.out.println("宽度" + height);
System.out.println("高度" + width);
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
/**
* 读取图片属性:旋转的角度
*
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 旋转图片
*
* @param angle
* @param bitmap
* @return Bitmap
*/
public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
// 旋转图片 动作
Matrix matrix = new Matrix();
matrix.postRotate(angle);
System.out.println("angle2=" + angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
/**
* 通过uri获取图片地址
*
* @param uri
* @return
*/
public static String getPath(Uri uri, Activity act) {
/*
* String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor
* = getContentResolver().query(uri, projection, null, null, null); int
* column_index = cursor
* .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
* cursor.moveToFirst(); return cursor.getString(column_index);
*/
// 由于原先的方式不支持系统4.4.4版本
return getImageAbsolutePath(act, uri);
}
/**
* 根据Uri获取图片绝对路径,解决Android4.4以上版本Uri转换
*
* @param
* @param imageUri
* @author yaoxing
* @date 2014-10-12
*/
@TargetApi(19)
public static String getImageAbsolutePath(Activity context, Uri imageUri) {
if (context == null || imageUri == null)
return null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
&& DocumentsContract.isDocumentUri(context, imageUri)) {
if (isExternalStorageDocument(imageUri)) {
String docId = DocumentsContract.getDocumentId(imageUri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/"
+ split[1];
}
} else if (isDownloadsDocument(imageUri)) {
String id = DocumentsContract.getDocumentId(imageUri);
Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"),
Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(imageUri)) {
String docId = DocumentsContract.getDocumentId(imageUri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = BaseColumns._ID + "=?";
String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
}
} // MediaStore (and general)
else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(imageUri))
return imageUri.getLastPathSegment();
return getDataColumn(context, imageUri, null, null);
}
// File
else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
return imageUri.getPath();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri
.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri
.getAuthority());
}
public static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
String column = MediaColumns.DATA;
String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri
.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri
.getAuthority());
}
// 获取sd卡路径
public static String getSdPath(Context c) {
// get stargestate if storagestate is MEDIA_MOUNTED(mean:SD onLine)
String path = null;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File file = Environment.getExternalStorageDirectory();
// get the standard Path
try {
path = file.getCanonicalPath();
// Toast.makeText(c, path, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
return path == null ? "/sdcard/" : path;
}
public static Bitmap textAsBitmap(String text, float textSize) {
TextPaint textPaint = new TextPaint();
// textPaint.setARGB(0x31, 0x31, 0x31, 0);
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(textSize);
StaticLayout layout = new StaticLayout(text, textPaint, 100, Layout.Alignment.ALIGN_NORMAL, 1.3f, 0.0f, true);
Bitmap bitmap = Bitmap.createBitmap(layout.getWidth() + 20, layout.getHeight() + 20, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.translate(10, 10);
canvas.drawColor(Color.YELLOW);
layout.draw(canvas);
Log.d("textAsBitmap", String.format("1:%d %d", layout.getWidth(), layout.getHeight()));
return bitmap;
}
/**
* 获取缩放后的本地图片
*
* @param filePath 文件路径
* @param width 宽
* @param height 高
* @return
*/
public static Bitmap readBitmapFromFileDescriptor(String filePath, int width, int height) {
try {
FileInputStream fis = new FileInputStream(filePath);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);
float srcWidth = options.outWidth;
float srcHeight = options.outHeight;
int inSampleSize = 1;
if (srcHeight > height || srcWidth > width) {
if (srcWidth > srcHeight) {
inSampleSize = Math.round(srcHeight / height);
} else {
inSampleSize = Math.round(srcWidth / width);
}
}
options.inJustDecodeBounds = false;
options.inSampleSize = inSampleSize;
return BitmapFactory.decodeFileDescriptor(fis.getFD(), null, options);
} catch (Exception ex) {
}
return null;
}
/**
* 获取头像存储地址
*/
public static String getAvatarPath(String avatarName) {
String availableSdPath = SdUtils.isAllSdEnough(50);
String SAVE_DIR = Constant.AVATAR_SAVE_DIR;//保存文件夹名称
String SAVE_DIR_NAME = avatarName;//保存文件名称
return availableSdPath + SAVE_DIR + SAVE_DIR_NAME;
}
public static byte[] getLocalAvatar(String avatarName) {
if (TextUtils.isEmpty(avatarName)) {
return null;
}
try {
Bitmap bitmap = ImageUtil.readBitmapFromFileDescriptor(ImageUtil.getAvatarPath(avatarName + ".jpg"), 200, 200);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bytes = baos.toByteArray();
baos.close();
baos.flush();
return bytes;//返回一个bitmap对象
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 保存bitmap到本地
*
* @param context
* @param mBitmap
* @return
*/
public static final String TAG = "GifHeaderParser";
public static void saveBitmap(Bitmap mBitmap, String avatarName) {
boolean isSuc;
try {
String availableSdPath = SdUtils.isAllSdEnough(50);
if (null != availableSdPath) {
File file = new File(availableSdPath + Constant.AVATAR_SAVE_DIR);
String apkFilePath;
File apkFile = null;
if (!file.exists()) {
isSuc = file.mkdirs();
if (isSuc) {
apkFilePath = availableSdPath + Constant.AVATAR_SAVE_DIR + avatarName + ".jpg";
apkFile = new File(apkFilePath);
} else {
Log.d(TAG, "文件夹" + availableSdPath + Constant.AVATAR_SAVE_DIR + "创建失败");
}
} else {
delAllFile(availableSdPath + Constant.AVATAR_SAVE_DIR);
apkFilePath = availableSdPath + Constant.AVATAR_SAVE_DIR + avatarName + ".jpg";
apkFile = new File(apkFilePath);
}
FileOutputStream fos = new FileOutputStream(apkFile);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
Log.d(TAG, "图片保存成功");
}
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
}
}
/**
* 删除指定文件夹下所有文件
*
* @param path 文件夹完整绝对路径
* @return
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
}
return flag;
}
}
|
package com.tencent.mm.pluginsdk;
import android.app.Activity;
import com.tencent.mm.ac.d;
import com.tencent.mm.kernel.c.a;
import com.tencent.mm.storage.ab;
public interface g extends a {
void a(d dVar, Activity activity, ab abVar);
void a(d dVar, Activity activity, ab abVar, boolean z, Runnable runnable);
}
|
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import bean.CommentBean;
public class CommentDao {
/**
* 根据评论id得到某个评论
*/
public CommentBean getCommentBycommentId(int commentId) {
CommentBean commentBean=new CommentBean();
Connection conn=DataBase.getConnection();
PreparedStatement pstmt=null;
String sql="select comment_detail,comment_date,user_id,note_id from comment where comment_id=?";
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, commentId);
ResultSet rs=pstmt.executeQuery();
while(rs.next()) {
commentBean.setCommentId(commentId);
commentBean.setCommentDetail(rs.getString("comment_detail"));
//将数据库中时间戳类型转化成符合某种格式的Date对象
Timestamp time = rs.getTimestamp("comment_date");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
String str = sdf.format(time);
Date date = sdf.parse(str);
commentBean.setCommentDate(date);
commentBean.setUser(new UserDao().getUserById(rs.getInt("user_id")));
commentBean.setNote(new NoteDao().getNoteById(rs.getInt("note_id")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(pstmt);
DataBase.close(conn);
}
return commentBean;
}
/**
* 根据笔记id得到评论列表(所有评论)
*/
public List<CommentBean> getCommentsBynoteId(int noteId){
List<CommentBean> commentList=new ArrayList<CommentBean>();
Connection conn=DataBase.getConnection();
PreparedStatement pstmt=null;
String sql="select comment_id,comment_detail,comment_date,user_id from comment where note_id=? order by comment_date desc";
ResultSet rs=null;
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, noteId);
rs=pstmt.executeQuery();
while(rs.next()) {
CommentBean commentBean=new CommentBean();
commentBean.setCommentId(rs.getInt("comment_id"));
commentBean.setCommentDetail(rs.getString("comment_detail"));
//将数据库中时间戳类型转化成符合某种格式的Date对象
Timestamp time = rs.getTimestamp("comment_date");
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
String str = sdf.format(time);
Date date = sdf.parse(str);
commentBean.setCommentDate(date);
commentBean.setUser(new UserDao().getUserById(rs.getInt("user_id")));
commentBean.setNote(new NoteDao().getNoteById(noteId));
commentList.add(commentBean);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(rs);
DataBase.close(pstmt);
DataBase.close(conn);
}
return commentList;
}
/**
* 计算某个笔记id的评论总数
*/
public int getCommentCount(int noteId) {
Connection conn=DataBase.getConnection();
PreparedStatement pstmt=null;
String sql="select count(*) c from comment where note_id=?";
int count=0;
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, noteId);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
count=rs.getInt("c");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(pstmt);
DataBase.close(conn);
}
return count;
}
/**
* 添加评论(修改)
*/
public void addComment(CommentBean comment) {
Connection conn=DataBase.getConnection();
PreparedStatement pstmt=null;
String sql="insert into comment(comment_id,comment_detail,comment_date,user_id,note_id) values(0,?,NOW(),?,?)" ;
try {
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, comment.getCommentDetail());
pstmt.setInt(2, comment.getUser().getUserId());
pstmt.setInt(3, comment.getNote().getNoteId());
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(pstmt);
DataBase.close(conn);
}
}
/**
* 删除评论
* */
public void removeComment(int commentId) {
Connection conn = DataBase.getConnection();
PreparedStatement pstmt = null;
try {
String sql = "delete from comment where comment_id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, commentId);
pstmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(pstmt);
DataBase.close(conn);
}
}
/**
* 点赞评论(修改)
*/
public void clickLike(int userId,int commentId) {
Connection conn=DataBase.getConnection();
PreparedStatement pstmt=null;
String sql="insert into like_comment(user_id,comment_id) values(?,?)";
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1,userId);
pstmt.setInt(2, commentId);
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(pstmt);
DataBase.close(conn);
}
}
/**
* 取消评论点赞(修改)
*/
public void cancelLike(int userId,int commentId) {
Connection conn=DataBase.getConnection();
PreparedStatement pstmt=null;
String sql="delete from like_comment where user_id =? and comment_id=?" ;
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1,userId);
pstmt.setInt(2, commentId);
pstmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(pstmt);
DataBase.close(conn);
}
}
/**
* 查看该用户是否点赞了该评论
* */
public boolean isLike(int userId,int commentId) {
boolean is = false;
Connection conn = DataBase.getConnection();
PreparedStatement pstmt = null;
ResultSet res = null;
try {
String sql = "select * from like_comment where user_id =? and comment_id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, userId);
pstmt.setInt(2, commentId);
res = pstmt.executeQuery();
if(res.next())
is = true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DataBase.close(res);
DataBase.close(pstmt);
DataBase.close(conn);
}
return is;
}
/**
* 得到某个评论总的赞数(新增)
*/
public int getLikeCount(int commentId) {
Connection conn = DataBase.getConnection();
PreparedStatement pstmt = null;
ResultSet res = null;
String sql="select count(*) c from like_comment where comment_id=?";
int count=0;
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, commentId);
res=pstmt.executeQuery();
if(res.next()) {
count=res.getInt("c");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DataBase.close(res);
DataBase.close(pstmt);
DataBase.close(conn);
}
return count;
}
}
|
package com.yida.design.command.generator;
/**
*********************
* 客户端
*
* @author yangke
* @version 1.0
* @created 2018年5月12日 上午11:03:40
***********************
*/
public class Client {
public static void main(String[] args) {
// 声明调用者
Invoker invoker = new Invoker();
// 定义接收者
ConcreteReciver1 receiver = new ConcreteReciver1();
// 定义接收者命令
AbstractCommand command = new ConcreteCommand1(receiver);
// 把命令交给调用者去执行
invoker.setCommand(command);
invoker.action();
}
}
|
package com.bat.eureka.server.eventlistener;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* 服务监听
*
* @author ZhengYu
* @version 1.0 2019/12/8 11:57
**/
@Slf4j
@Component
public class EurekaClientChangeEventListener {
/**
* 监听 服务下线事件
*
* @param eurekaInstanceCanceledEvent 服务下线事件
* @author ZhengYu
*/
@EventListener
public void listen(EurekaInstanceCanceledEvent eurekaInstanceCanceledEvent) {
// 判断是否为master节点
if (!eurekaInstanceCanceledEvent.isReplication()) {
log.info("服务下线事件 ==> appName=[{}],serverId=[{}]", eurekaInstanceCanceledEvent.getAppName(), eurekaInstanceCanceledEvent.getServerId());
}
}
/**
* 监听 服务注册事件
*
* @param eurekaInstanceRegisteredEvent 服务下线事件
* @author ZhengYu
*/
@EventListener
public void listen(EurekaInstanceRegisteredEvent eurekaInstanceRegisteredEvent) {
// 判断是否为master节点
if (!eurekaInstanceRegisteredEvent.isReplication()) {
log.info("服务注册事件 ==> instanceInfo=[{}],leaseDuration=[{}]", JSONObject.toJSONString(eurekaInstanceRegisteredEvent.getInstanceInfo()), eurekaInstanceRegisteredEvent.getLeaseDuration());
}
}
/**
* 监听 服务续约事件
*
* @param eurekaInstanceRenewedEvent 服务续约事件
* @author ZhengYu
*/
@EventListener
public void listen(EurekaInstanceRenewedEvent eurekaInstanceRenewedEvent) {
// 判断是否为master节点
if (!eurekaInstanceRenewedEvent.isReplication()) {
log.info("服务续约事件 ==> appName=[{}],serverId=[{}]", eurekaInstanceRenewedEvent.getAppName(), eurekaInstanceRenewedEvent.getServerId());
}
}
/**
* 监听 Eureka注册中心启动事件
*
* @param eurekaRegistryAvailableEvent Eureka注册中心启动事件
* @author ZhengYu
*/
@EventListener
public void listen(EurekaRegistryAvailableEvent eurekaRegistryAvailableEvent) {
log.info("Eureka注册中心启动...");
}
/**
* 监听 Eureka Server启动事件
*
* @param eurekaServerStartedEvent Eureka Server启动事件
* @author ZhengYu
*/
@EventListener
public void listen(EurekaServerStartedEvent eurekaServerStartedEvent) {
log.info("Eureka Server启动...");
}
}
|
package com.github.andreptb.fitnessemavenrunner;
import java.io.File;
import java.util.HashMap;
import java.util.Objects;
import org.apache.maven.plugin.testing.MojoRule;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class FitnesseRunnerMojoTest {
@Rule
public MojoRule rule = new MojoRule();
private MojoExecutor mojo;
@Before
public void setUpMavenProject() throws Exception {
this.mojo = new MojoExecutor();
}
@Test
public void testRunSuiteWithDefaultConfig() throws Exception {
this.mojo.put("command", "FrontPage?suite&format=text");
this.mojo.execute("/test-project", "run");
}
private class MojoExecutor extends HashMap<String, String> {
void execute(String pom, String goal) throws Exception {
Xpp3Dom[] config = entrySet().stream().map(entry -> {
Xpp3Dom dom = new Xpp3Dom(Objects.toString(entry.getKey()));
dom.setValue(Objects.toString(entry.getValue()));
return dom;
}).toArray(size -> new Xpp3Dom[size]);
FitnesseRunnerMojoTest.this.rule.executeMojo(FitnesseRunnerMojoTest.this.rule.readMavenProject(new File(getClass().getResource(pom).toURI())), goal, config);
}
}
}
|
package com.Collections_PriorityQueue_HashMap_TreeMap;
import java.util.HashMap;
//4. Write a Java program to remove all of the mappings from a map.
public class HashMap_RemoveAllMapping {
public static void main(String args[]) {
HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
hash_map.put(1, "Raj");
hash_map.put(2, "Rohan");
hash_map.put(3, "Bhanu");
hash_map.put(4, "Rahul");
hash_map.put(5, "Sham");
// print the map
System.out.println("The Original linked map: " + hash_map);
// Removing all the elements from the linked map
hash_map.clear();
System.out.println("The New map: " + hash_map);
}
}
|
package ru.zizitop.examples.schedule;
import java.time.DayOfWeek;
public class LessonSchedule {
public Long id;
public DayOfWeek dayOfWeek;
public Integer hour;
public Integer minute;
public boolean canceled;
@Override
public String toString() {
return "LessonSchedule{" +
"id=" + id +
", dayOfWeek=" + dayOfWeek +
", hour=" + hour +
", minute=" + minute +
", canceled=" + canceled +
'}';
}
}
|
package edu.metrostate.ics372.thatgroup.clinicaltrial.android.patientactivity;
import java.time.LocalDate;
import edu.metrostate.ics372.thatgroup.clinicaltrial.android.BaseView;
import edu.metrostate.ics372.thatgroup.clinicaltrial.android.patientactivity.PatientPresenter;
/**
* @author That Group
*/
public interface PatientView extends BaseView<PatientPresenter> {
void setPatientId(String id);
void setStartDate(LocalDate date);
void setEndDate(LocalDate date);
void setStatusId(String statusId);
String getPatientId();
LocalDate getStartDate();
LocalDate getEndDate();
String getStatusId();
void setVisibleStartTrial(boolean visible);
void setVisibleEndTrial(boolean visible);
void setVisibleAddReading(boolean visible);
void setVisibleViewReadings(boolean visible);
void setVisibleSave(boolean visible);
void setDisabledSave(boolean disable);
void setDisabledId(boolean disable);
void setDisabledStartTrial(boolean disable);
void setDisabledEndTrial(boolean disable);
}
|
class Solution {
public boolean canThreePartsEqualSum(int[] A) {
int sum = Arrays.stream(A).sum(), part = 0, average = sum / 3, cnt = 0;
for (int a : A) {
part += a;
if (part == average) { // find the average: sum / 3
++cnt; // find an average, increase the counter.
part = 0; // reset part.
}
}
return cnt >= 3 && sum % 3 == 0;
}
/*
public boolean canThreePartsEqualSum(int[] A) {
int i = 0;
int j = A.length - 1;
int tot = 0;
while(i <= j)
{
tot += A[i++];
}
if(tot % 3 != 0)
{
return false;
}
int part = tot/3;
i = 0;
int cur = 0;
int count = 0;
while(i <= j)
{
cur += A[i++];
System.out.println("cur" + cur);
if(cur == part)
{
cur = 0;
count++;
}
}
if(count == 3 && tot != 0 )
{
return true;
}
if(count >= 3 && tot == 0 )
{
return true;
}
return false;
}*/
} |
package com.base.crm.orders.controller;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.base.common.util.ExcelView;
import com.base.common.util.PageTools;
import com.base.crm.common.constants.OrderStatus;
import com.base.crm.consume.entity.CustomerConsume;
import com.base.crm.consume.service.CustomerConsumeService;
import com.base.crm.customer.entity.CustInfo;
import com.base.crm.customer.service.CustInfoService;
import com.base.crm.orders.constants.OrderExcelMappings;
import com.base.crm.orders.entity.CustOrder;
import com.base.crm.orders.service.CustOrderService;
import com.base.crm.orders.utils.OrderExcelImport;
import com.base.crm.users.entity.UserInfo;
@Controller
@RequestMapping(value="/orders")
@SessionAttributes("user")
public class OrdersController {
private static final Logger logger = LoggerFactory.getLogger(OrdersController.class);
@Autowired
private CustOrderService custOrderService;
@Autowired
private CustInfoService custInfoService;
@Autowired
private CustomerConsumeService customerConsumeService;
@Autowired
private OrderExcelMappings orderExcelMappings;
@RequestMapping(value = "/pageView")
@ResponseBody
public Map<String, Object> ordersView(CustOrder order,PageTools pageTools,@ModelAttribute("user") UserInfo user){
logger.info("ordersView request:"+order);
if(!user.isAdmin()){
order.setUserId(user.getuId());
}
Long size = custOrderService.selectPageTotalCount(order);
pageTools.setTotal(size);
Map<String,Object> result = new HashMap<String,Object>();
result.put("pageTools", pageTools);
return result;
}
@RequestMapping(value="/orderEdit")
@ResponseBody
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
public Map<String,Object> orderEdit(CustOrder order) throws Exception{
logger.info("orderEdit request :"+order);
if(order.getOldOrderStatus()!=null){
if(order.getOldOrderStatus()>OrderStatus.DELIVERING.getKey()&&order.getOrderStatus()==OrderStatus.DELIVERING.getKey()){
throw new RuntimeException("此单不可修改为派送中状态!");
}else if(order.getOldOrderStatus()>=OrderStatus.SIGNED.getKey()){
throw new RuntimeException("此单不可修改状态!");
}else if(order.getOldOrderStatus()>=OrderStatus.DELIVERING.getKey()&&order.getOrderStatus()==OrderStatus.INVALIDATED.getKey()){
throw new RuntimeException("此单不可修改作废态!");
}else if(order.getOldOrderStatus()>=OrderStatus.DELIVERING.getKey()&&order.getOrderStatus() < OrderStatus.DELIVERING.getKey()){
throw new RuntimeException("此单不可回退状态!");
}
}
CustOrder resultOrder = custOrderService.selectByPrimaryKey(order.getOrderNo());
CustomerConsume consume = new CustomerConsume();
consume.setUserId(order.getUserId());
consume.setWechatNo(order.getoWechatNo());
consume.setOrderNo(order.getOrderNo());
consume.setConsumeDate(resultOrder.getOrderDate());
if(order.getOrderStatus()==OrderStatus.WAITING.getKey()){
if(order.getDeposits()!=null&&order.getDeposits()>0){
consume.setConsumeType(2);
consume.setAmount(new BigDecimal(order.getDeposits()));
consume.setRemark(String.format("微信号[%s]的金额消费:%s元,订单号[%s]",consume.getWechatNo(), consume.getAmount().toPlainString(),consume.getOrderNo()));
}else{
updateCustomerAMT(order);
consume.setConsumeType(3);
consume.setAmount(new BigDecimal(order.getPayAmount()).negate());
consume.setRemark(String.format("微信号[%s]的余额消费:%s元,订单号[%s]",consume.getWechatNo(), consume.getAmount().toPlainString(),consume.getOrderNo()));
}
}else if(order.getOrderStatus()==OrderStatus.SIGNED.getKey()){
if(order.getPayAmount()!=order.getTotalAmt()){
double payment = order.getDeposits()+ order.getCashOnDeliveryAmt();
order.setPayAmount(payment);
}
if(order.getCashOnDeliveryAmt()!=null&&order.getCashOnDeliveryAmt()>0){
consume.setConsumeType(2);
consume.setAmount(new BigDecimal(order.getCashOnDeliveryAmt()));
consume.setRemark(String.format("微信号[%s]的金额消费:%s元,订单号[%s]",consume.getWechatNo(), consume.getAmount().toPlainString(),consume.getOrderNo()));
}
}else if(order.getOrderStatus()==OrderStatus.REFUSED.getKey()){
consume.setConsumeType(4);
customerConsumeService.updateByOrderNo(consume);
BigDecimal amount = new BigDecimal(order.getDeposits() - order.getPayAmount());
consume.setConsumeType(6);
consume.setAmount(amount.negate());
consume.setRemark(String.format("微信号[%s]的退款:%s元,订单号[%s]元,拒收或退款",consume.getWechatNo(), consume.getAmount().toPlainString(),consume.getOrderNo()));
}
if(OrderStatus.DELIVERING.getKey()==order.getOrderStatus()){
order.setDepositoryId(resultOrder.getDepositoryId());
order.setAssortId(resultOrder.getAssortId());
// 控制同一状态不会重复更新库存减少
if(order.getOldOrderStatus()!=null&&OrderStatus.DELIVERING.getKey()!=order.getOldOrderStatus()){
custOrderService.batchUpdateProductStock(order,-1);
}
}else if( OrderStatus.REFUSED.getKey()==order.getOrderStatus()){
custOrderService.batchUpdateProductStock(order,1);
}
int paymentMethod = order.getPaymentMethod()==null?-1:order.getPaymentMethod();
if(consume.getRemark()!=null && paymentMethod!=3){
logger.info(consume.getRemark());
customerConsumeService.insertSelective(consume);
}
int num = custOrderService.updateByPrimaryKeySelective(order);
Map<String,Object> map = new HashMap<String,Object>();
map.put("success", true);
map.put("editNumber", num);
return map;
}
private void updateCustomerAMT(CustOrder order) throws Exception {
CustInfo customer = new CustInfo();
customer.setCustWechatNo(order.getoWechatNo());
customer.setAmt(order.getPayAmount()*-1);
custInfoService.updateByPrimaryKeySelective(customer);
}
@RequestMapping(value="/orderAdd")
@ResponseBody
public Map<String,Object> orderAdd(CustOrder order) throws Exception{
logger.info("orderAdd request:"+order);
// int num = custOrderService.insertSelective(order);
int num = custOrderService.doInsert(order);
Map<String,Object> map = new HashMap<String,Object>();
map.put("success", true);
map.put("addNumber", num);
return map;
}
@RequestMapping(value="/orderDel")
@ResponseBody
public Map<String,Object> orderDel(Long id) throws Exception{
logger.info("orderDel request:{}",id);
int num = custOrderService.doDelete(id);
Map<String,Object> map = new HashMap<String,Object>();
map.put("success", true);
map.put("addNumber", num);
return map;
}
@RequestMapping(value="/loadPage")
public ModelAndView loadPage(CustOrder order,PageTools pageTools,@ModelAttribute("user") UserInfo user) throws Exception{
logger.info("loadPage request:"+order +" page info ==="+pageTools);
logger.info("loadPage request user info =====:"+user);
if(!user.isAdmin()){
order.setUserId(user.getuId());
}
order.setPageTools(pageTools);
ModelAndView mv = new ModelAndView("page/orders/Content :: container-fluid");
Long size = custOrderService.selectPageTotalCount(order);
pageTools.setTotal(size);
List<CustOrder> ciList = custOrderService.selectPageByObjectForList(order);
logger.info("loadPage request list info =====:"+ciList);
mv.addObject("orderList", ciList);
mv.addObject("pageTools", pageTools);
mv.addObject("queryOrder", order);
return mv;
}
@RequestMapping(value="/primaryModalView")
public String primaryModalView(Long id,String modifyModel,Model model,@ModelAttribute("user") UserInfo user) throws Exception{
logger.info("primaryModalView request:"+id+",model:"+model);
// Map<Integer,String> orderStatusMap = new HashMap<Integer,String>();
// if(id!=null){
// CustOrder order = custOrderService.selectByPrimaryKey(id);
// model.addAttribute("modifyOrder", order);
// if(user.isAdmin()){
// orderStatusMap = OrderStatus.orderStatusMap;
// }else if(order.getOrderStatus()==OrderStatus.NON_DELIVERY.getKey()){
// orderStatusMap.put(OrderStatus.NON_DELIVERY.getKey(), OrderStatus.NON_DELIVERY.toString());
// orderStatusMap.put(OrderStatus.WAITING.getKey(), OrderStatus.WAITING.toString());
// orderStatusMap.put(OrderStatus.INVALIDATED.getKey(), OrderStatus.INVALIDATED.toString());
// }else if(order.getOrderStatus()==OrderStatus.DELIVERING.getKey()){
// orderStatusMap.put(OrderStatus.DELIVERING.getKey(), OrderStatus.DELIVERING.toString());
// orderStatusMap.put(OrderStatus.SIGNED.getKey(), OrderStatus.SIGNED.toString());
// orderStatusMap.put(OrderStatus.REFUSED.getKey(), OrderStatus.REFUSED.toString());
// }else{
//
// orderStatusMap.put(order.getOrderStatus(), OrderStatus.orderStatusMap.get(order.getOrderStatus()));
// }
// }else{
// orderStatusMap.put(OrderStatus.NON_DELIVERY.getKey(), OrderStatus.NON_DELIVERY.toString());
// }
if(id!=null){
CustOrder order = custOrderService.selectByPrimaryKey(id);
model.addAttribute("modifyOrder", order);
}
model.addAttribute("orderStatusMap", OrderStatus.orderStatusMap);
model.addAttribute("modifyModel", modifyModel);
logger.info("model : "+model+", levelMap");
return "page/orders/ModifyModal";
}
@RequestMapping("/orderExport")
public ModelAndView orderExport(CustOrder order){
logger.info("orderExport request:"+order);
List<CustOrder> data = custOrderService.selectByObjectForList(order);
orderExcelMappings.setOrderExcelMappings(data);
Map<String, Object> map = new HashMap<String, Object>();
map.put("ExcelMappings", orderExcelMappings);
return new ModelAndView(new ExcelView(), map);
}
@RequestMapping("/importModalView")
public String importModalView(){
logger.info("importModalView request");
return "page/orders/ImportModalView";
}
@PostMapping("/import")
@ResponseBody
public Map<String, Object> importOrder(@RequestParam("file") MultipartFile file) throws Exception {
logger.info("import request");
List<CustOrder> orderList =new OrderExcelImport().batchImport( file.getOriginalFilename(), file);
custOrderService.batchUpdateOrders(orderList);
Map<String, Object> result = new HashMap<String, Object>();
result.put("message", "上传成功,总共上传订单数:"+orderList.size());
logger.info("import end:"+result);
return result;
}
}
|
package org.gmart.devtools.java.serdes.codeGenExample.openApiExample.generatedFiles;
import javax.annotation.processing.Generated;
import org.gmart.devtools.java.serdes.codeGen.javaGen.model.EnumSpecification;
@Generated("")
public enum AbstractNumberTypeType implements EnumSpecification.EnumValueFromYaml {
number,
integer;
public String toOriginalValue() {
return toString();
}
}
|
package com.ehootu.flow.model;
import java.io.Serializable;
/**
*
* 流动人口输入实体
*
* @author Kongxiaoping
* @email
* @date 2017-10-12 16:54:19
*/
public class InputPersonFlow implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
/**
* 操作类型
*/
private Integer operation;
/**
* 警号
*/
private String policeNumber;
/**
* 所属派出所
*/
private String policeStation;
/**
* 所属警务室
*/
private String policeOffice;
/**
* 申请时间 标志 1 一周内 2一个月内
*/
private String timeFlog;
/**
* 微信号id
*/
private String weixinId;
/**
* 开始时间
*/
private String startTime;
/**
* 结束时间
*/
private String endTime;
/**
* 行政区划名称
*/
private String xzqhmc;
/**
* 街路巷名称
*/
private String jlxmc;
/**
* 门牌号名称
*/
private String mphmc;
/**
* 门牌号后缀
*/
private String mphhz;
/**
* 楼牌号名称
*/
private String lphmc;
/**
* 楼牌号后缀
*/
private String lphhz;
/**
* 单元号名称
*/
private String dyhmc;
/**
* 单元号后缀
*/
private String dyhhz;
/**
* 层号名称
*/
private String chmc;
/**
* 层号后缀
*/
private String chhz;
/**
* 户号名称
*/
private String hhmc;
/**
* 户号后缀
*/
private String hhhz;
/**
* 全部名称
*/
private String address;
/**
* 42位地址编码
*/
private String mpdm;
/**
* 当前页码
*/
private int page;
/**
* 每页条数 默认10条
*/
private int limit = 10;
/*****流动人口表******/
/**
* 性别(0 女 1 男)
*/
private String gender;
/**
* 电话号码
*/
private String phoneNumber;
/**
* qq
*/
private String qq;
/**
* 微信
*/
private String weixin;
/**
* 邮箱
*/
private String email;
/**
* 所属工作站
*/
private String workStation;
/**
* 姓名
*/
private String floatingName;
/**
* 身份证号
*/
private String idNumber;
/**
* 随身物品
*/
private String personalEffects;
/**
* 个体特征
*/
private String personalFeature;
/**
* 流入时间
*/
// private Date inflowTime;
private String inflowTime;
/**
* 流出时间
*/
// private Date outflowTime;
private String outflowTime;
/**
* 流动原因
*/
private String flowReason;
/**
* 流出去向
*/
private String outflowTo;
/**
* 照片,多张照片逗号分割
*/
private String photographs;
/**
* 户籍住址
*/
private String registerAddress;
/**
* 前科记录
*/
private String criminalRecord;
/**
* 活动轨迹
*/
private String actionTrack;
/**
* 工作岗位或单位
*/
private String workCompany;
/**
* 是否录入流口平台,0-否;1-是
*/
private Integer ifInput;
/**
* 流动人口类型(1-出租、2-建筑工地人员,3-企业单位)
*/
private Integer floatingPopulationType;
/**
* 流出或者流入类型(1-流入;2-流出)
*/
private Integer flowWay;
/**
* 数据登记时间
*/
// private Date inputTime;
private String inputTime;
/**
* 数据登记人 1代表从微信端录入 2代表从警察直接录入
*/
private String operator;
/**
* 登录用户id(操作人)
*/
private String userId;
/**
* 警员id
*/
private String policeId;
/**
* 编号
*/
private String number;
/*****审核表******/
/**
* 流动人口业务表id
*/
private String personFlowId;
/**
* 受理编号
*/
private String acceptNumber;
/**
* 审核状态
*/
private Integer approvalStatus;
/**
* 是否提交上级,0-否;1-是
*/
private Integer ifSubmitSuperior;
/**
* 审核意见
*/
private String approvalSuggestion;
/**
* 预约日期(保留字段,目前不用)
*/
private String appointmentDate;
/**
* 审核时间
*/
// private Date approvalTime;
private String approvalTime;
/**
* 留言
*/
private String leaveMessage;
/**
* 红包金额
*/
private String redPacketMoney;
public String getRedPacketMoney() {
return redPacketMoney;
}
public void setRedPacketMoney(String redPacketMoney) {
this.redPacketMoney = redPacketMoney;
}
public String getWeixinId() {
return weixinId;
}
public void setWeixinId(String weixinId) {
this.weixinId = weixinId;
}
public String getLeaveMessage() {
return leaveMessage;
}
public void setLeaveMessage(String leaveMessage) {
this.leaveMessage = leaveMessage;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getInflowTime() {
return inflowTime;
}
public void setInflowTime(String inflowTime) {
this.inflowTime = inflowTime;
}
public String getOutflowTime() {
return outflowTime;
}
public void setOutflowTime(String outflowTime) {
this.outflowTime = outflowTime;
}
public String getInputTime() {
return inputTime;
}
public void setInputTime(String inputTime) {
this.inputTime = inputTime;
}
public String getApprovalTime() {
return approvalTime;
}
public void setApprovalTime(String approvalTime) {
this.approvalTime = approvalTime;
}
public String getPersonFlowId() {
return personFlowId;
}
public void setPersonFlowId(String personFlowId) {
this.personFlowId = personFlowId;
}
public String getAcceptNumber() {
return acceptNumber;
}
public void setAcceptNumber(String acceptNumber) {
this.acceptNumber = acceptNumber;
}
public Integer getApprovalStatus() {
return approvalStatus;
}
public void setApprovalStatus(Integer approvalStatus) {
this.approvalStatus = approvalStatus;
}
public Integer getIfSubmitSuperior() {
return ifSubmitSuperior;
}
public void setIfSubmitSuperior(Integer ifSubmitSuperior) {
this.ifSubmitSuperior = ifSubmitSuperior;
}
public String getApprovalSuggestion() {
return approvalSuggestion;
}
public void setApprovalSuggestion(String approvalSuggestion) {
this.approvalSuggestion = approvalSuggestion;
}
public String getAppointmentDate() {
return appointmentDate;
}
public void setAppointmentDate(String appointmentDate) {
this.appointmentDate = appointmentDate;
}
public InputPersonFlow() {
super();
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getXzqhmc() {
return xzqhmc;
}
public void setXzqhmc(String xzqhmc) {
this.xzqhmc = xzqhmc;
}
public String getJlxmc() {
return jlxmc;
}
public void setJlxmc(String jlxmc) {
this.jlxmc = jlxmc;
}
public String getMphmc() {
return mphmc;
}
public void setMphmc(String mphmc) {
this.mphmc = mphmc;
}
public String getMphhz() {
return mphhz;
}
public void setMphhz(String mphhz) {
this.mphhz = mphhz;
}
public String getLphmc() {
return lphmc;
}
public void setLphmc(String lphmc) {
this.lphmc = lphmc;
}
public String getLphhz() {
return lphhz;
}
public void setLphhz(String lphhz) {
this.lphhz = lphhz;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getMpdm() {
return mpdm;
}
public void setMpdm(String mpdm) {
this.mpdm = mpdm;
}
public String getDyhmc() {
return dyhmc;
}
public void setDyhmc(String dyhmc) {
this.dyhmc = dyhmc;
}
public String getDyhhz() {
return dyhhz;
}
public void setDyhhz(String dyhhz) {
this.dyhhz = dyhhz;
}
public String getChmc() {
return chmc;
}
public void setChmc(String chmc) {
this.chmc = chmc;
}
public String getChhz() {
return chhz;
}
public void setChhz(String chhz) {
this.chhz = chhz;
}
public String getHhmc() {
return hhmc;
}
public void setHhmc(String hhmc) {
this.hhmc = hhmc;
}
public String getHhhz() {
return hhhz;
}
public void setHhhz(String hhhz) {
this.hhhz = hhhz;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getWeixin() {
return weixin;
}
public void setWeixin(String weixin) {
this.weixin = weixin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPoliceStation() {
return policeStation;
}
public void setPoliceStation(String policeStation) {
this.policeStation = policeStation;
}
public String getPoliceOffice() {
return policeOffice;
}
public void setPoliceOffice(String policeOffice) {
this.policeOffice = policeOffice;
}
public String getWorkStation() {
return workStation;
}
public void setWorkStation(String workStation) {
this.workStation = workStation;
}
public String getFloatingName() {
return floatingName;
}
public void setFloatingName(String floatingName) {
this.floatingName = floatingName;
}
public String getIdNumber() {
return idNumber;
}
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
public String getPersonalEffects() {
return personalEffects;
}
public void setPersonalEffects(String personalEffects) {
this.personalEffects = personalEffects;
}
public String getPersonalFeature() {
return personalFeature;
}
public void setPersonalFeature(String personalFeature) {
this.personalFeature = personalFeature;
}
public String getFlowReason() {
return flowReason;
}
public void setFlowReason(String flowReason) {
this.flowReason = flowReason;
}
public String getOutflowTo() {
return outflowTo;
}
public void setOutflowTo(String outflowTo) {
this.outflowTo = outflowTo;
}
public String getPhotographs() {
return photographs;
}
public void setPhotographs(String photographs) {
this.photographs = photographs;
}
public String getRegisterAddress() {
return registerAddress;
}
public void setRegisterAddress(String registerAddress) {
this.registerAddress = registerAddress;
}
public String getCriminalRecord() {
return criminalRecord;
}
public void setCriminalRecord(String criminalRecord) {
this.criminalRecord = criminalRecord;
}
public String getActionTrack() {
return actionTrack;
}
public void setActionTrack(String actionTrack) {
this.actionTrack = actionTrack;
}
public String getWorkCompany() {
return workCompany;
}
public void setWorkCompany(String workCompany) {
this.workCompany = workCompany;
}
public Integer getIfInput() {
return ifInput;
}
public void setIfInput(Integer ifInput) {
this.ifInput = ifInput;
}
public Integer getFloatingPopulationType() {
return floatingPopulationType;
}
public void setFloatingPopulationType(Integer floatingPopulationType) {
this.floatingPopulationType = floatingPopulationType;
}
public Integer getFlowWay() {
return flowWay;
}
public void setFlowWay(Integer flowWay) {
this.flowWay = flowWay;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPoliceId() {
return policeId;
}
public void setPoliceId(String policeId) {
this.policeId = policeId;
}
public String getTimeFlog() {
return timeFlog;
}
public void setTimeFlog(String timeFlog) {
this.timeFlog = timeFlog;
}
/**
* 拼接七段地址
* @return
*/
public String getAddress() {
StringBuffer result = new StringBuffer();
// 行政区划名称
result.append(xzqhmc);
// 街路巷名称
result.append(jlxmc);
// 门牌号名称
result.append(mphmc);
// 门牌号后缀
result.append(mphhz);
// 楼牌号名称
result.append(lphmc);
// 楼牌号后缀
result.append(lphhz);
//单元号名称
result.append(dyhmc);
//单元号后缀
result.append(dyhhz);
//层号名称
result.append(chmc);
//层号后缀
result.append(chhz);
//户号名称
result.append(hhmc);
//户号后缀
result.append(hhhz);
return result.toString() ;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getOperation() {
return operation;
}
public void setOperation(Integer operation) {
this.operation = operation;
}
public String getPoliceNumber() {
return policeNumber;
}
public void setPoliceNumber(String policeNumber) {
this.policeNumber = policeNumber;
}
@Override
public String toString() {
return "InputPersonFlow{" +
"id=" + id +
", operation=" + operation +
", policeNumber='" + policeNumber + '\'' +
", xzqhmc='" + xzqhmc + '\'' +
", jlxmc='" + jlxmc + '\'' +
", mphmc='" + mphmc + '\'' +
", mphhz='" + mphhz + '\'' +
", lphmc='" + lphmc + '\'' +
", lphhz='" + lphhz + '\'' +
", dyhmc='" + dyhmc + '\'' +
", dyhhz='" + dyhhz + '\'' +
", chmc='" + chmc + '\'' +
", chhz='" + chhz + '\'' +
", hhmc='" + hhmc + '\'' +
", hhhz='" + hhhz + '\'' +
", address='" + address + '\'' +
", mpdm='" + mpdm + '\'' +
", page=" + page +
", limit=" + limit +
", gender='" + gender + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
", qq='" + qq + '\'' +
", weixin='" + weixin + '\'' +
", email='" + email + '\'' +
", policeStation='" + policeStation + '\'' +
", policeOffice='" + policeOffice + '\'' +
", workStation='" + workStation + '\'' +
", floatingName='" + floatingName + '\'' +
", idNumber=" + idNumber +
", personalEffects='" + personalEffects + '\'' +
", personalFeature='" + personalFeature + '\'' +
", inflowTime=" + inflowTime +
", outflowTime=" + outflowTime +
", flowReason='" + flowReason + '\'' +
", outflowTo='" + outflowTo + '\'' +
", photographs='" + photographs + '\'' +
", registerAddress='" + registerAddress + '\'' +
", criminalRecord='" + criminalRecord + '\'' +
", actionTrack='" + actionTrack + '\'' +
", workCompany='" + workCompany + '\'' +
", ifInput=" + ifInput +
", floatingPopulationType=" + floatingPopulationType +
", flowWay=" + flowWay +
", inputTime=" + inputTime +
", operator=" + operator +
", userId=" + userId +
", policeId=" + policeId +
'}';
}
}
|
package com.tencent.mm.plugin.scanner.util;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.widget.Toast;
import com.tencent.mm.R;
import com.tencent.mm.aa.q;
import com.tencent.mm.ab.l;
import com.tencent.mm.ac.d.b;
import com.tencent.mm.ac.z;
import com.tencent.mm.bg.d;
import com.tencent.mm.g.a.lo;
import com.tencent.mm.g.a.op;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.modelsimple.u;
import com.tencent.mm.network.ab;
import com.tencent.mm.plugin.af.a.c.a;
import com.tencent.mm.plugin.messenger.a.f;
import com.tencent.mm.plugin.sns.i$l;
import com.tencent.mm.pluginsdk.ui.j;
import com.tencent.mm.pluginsdk.wallet.h;
import com.tencent.mm.protocal.c.bja;
import com.tencent.mm.protocal.c.bjp;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public final class e implements com.tencent.mm.ab.e, a {
public String appId;
public int bJt;
public String bJw;
public String bhd;
private ProgressDialog hpV = null;
public int iVT;
public String imagePath;
private Activity mActivity;
private int mMR;
private String mMS;
private Bundle mMT;
a mMU = null;
private Map<l, Integer> mMV = new HashMap();
public e() {
onResume();
}
public final void a(Activity activity, String str, int i, int i2, int i3, a aVar, Bundle bundle) {
x.i("MicroMsg.QBarStringHandler", "deal QBarString %s, source:%d, codeType: %s, codeVersion: %s", new Object[]{str, Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3)});
this.mActivity = activity;
this.mMR = i;
this.mMS = str;
this.mMU = aVar;
this.mMT = bundle;
if (bi.oW(str)) {
x.e("MicroMsg.QBarStringHandler", "qbarstring is null or nil");
} else if (au.DF().Lg() == 0) {
Toast.makeText(activity, activity.getString(R.l.fmt_iap_err), 0).show();
if (this.mMU != null) {
this.mMU.o(0, null);
}
} else {
String str2 = "";
if (str.startsWith("weixin://qr/")) {
str2 = str.substring(12) + "@qr";
} else if (str.startsWith("http://weixin.qq.com/r/")) {
str2 = str.substring(23) + "@qr";
}
if (bi.oW(str2)) {
x.d("MicroMsg.QBarStringHandler", "qbarString: %s, auth native: %s, remittance: %s", new Object[]{str, Boolean.valueOf(true), Boolean.valueOf(true)});
int vE;
int vc;
int vc2;
op opVar;
if (str.startsWith("weixin://wxpay/bizpayurl")) {
x.i("MicroMsg.QBarStringHandler", "do native pay");
vE = vE(this.mMR);
vc = vc(vE);
lo loVar = new lo();
loVar.bVS.url = str;
loVar.bVS.bVU = vc;
loVar.bVS.scene = vE;
loVar.bVS.context = this.mActivity;
if (vc == 13) {
x.d("MicroMsg.QBarStringHandler", "add source and sourceType");
loVar.bVS.bhd = this.bhd;
loVar.bVS.bJt = this.bJt;
}
loVar.bJX = new 1(this, loVar);
com.tencent.mm.sdk.b.a.sFg.a(loVar, Looper.myLooper());
new ag(Looper.getMainLooper()).postDelayed(new 4(this), 200);
return;
} else if (str.startsWith("https://wx.tenpay.com/f2f") || str.startsWith("wxp://f2f")) {
if (this.mMU != null) {
this.mMU.o(5, null);
}
h.a(this.mActivity, 1, str, vc(vE(this.mMR)), null);
if (this.mMU != null) {
this.mMU.o(3, null);
return;
}
return;
} else if (str.startsWith("wxp://wbf2f")) {
if (this.mMU != null) {
this.mMU.o(5, null);
}
h.a(this.mActivity, 6, str, vc(vE(this.mMR)), null);
if (this.mMU != null) {
this.mMU.o(3, null);
return;
}
return;
} else if (i2 == 22 && str.startsWith("m")) {
x.d("MicroMsg.QBarStringHandler", "go to reward");
if (this.mMU != null) {
this.mMU.o(5, null);
}
vc2 = vc(vE(this.mMR));
str2 = "";
if (bundle != null) {
str2 = bundle.getString("stat_url", "");
}
vc = 1;
if (this.iVT == 37) {
vc = 2;
} else if (this.iVT == 38) {
vc = 3;
} else if (this.iVT == 40) {
vc = 4;
}
h.a(this.mActivity, str, vc2, str2, vc);
if (this.mMU != null) {
this.mMU.o(3, null);
return;
}
return;
} else if (str.startsWith("https://payapp.weixin.qq.com/qr/")) {
x.d("MicroMsg.QBarStringHandler", "f2f pay material");
if (this.mMU != null) {
this.mMU.o(5, null);
}
vE = vE(this.mMR);
vc = vc(vE);
opVar = new op();
opVar.bZx.bZz = str;
opVar.bZx.scene = vE;
opVar.bZx.type = 0;
opVar.bZx.YC = new WeakReference(this.mActivity);
opVar.bZx.bJX = new 5(this, opVar, vc);
com.tencent.mm.sdk.b.a.sFg.m(opVar);
return;
} else if (i2 == 22 && str.startsWith("n")) {
x.d("MicroMsg.QBarStringHandler", "qr reward pay material");
if (this.mMU != null) {
this.mMU.o(5, null);
}
String str3 = "";
if (bundle != null) {
str3 = bundle.getString("stat_url", "");
}
int vE2 = vE(this.mMR);
int vc3 = vc(vE2);
opVar = new op();
opVar.bZx.bZz = str;
opVar.bZx.scene = vE2;
opVar.bZx.type = 1;
opVar.bZx.YC = new WeakReference(this.mActivity);
opVar.bZx.bJX = new 6(this, opVar, vc3, str3, vE2);
com.tencent.mm.sdk.b.a.sFg.m(opVar);
return;
} else if (str.startsWith("wxhb://f2f")) {
x.i("MicroMsg.QBarStringHandler", "scan f2f hb url");
if (i2 == 19) {
if (this.mMU != null) {
this.mMU.o(5, null);
}
Intent intent = new Intent();
intent.putExtra("key_share_url", str);
d.b(this.mActivity, "luckymoney", ".f2f.ui.LuckyMoneyF2FReceiveUI", intent, 1);
return;
}
return;
} else {
String str4 = this.appId;
x.i("MicroMsg.QBarStringHandler", "getA8Key text:%s, mQBarStringSource: %s, sceneValue: %s", new Object[]{str, Integer.valueOf(this.mMR), Integer.valueOf(this.iVT > 0 ? this.iVT : vE(this.mMR))});
com.tencent.mm.modelsimple.h hVar = new com.tencent.mm.modelsimple.h(str, vc2, i2, i3, str4, (int) System.currentTimeMillis(), new byte[0]);
this.mMV.put(hVar, Integer.valueOf(1));
au.DF().a(hVar, 0);
if (this.hpV != null) {
this.hpV.dismiss();
}
activity.getString(R.l.app_tip);
this.hpV = com.tencent.mm.ui.base.h.a(activity, activity.getString(R.l.qrcode_scan_default), true, new 9(this, hVar));
if (this.mMU != null) {
this.mMU.o(5, null);
return;
}
return;
}
}
a(activity, i, str2, false);
}
}
private static int vc(int i) {
if (i == 30 || i == 37 || i == 38 || i == 40) {
return 13;
}
if (i == 4 || i == 47) {
return 12;
}
if (i == 34) {
return 24;
}
return 0;
}
public final void bsY() {
x.i("MicroMsg.QBarStringHandler", "cancel Deal");
this.mMS = null;
this.mActivity = null;
onPause();
}
public final void onResume() {
x.i("MicroMsg.QBarStringHandler", "onResume");
au.DF().a(i$l.AppCompatTheme_ratingBarStyle, this);
au.DF().a(233, this);
au.DF().a(666, this);
au.DF().a(372, this);
}
public final void onPause() {
x.i("MicroMsg.QBarStringHandler", "onPause");
au.DF().b(i$l.AppCompatTheme_ratingBarStyle, this);
au.DF().b(233, this);
au.DF().b(666, this);
au.DF().b(372, this);
}
private void a(Activity activity, int i, String str, boolean z) {
int i2 = 2;
x.i("MicroMsg.QBarStringHandler", "start search contact %s", new Object[]{str});
if (i != 2) {
i2 = 1;
}
f fVar = new f(str, i2, 5, z);
this.mMV.put(fVar, Integer.valueOf(1));
au.DF().a(fVar, 0);
activity.getString(R.l.app_tip);
this.hpV = com.tencent.mm.ui.base.h.b(activity, activity.getString(R.l.scan_loading_tip), new 7(this, fVar));
}
private static int vE(int i) {
if (i == 1) {
return 34;
}
if (i == 0) {
return 4;
}
if (i == 3) {
return 42;
}
return 30;
}
public final void a(int i, int i2, String str, l lVar) {
x.i("MicroMsg.QBarStringHandler", "onSceneEnd: errType = [%s] errCode = [%s] errMsg = [%s]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
String str2;
if (lVar == null) {
String str3 = "MicroMsg.QBarStringHandler";
str2 = "onSceneEnd() scene is null [%s]";
Object[] objArr = new Object[1];
objArr[0] = Boolean.valueOf(lVar == null);
x.e(str3, str2, objArr);
if (this.mMU != null) {
this.mMU.o(2, null);
return;
}
return;
}
if (!this.mMV.containsKey(lVar)) {
if (lVar instanceof u) {
x.e("MicroMsg.QBarStringHandler", "emotion scan scene");
} else {
x.e("MicroMsg.QBarStringHandler", "not my scene, don't care it");
return;
}
}
this.mMV.remove(lVar);
if (this.hpV != null) {
this.hpV.dismiss();
this.hpV = null;
}
com.tencent.mm.modelsimple.h hVar;
if (lVar.getType() == 372 && i == 4 && i2 == -2034) {
hVar = new com.tencent.mm.modelsimple.h(((com.tencent.mm.openim.b.e) lVar).eux, null, 50, 0, new byte[0]);
g.Ek();
g.Eh().dpP.a(hVar, 0);
this.mMV.put(hVar, Integer.valueOf(1));
} else if (i == 4 && i2 == -4) {
com.tencent.mm.ui.base.h.a(this.mActivity, R.l.qrcode_no_user_tip, R.l.app_tip, new 10(this));
} else {
Object obj;
switch (i) {
case 1:
if (au.DF().Lh()) {
au.DF().getNetworkServerIp();
new StringBuilder().append(i2);
} else if (ab.bU(this.mActivity)) {
j.eY(this.mActivity);
} else {
Toast.makeText(this.mActivity, this.mActivity.getString(R.l.fmt_http_err, new Object[]{Integer.valueOf(1), Integer.valueOf(i2)}), 1).show();
}
obj = 1;
break;
case 2:
Toast.makeText(this.mActivity, this.mActivity.getString(R.l.fmt_iap_err, new Object[]{Integer.valueOf(2), Integer.valueOf(i2)}), 1).show();
obj = 1;
break;
default:
obj = null;
break;
}
Bundle bundle;
String str4;
if (obj != null) {
if (this.mMU != null) {
this.mMU.o(1, null);
}
} else if (i == 4 && i2 == -2004) {
com.tencent.mm.ui.base.h.i(this.mActivity, R.l.qrcode_ban_by_expose, R.l.app_tip);
if (this.mMU != null) {
this.mMU.o(1, null);
}
} else if (i != 0 || i2 != 0) {
Toast.makeText(this.mActivity, this.mActivity.getString(R.l.fmt_search_err, new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}), 0).show();
if (this.mMU != null) {
this.mMU.o(1, null);
}
} else if (lVar.getType() == i$l.AppCompatTheme_ratingBarStyle) {
f fVar = (f) lVar;
if (!fVar.lbK) {
bja bcS = fVar.bcS();
if (com.tencent.mm.storage.ab.Dk(bcS.rTe) && bcS.rTl != null && !bi.oW(bcS.rTl.eJW) && com.tencent.mm.modelappbrand.a.jh(bcS.rTl.eJW)) {
int vE = this.iVT > 0 ? this.iVT : vE(this.mMR);
x.i("MicroMsg.QBarStringHandler", "getA8Key text:%s, mQBarStringSource: %s, sceneValue: %s", new Object[]{this.mMS, Integer.valueOf(this.mMR), Integer.valueOf(vE)});
hVar = new com.tencent.mm.modelsimple.h(this.mMS, null, 43, 0, new byte[0]);
this.mMV.put(hVar, Integer.valueOf(1));
au.DF().a(hVar, 0);
if (this.hpV != null) {
this.hpV.dismiss();
}
Context context = this.mActivity;
this.mActivity.getString(R.l.app_tip);
this.hpV = com.tencent.mm.ui.base.h.a(context, this.mActivity.getString(R.l.qrcode_scan_default), true, new 3(this, hVar));
obj = 1;
if (obj == null) {
bja bcS2 = ((f) lVar).bcS();
str2 = com.tencent.mm.platformtools.ab.a(bcS2.rvi);
x.d("MicroMsg.QBarStringHandler", "handle search contact result, username:" + bcS2.rvi);
q.Kp().g(str2, com.tencent.mm.platformtools.ab.a(bcS2.rcn));
if (this.hpV != null && this.hpV.isShowing()) {
x.d("MicroMsg.QBarStringHandler", "tip dialog dismiss");
this.hpV.dismiss();
}
if (bi.oV(str2).length() > 0) {
au.HU();
com.tencent.mm.storage.ab Yg = c.FR().Yg(str2);
if (Yg != null && com.tencent.mm.l.a.gd(Yg.field_type) && Yg.ckW()) {
com.tencent.mm.ac.d kA = z.MY().kA(str2);
kA.bG(false);
b bVar = kA.dKP;
if (bVar.dKT != null) {
bVar.dLj = bVar.dKT.optInt("ScanQRCodeType", 0);
}
if (!((bVar.dLj == 1 ? 1 : null) == null || kA.LY())) {
Intent intent = new Intent();
intent.putExtra("Chat_User", str2);
intent.putExtra("finish_direct", true);
com.tencent.mm.plugin.scanner.b.ezn.e(intent, this.mActivity);
obj = 1;
}
}
vE = bsZ();
Intent intent2 = new Intent();
com.tencent.mm.pluginsdk.ui.tools.c.a(intent2, bcS2, vE);
if (!(Yg == null || com.tencent.mm.l.a.gd(Yg.field_type))) {
intent2.putExtra("Contact_IsLBSFriend", true);
}
if ((bcS2.rTe & 8) > 0) {
com.tencent.mm.plugin.report.service.h.mEJ.k(10298, str2 + "," + vE);
}
if (this.mActivity != null) {
com.tencent.mm.plugin.scanner.b.ezn.d(intent2, this.mActivity);
com.tencent.mm.plugin.report.service.h hVar2 = com.tencent.mm.plugin.report.service.h.mEJ;
Object[] objArr2 = new Object[6];
objArr2[0] = Integer.valueOf(com.tencent.mm.storage.ab.Dk(bcS2.rTe) ? 0 : 1);
objArr2[1] = Integer.valueOf(this.bJt);
objArr2[2] = Integer.valueOf(this.mMR);
objArr2[3] = this.imagePath;
objArr2[4] = this.mMS;
objArr2[5] = bi.oV(this.bJw);
hVar2.h(14268, objArr2);
}
obj = 1;
} else {
if (this.mActivity != null) {
Toast.makeText(this.mActivity, R.l.scan_search_contact_fail, 0).show();
}
obj = null;
}
if (obj != null) {
if (this.mMU != null) {
bundle = new Bundle();
bundle.putString("geta8key_fullurl", com.tencent.mm.platformtools.ab.a(((f) lVar).bcS().rvi));
bundle.putInt("geta8key_action_code", 4);
this.mMU.o(3, bundle);
}
} else if (this.mMU != null) {
this.mMU.o(1, null);
}
}
}
}
obj = null;
if (obj == null) {
bja bcS22 = ((f) lVar).bcS();
str2 = com.tencent.mm.platformtools.ab.a(bcS22.rvi);
x.d("MicroMsg.QBarStringHandler", "handle search contact result, username:" + bcS22.rvi);
q.Kp().g(str2, com.tencent.mm.platformtools.ab.a(bcS22.rcn));
if (this.hpV != null && this.hpV.isShowing()) {
x.d("MicroMsg.QBarStringHandler", "tip dialog dismiss");
this.hpV.dismiss();
}
if (bi.oV(str2).length() > 0) {
au.HU();
com.tencent.mm.storage.ab Yg2 = c.FR().Yg(str2);
if (Yg2 != null && com.tencent.mm.l.a.gd(Yg2.field_type) && Yg2.ckW()) {
com.tencent.mm.ac.d kA2 = z.MY().kA(str2);
kA2.bG(false);
b bVar2 = kA2.dKP;
if (bVar2.dKT != null) {
bVar2.dLj = bVar2.dKT.optInt("ScanQRCodeType", 0);
}
if (!((bVar2.dLj == 1 ? 1 : null) == null || kA2.LY())) {
Intent intent3 = new Intent();
intent3.putExtra("Chat_User", str2);
intent3.putExtra("finish_direct", true);
com.tencent.mm.plugin.scanner.b.ezn.e(intent3, this.mActivity);
obj = 1;
}
}
vE = bsZ();
Intent intent22 = new Intent();
com.tencent.mm.pluginsdk.ui.tools.c.a(intent22, bcS22, vE);
if (!(Yg2 == null || com.tencent.mm.l.a.gd(Yg2.field_type))) {
intent22.putExtra("Contact_IsLBSFriend", true);
}
if ((bcS22.rTe & 8) > 0) {
com.tencent.mm.plugin.report.service.h.mEJ.k(10298, str2 + "," + vE);
}
if (this.mActivity != null) {
com.tencent.mm.plugin.scanner.b.ezn.d(intent22, this.mActivity);
com.tencent.mm.plugin.report.service.h hVar22 = com.tencent.mm.plugin.report.service.h.mEJ;
Object[] objArr22 = new Object[6];
objArr22[0] = Integer.valueOf(com.tencent.mm.storage.ab.Dk(bcS22.rTe) ? 0 : 1);
objArr22[1] = Integer.valueOf(this.bJt);
objArr22[2] = Integer.valueOf(this.mMR);
objArr22[3] = this.imagePath;
objArr22[4] = this.mMS;
objArr22[5] = bi.oV(this.bJw);
hVar22.h(14268, objArr22);
}
obj = 1;
} else {
if (this.mActivity != null) {
Toast.makeText(this.mActivity, R.l.scan_search_contact_fail, 0).show();
}
obj = null;
}
if (obj != null) {
if (this.mMU != null) {
bundle = new Bundle();
bundle.putString("geta8key_fullurl", com.tencent.mm.platformtools.ab.a(((f) lVar).bcS().rvi));
bundle.putInt("geta8key_action_code", 4);
this.mMU.o(3, bundle);
}
} else if (this.mMU != null) {
this.mMU.o(1, null);
}
}
} else if (lVar.getType() == 372) {
bjp bjp = ((com.tencent.mm.openim.b.e) lVar).euw;
str4 = bjp.hbL;
x.d("MicroMsg.QBarStringHandler", "handle search openim contact result, username:" + str4);
if (this.hpV != null && this.hpV.isShowing()) {
x.d("MicroMsg.QBarStringHandler", "tip dialog dismiss");
this.hpV.dismiss();
}
if (bi.oV(str4).length() > 0) {
au.HU();
com.tencent.mm.storage.ab Yg3 = c.FR().Yg(str4);
int bsZ = bsZ();
Intent intent4 = new Intent();
com.tencent.mm.pluginsdk.ui.tools.c.a(intent4, bjp, bsZ);
if (!(Yg3 == null || com.tencent.mm.l.a.gd(Yg3.field_type))) {
intent4.putExtra("Contact_IsLBSFriend", true);
}
if (this.mActivity != null) {
com.tencent.mm.plugin.scanner.b.ezn.d(intent4, this.mActivity);
com.tencent.mm.plugin.report.service.h.mEJ.h(14268, new Object[]{Integer.valueOf(2), Integer.valueOf(this.bJt), Integer.valueOf(this.mMR), this.imagePath, this.mMS, bi.oV(this.bJw)});
}
obj = 1;
} else {
if (this.mActivity != null) {
Toast.makeText(this.mActivity, R.l.scan_search_contact_fail, 0).show();
}
obj = null;
}
if (obj != null) {
if (this.mMU != null) {
bundle = new Bundle();
bundle.putString("geta8key_fullurl", bjp.hbL);
bundle.putInt("geta8key_action_code", 4);
this.mMU.o(3, bundle);
}
} else if (this.mMU != null) {
this.mMU.o(1, null);
}
} else if (lVar.getType() == 233) {
int i3;
String QL = ((com.tencent.mm.modelsimple.h) lVar).QL();
Bundle bundle2 = new Bundle();
bundle2.putString("geta8key_fullurl", QL);
bundle2.putInt("geta8key_action_code", ((com.tencent.mm.modelsimple.h) lVar).QN());
if (this.mMU != null) {
this.mMU.o(4, bundle2);
}
if (this.iVT > 0) {
i3 = this.iVT;
} else {
i3 = vE(this.mMR);
}
x.i("MicroMsg.QBarStringHandler", "handleGetA8KeyRedirect, sceneValue: %s", new Object[]{Integer.valueOf(i3)});
boolean a = com.tencent.mm.plugin.af.a.c.a(this, (com.tencent.mm.modelsimple.h) lVar, new 11(this), this.mMS, i3, this.mMR, new 2(this), this.mMT);
if (!a && ((com.tencent.mm.modelsimple.h) lVar).QN() == 4) {
a(this.mActivity, this.mMR, QL, true);
} else if (a || ((com.tencent.mm.modelsimple.h) lVar).QN() != 29) {
x.i("MicroMsg.QBarStringHandler", "scene geta8key, redirect result = [%s]", new Object[]{Boolean.valueOf(a)});
if (!a && this.mMU != null) {
this.mMU.o(1, null);
}
} else {
Context context2 = this.mActivity;
x.i("MicroMsg.QBarStringHandler", "start search contact %s", new Object[]{QL});
com.tencent.mm.openim.b.e eVar = new com.tencent.mm.openim.b.e(QL);
this.mMV.put(eVar, Integer.valueOf(1));
au.DF().a(eVar, 0);
context2.getString(R.l.app_tip);
this.hpV = com.tencent.mm.ui.base.h.b(context2, context2.getString(R.l.scan_loading_tip), new 8(this, eVar));
}
} else if (lVar.getType() != 666) {
} else {
if (i != 0 || i2 != 0) {
x.i("MicroMsg.QBarStringHandler", "jump emotion detail failed.");
} else if (lVar instanceof u) {
x.d("MicroMsg.QBarStringHandler", "[oneliang]NetSceneScanEmoji productId:%s", new Object[]{((u) lVar).Rt().rem});
Intent intent5 = new Intent();
intent5.putExtra("extra_id", str4);
intent5.putExtra("preceding_scence", 11);
intent5.putExtra("download_entrance_scene", 14);
d.b(this.mActivity, "emoji", ".ui.EmojiStoreDetailUI", intent5);
x.i("MicroMsg.QBarStringHandler", "[oneliang]NetSceneScanEmoji onSceneEnd.");
if (this.mMU != null) {
this.mMU.o(3, null);
}
}
}
}
}
private int bsZ() {
switch (this.mMR) {
case 1:
return 45;
default:
return 30;
}
}
public final Context getContext() {
return this.mActivity;
}
public final void hk(boolean z) {
if (z) {
if (this.mMU != null) {
this.mMU.o(1, null);
}
} else if (this.mMU != null) {
this.mMU.o(3, null);
}
}
}
|
import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.math3.distribution.ExponentialDistribution;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpChannel;
public class App
{
private long interRequestDelayMean;
private DMEService dmeService;
private long meanCsExecutionTime;
private int appId;
private ExponentialDistribution expInterReqDelay;
private ExponentialDistribution expCsExecTime;
private InetSocketAddress testerAddress;
private SctpChannel testerChannel = null;
private static final String CS_EVENT = "C";
private static final String CS_EVENT_DONE = "L";
private static final String ACK = "A";
private static final int MESSAGE_SIZE = 200;
private boolean testing;
private static final String END_TAG = "!END";
public App(long ird, long cset, DMEService dmeServ, int appId)
{
interRequestDelayMean = ird;
dmeService = dmeServ;
meanCsExecutionTime = cset;
this.appId = appId;
testing = false;
expInterReqDelay = new ExponentialDistribution(interRequestDelayMean);
expCsExecTime = new ExponentialDistribution(meanCsExecutionTime);
}
public void setTesting()
{
testing = true;
}
public void setUpNetworking(int testerPort, String testerHost)
{
boolean connected = false;
testerAddress = new InetSocketAddress(testerHost, testerPort);
SocketAddress socketAddress = testerAddress;
//Open a channel. NOT SERVER CHANNEL
connected = false;
testerChannel = null;
//waiting till server is up
while(!connected)
{
try
{
testerChannel = SctpChannel.open();
//Bind the channel's socket to a local port. Again this is not a server bind
//sctpChannel.bind(new InetSocketAddress(neighbor.getNeighborAddress().getPort()));
try
{
testerChannel.bind(null);
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
//Connect the channel's socket to the remote server
try
{
testerChannel.connect(socketAddress);
connected = true;
}
catch(ConnectException ce)
{
connected = false;
try
{
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}
public void start(int numberOfReq)
{
ByteBuffer byteBuffer = ByteBuffer.allocate(MESSAGE_SIZE);
int requestNo = 0;
long interRequestDelay, csExecutionTime;
Message msg;
MessageInfo messageInfo;
int[] vectorClock;
for(int i = 0; i < numberOfReq; i++)
{
boolean res = dmeService.csEnter(appId, requestNo);
if(res)
{
/*
*
* Testing
*/
if(testing)
{
dmeService.sendVectorClock(requestNo);
vectorClock = dmeService.getVectorClock();
String vectorClockStr = Arrays.toString(vectorClock);
String str;
msg = new Message(appId, CS_EVENT, i, Integer.MIN_VALUE);
str = msg.toString();
str = msg.stripMessage(str);
str = str + "~" + vectorClockStr + END_TAG;
/*
*
* Testing
*/
messageInfo = MessageInfo.createOutgoing(null,0);
byteBuffer.clear();
byteBuffer.put(str.getBytes());
byteBuffer.flip();
try
{
testerChannel.send(byteBuffer,messageInfo);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byteBuffer.clear();
messageInfo = testerChannel.receive(byteBuffer,null,null);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
csExecutionTime = Math.round(expCsExecTime.sample());
//doing some work
Thread.sleep(csExecutionTime);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
dmeService.csLeave(appId, requestNo++);
interRequestDelay = Math.round(expInterReqDelay.sample());
try
{
Thread.sleep(interRequestDelay);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("DONE");
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
long interReqDelay = Long.parseLong(args[1]);
long csExecTime = Long.parseLong(args[2]);
int numberOfReq = Integer.parseInt(args[3]);
int nodeId = Integer.parseInt(args[6]);
int testerPort = Integer.parseInt(args[7]);
String testerHost = args[8];
String testing = args[9];
String nodeLocations = args[4];
String[] locationsArr = nodeLocations.split("#");
HashMap<Integer, String[]> nodeDetails = new HashMap<Integer, String[]>();
int[] nodeIds = new int[N];
for(int i = 0; i < locationsArr.length; i++)
{
int tempNodeId = Integer.parseInt(locationsArr[i].split(" ")[0]);
nodeDetails.put(tempNodeId, locationsArr[i].split(" "));
nodeIds[i] = tempNodeId;
}
String quorumLocations = args[5];
String[] quorumLocationsArr = quorumLocations.split("#");
HashMap<Integer, ArrayList<Integer>> quorumAllSet = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0; i < quorumLocationsArr.length; i++)
{
String[] splitQuorumLocs = quorumLocationsArr[i].split(" ");
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int j = 0; j < splitQuorumLocs.length; j++)
{
temp.add(Integer.parseInt(splitQuorumLocs[j]));
}
quorumAllSet.put(nodeIds[i], temp);
}
ArrayList<Integer> dualQuorumSet = new ArrayList<Integer>();
Iterator it = quorumAllSet.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pair = (Map.Entry)it.next();
ArrayList<Integer> tempArr = (ArrayList<Integer>)pair.getValue();
for(Integer t : tempArr)
{
if(t == nodeId)
{
dualQuorumSet.add((Integer)pair.getKey());
break;
}
}
}
DMEService dmeService = new DMEService(nodeId, nodeDetails, quorumAllSet.get(nodeId), dualQuorumSet, testerPort, N);
if(!quorumAllSet.get(nodeId).isEmpty())
{
App app = new App(interReqDelay, csExecTime, dmeService, nodeId);
if(testing.equalsIgnoreCase("yes"))
{
app.setUpNetworking(testerPort, testerHost);
app.setTesting();
}
app.start(numberOfReq);
}
}
}
|
package Server;
import java.rmi.Remote;
import java.rmi.RemoteException;
import Client.ClientInterface;
import Session.SessionInterface;
/**
* Legt die Methoden des Servers fest, hier nur die Erzeugung einer neuen Sitzung
*/
public interface ServerInterface extends Remote {
/**
* Erzeugt eine neue Session mit dem Namen des Clienten und dem Interface der Clients
* @param name
* @param clientInt
* @return
* @throws RemoteException
*/
public SessionInterface makeSession(String name, ClientInterface clientInt) throws RemoteException;
}
|
package com.app.service;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;
import com.app.model.DiaryEvent;
import com.app.util.ReportDownloadUtil;
public class DownloadService {
public static Scanner sc = new Scanner(System.in);
public static void download(List<DiaryEvent> diaryEvent, int idCount) throws IOException {
System.out.println("Event Date: ");
String inut = sc.nextLine();
String date = inut.replace("/", "");
ReportDownloadUtil.downloadReport(diaryEvent, date, idCount);
}
}
|
package club.eridani.cursa.command.commands;
import club.eridani.cursa.client.ModuleManager;
import club.eridani.cursa.command.CommandBase;
import club.eridani.cursa.common.annotations.Command;
import club.eridani.cursa.utils.ChatUtil;
import java.util.Objects;
/**
* Created by killRED on 2020
* Updated by B_312 on 01/15/21
*/
@Command(command = "toggle",description = "Toggle selected module or HUD.")
public class Toggle extends CommandBase {
@Override
public void onCall(String s, String[] args) {
try {
Objects.requireNonNull(ModuleManager.getModuleByName(args[0])).toggle();
} catch(Exception e) {
ChatUtil.sendNoSpamErrorMessage(getSyntax());
}
}
@Override
public String getSyntax() {
return "toggle <modulename>";
}
} |
///* Doctor.java
// Interface Repository for the Doctor
// Author: Bheka Gumede (218223420)
// Date: 30 July 2021
// */
//package za.ac.cput.Repository;
//
//import za.ac.cput.Entity.Doctor;
//import java.util.Set;
//
//public interface IDoctorRepository extends IRepository<Doctor, String>
//{
// public Set<Doctor> getAll();
//}
|
package com.tencent.mm.plugin.product.b;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.bnx;
import com.tencent.mm.protocal.c.bro;
import com.tencent.mm.protocal.c.brp;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.wallet_core.c.m;
public final class l extends m implements k {
private b diG;
private e diJ;
public String lRk;
public l(bnx bnx, String str) {
a aVar = new a();
aVar.dIG = new bro();
aVar.dIH = new brp();
aVar.uri = "/cgi-bin/micromsg-bin/submitmallorder";
aVar.dIF = 556;
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
bro bro = (bro) this.diG.dID.dIL;
bro.spz = bnx;
bro.spB = str;
}
public final int getType() {
return 556;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.diG, this);
}
public final void e(int i, int i2, String str, q qVar) {
brp brp = (brp) ((b) qVar).dIE.dIL;
if (i == 0 && i2 == 0) {
x.d("MicroMsg.NetSceneMallSubmitMallOrder", "resp.ReqKey " + brp.spA);
this.lRk = brp.spA;
}
x.d("MicroMsg.NetSceneMallSubmitMallOrder", "errCode " + i2 + ", errMsg " + str);
this.diJ.a(i, i2, str, this);
}
}
|
package start.entity;
/**
* @Author: Jason
* @Create: 2020/10/12 20:18
* @Description 异常类
*/
public class UnableToAquireLockException extends RuntimeException{
public UnableToAquireLockException(){};
public UnableToAquireLockException(String message){
super(message);
}
public UnableToAquireLockException(String message, Throwable cause){
super(message,cause);
}
}
|
package com.salesdataanalysis.domain.model.customer;
import static com.google.common.base.Preconditions.checkNotNull;
import com.salesdataanalysis.domain.shared.data.Data;
import com.salesdataanalysis.domain.shared.data.Type;
import com.salesdataanalysis.domain.shared.document.CNPJ;
import com.salesdataanalysis.domain.shared.name.Name;
import jersey.repackaged.com.google.common.base.MoreObjects;
public final class Customer implements Data {
private CNPJ cnpj;
private Name name;
private BusinessArea businessArea;
private Customer(final CNPJ cnpj, final Name name, final BusinessArea businessArea) {
this.cnpj = cnpj;
this.name = name;
this.businessArea = businessArea;
}
public static final Customer of(final CNPJ cnpj, final Name name, final BusinessArea businessArea) {
checkNotNull(cnpj, "CNPJ cannot be null");
checkNotNull(name, "Name cannot be null");
checkNotNull(businessArea, "Business area cannot be null");
return new Customer(cnpj, name, businessArea);
}
@Override
public final String toString() {
return MoreObjects.toStringHelper(this)
.add("cnpj", cnpj)
.add("name", name)
.toString();
}
public final CNPJ getCnpj() {
return cnpj;
}
public final Name getName() {
return name;
}
public final BusinessArea getBusinessArea() {
return businessArea;
}
@Override
public Type getType() {
return Type.CUSTOMER;
}
}
|
package com.craigcorstorphine.topten;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.List;
public class FeedAdapter extends ArrayAdapter {
private static final String TAG = "FeedAdapter";
private final int layoutReasource;
private final LayoutInflater layoutInflater;
private List<FeedEntry> application;
public FeedAdapter(Context context, int resource, List<FeedEntry> application) {
super(context, resource);
this.layoutReasource = resource;
this.layoutInflater = LayoutInflater.from(context);
this.application = application;
}
@Override
public int getCount() {
return application.size();
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(layoutReasource, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// TextView tvName = convertView.findViewById(R.id.tvName);
// TextView tvArtist = convertView.findViewById(R.id.tvArtist);
// TextView tvSummary = convertView.findViewById(R.id.tvSummary);
FeedEntry currentApp = application.get(position);
viewHolder.tvTitle.setText(currentApp.getTitle());
viewHolder.tvLink.setText(currentApp.getLink());
viewHolder.tvDescrition.setText(currentApp.getSummery());
return convertView;
}
private class ViewHolder {
final TextView tvTitle;
final TextView tvLink;
final TextView tvDescrition;
ViewHolder(View v) {
this.tvTitle = v.findViewById(R.id.tvTitle);
this.tvLink = v.findViewById(R.id.tvLink);
this.tvDescrition = v.findViewById(R.id.tvDescrition);
}
}
}
|
package co.staruml.handler;
import java.util.*;
import org.eclipse.swt.events.KeyEvent;
import co.staruml.core.DiagramControl;
import co.staruml.graphics.Canvas;
public class HandlerGroup extends Handler {
private Vector<Handler> handlers;
public HandlerGroup() {
handlers = new Vector<Handler>();
}
public void addHandler(Handler handler) {
handlers.add(handler);
}
public void removeHandler(Handler handler) {
handlers.remove(handler);
}
public void mouseDragged(DiagramControl diagramControl, Canvas canvas, MouseEvent e) {
}
public void mouseMoved(DiagramControl diagramControl, Canvas canvas, MouseEvent e) {
}
public void mousePressed(DiagramControl diagramControl, Canvas canvas, MouseEvent e) {
}
public void mouseReleased(DiagramControl diagramControl, Canvas canvas, MouseEvent e) {
}
@Override
public void keyPressed(DiagramControl diagramControl, Canvas canvas,
KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
package com.design.pattern.builder.product;
import com.design.pattern.builder.middleProduct.PastryCream;
import lombok.Data;
import java.time.LocalDateTime;
/**
* @author zhangbingquan
* @desc 糕点对象,面包建造者对象生产出来的对象
* @time 2019/7/28 21:55
*/
@Data
public class Pastry {
/**生产日期*/
private LocalDateTime productinTime;
/**奶油对象*/
private PastryCream pastryCream;
/**制作的糕点名字*/
private String pastryName;
/**制作糕点使用的蛋*/
private String egg;
/**制作糕点使用的水*/
private String water;
}
|
package factorioMain;
import org.lwjgl.util.Rectangle;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
public class Entity {
private Image image;
private int x,y;
private String name;
private Rectangle rect;
private Conveyor preConveyor;
private boolean inContact;
private boolean erase = false;
private boolean addKapa = true;
private int tick = 0;
private boolean inInventory = false;
public Entity(Image image, int x, int y, String name) {
this.image = image;
this.setX(x);
this.setY(y);
this.setName(name);
this.rect = new Rectangle(this.x,this.y,image.getWidth(),image.getHeight());
}
public void Draw(Graphics g) {
g.drawImage(this.image, this.x, this.y);
}
public Image getImage() {
return image;
}
public void updateEntity(WorldGeneration world) {
this.tick++;
if(world.getTileFromChunk(this.getX()/world.getTileSize(), this.getY()/world.getTileSize()).getTag() == "Conveyor") {
Conveyor currentConveyor = ((Conveyor) world.getTileFromChunk(this.getX()/world.getTileSize(), this.getY()/world.getTileSize()));
if(this.preConveyor == null) {
this.preConveyor = currentConveyor;
}
else if(!this.preConveyor.equals(currentConveyor)) {
this.preConveyor.setCapacity(this.preConveyor.getCapacity()-1);
this.preConveyor = currentConveyor;
this.addKapa = true;
}
if(this.addKapa) {
this.preConveyor.setCapacity(this.preConveyor.getCapacity()+1);
this.addKapa = false;
}
switch(currentConveyor.getDirection()) {
case "south":
if(world.getTileFromChunk(currentConveyor.getX(), currentConveyor.getY()+1).getDirection() != "north"
&& world.getTileFromChunk(currentConveyor.getX(), currentConveyor.getY()+1).getTag() == "Conveyor") {
if(((Conveyor)world.getTileFromChunk(currentConveyor.getX(), currentConveyor.getY()+1)).getCapacity() < 1) {
this.y += currentConveyor.getConveyorSpeed();
//this.inContact = false;
}
}
break;
case "north":
if(world.getTileFromChunk(currentConveyor.getX(), currentConveyor.getY()-1).getDirection() != "south"
&& world.getTileFromChunk(currentConveyor.getX(), currentConveyor.getY()-1).getTag() == "Conveyor") {
if(((Conveyor)world.getTileFromChunk(currentConveyor.getX(), currentConveyor.getY()-1)).getCapacity() < 1) {
this.y -= currentConveyor.getConveyorSpeed();
//this.inContact = false;
}
}
break;
case "west":
if(world.getTileFromChunk(currentConveyor.getX()-1, currentConveyor.getY()).getDirection() != "east"
&& world.getTileFromChunk(currentConveyor.getX()-1, currentConveyor.getY()).getTag() == "Conveyor") {
if(((Conveyor)world.getTileFromChunk(currentConveyor.getX()-1, currentConveyor.getY())).getCapacity() < 1) {
this.x -= currentConveyor.getConveyorSpeed();
//this.inContact = false;
}
}
break;
case "east":
if(world.getTileFromChunk(currentConveyor.getX()+1, currentConveyor.getY()).getDirection() != "west"
&& world.getTileFromChunk(currentConveyor.getX()+1, currentConveyor.getY()).getTag() == "Conveyor") {
if(((Conveyor)world.getTileFromChunk(currentConveyor.getX()+1, currentConveyor.getY())).getCapacity() < 1) {
this.x += currentConveyor.getConveyorSpeed();
//this.inContact = false;
}
}
break;
}
}
else {
if(this.tick > 1000) {
if(!(world.getTileFromChunk((this.getX()+1)/world.getTileSize(), this.getY()/world.getTileSize()).getTag() == "Conveyor"
|| world.getTileFromChunk((this.getX()-1)/world.getTileSize(), this.getY()/world.getTileSize()).getTag() == "Conveyor"
|| world.getTileFromChunk((this.getX())/world.getTileSize(), (this.getY()-1)/world.getTileSize()).getTag() == "Conveyor"
|| world.getTileFromChunk((this.getX())/world.getTileSize(), (this.getY()+1)/world.getTileSize()).getTag() == "Conveyor")
|| world.getTileFromChunk((this.getX())/world.getTileSize(), (this.getY())/world.getTileSize()).getTag() == "machines") {
world.getDeleteEntity().add(this);
}
this.tick = 0;
}
}
this.rect.setX(this.x);
this.rect.setY(this.y);
}
public Rectangle getRectangle() {
return this.rect;
}
public void setImage(Image image) {
this.image = image;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isInContact() {
return inContact;
}
public void setInContact(boolean inContact) {
this.inContact = inContact;
}
public boolean isInInventory() {
return inInventory;
}
public void setInInventory(boolean inInventory) {
this.inInventory = inInventory;
}
public boolean isErase() {
return erase;
}
public void setErase(boolean erase) {
this.erase = erase;
}
}
|
package cn.hui.javapro.design.decorator;
public abstract class Manager implements Project{
private Project project;
public Manager(Project project){
this.project = project;
}
public void doCoding() {
startWork();
}
public void startWork(){
doEarlyWork();
project.doCoding();
doEndWork();
}
/**
* 项目经理自己的事情,前期工作
*/
public abstract void doEarlyWork();
/**
* 项目经理做收尾工作
*/
public abstract void doEndWork();
} |
package com.tencent.mm.plugin.subapp.ui.voicetranstext;
class VoiceTransTextUI$8 implements Runnable {
final /* synthetic */ VoiceTransTextUI ouz;
VoiceTransTextUI$8(VoiceTransTextUI voiceTransTextUI) {
this.ouz = voiceTransTextUI;
}
public final void run() {
VoiceTransTextUI.r(this.ouz).setPadding(0, 0, 0, 0);
VoiceTransTextUI.s(this.ouz).setGravity(17);
}
}
|
package com.example.retail.models.taxutility;
import javax.persistence.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
@Entity
public class Taxes {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="taxes_tableid")
private Integer taxesTableId;
@NotEmpty
@NotNull
@Column(name = "tax_name", unique = true, updatable = false)
private String taxName;
@Min(0)
@Column(name = "tax_percent")
private Float taxPercent;
@Column(name = "additional_tax_info")
private String additionalTaxInfo;
@NotNull
@Column(name = "should_tax_apply")
private Boolean shouldTaxApply = true;
@NotEmpty
@NotNull
@Column(name = "last_updated_by")
private String taxLastUpdatedBy;
@NotNull
@Column(name = "last_updated_on")
private LocalDateTime taxLastUpdatedOn;
public Taxes() {}
public Taxes(@NotEmpty @NotNull String taxName, @Min(0) Float taxPercent, String additionalTaxInfo, @NotNull Boolean shouldTaxApply,
@NotEmpty @NotNull String taxLastUpdatedBy, @NotNull LocalDateTime taxLastUpdatedOn) {
this.taxName = taxName;
this.taxPercent = taxPercent;
this.additionalTaxInfo = additionalTaxInfo;
this.shouldTaxApply = shouldTaxApply;
this.taxLastUpdatedBy = taxLastUpdatedBy;
this.taxLastUpdatedOn = taxLastUpdatedOn;
}
public Integer getTaxesTableId() {
return taxesTableId;
}
public void setTaxesTableId(Integer taxesTableId) {
this.taxesTableId = taxesTableId;
}
public String getTaxName() {
return taxName;
}
public void setTaxName(String taxName) {
this.taxName = taxName;
}
public Float getTaxPercent() {
return taxPercent;
}
public void setTaxPercent(Float taxPercent) {
this.taxPercent = taxPercent;
}
public String getAdditionalTaxInfo() {
return additionalTaxInfo;
}
public void setAdditionalTaxInfo(String additionalTaxInfo) {
this.additionalTaxInfo = additionalTaxInfo;
}
public Boolean getShouldTaxApply() {
return shouldTaxApply;
}
public void setShouldTaxApply(Boolean shouldTaxApply) {
this.shouldTaxApply = shouldTaxApply;
}
public String getTaxLastUpdatedBy() {
return taxLastUpdatedBy;
}
public void setTaxLastUpdatedBy(String taxLastUpdatedBy) {
this.taxLastUpdatedBy = taxLastUpdatedBy;
}
public LocalDateTime getTaxLastUpdatedOn() {
return taxLastUpdatedOn;
}
public void setTaxLastUpdatedOn(LocalDateTime taxLastUpdatedOn) {
this.taxLastUpdatedOn = taxLastUpdatedOn;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.