text
stringlengths 10
2.72M
|
|---|
/**
*
* Question - Build project
* Created by Yu Zheng on 9/21/2015
*
* idea: Have no idea yet...
*
*/
public class Solution07 {
Project[] findBuildOrder(String[] projects, String[][] dependencies){
Graph graph = buildGraph(projects, dependencies);
return orderProjects(graph.GetNodes());
}
Graph buildGraph(String projects, String[][] dependencies){
Graph graph = new Graph();
for (String project: projects){
graph.createNode(project);
}
for (String[] dependency: dependencies){
String first = dependency[0];
String second = dependency[1];
graph.addEdge(first, second);
}
return graph;
}
Project[] orderProjects(ArrayList<Project> projects){
Project[] order = new Project[projects.size()];
int endOfList = addNonDependent(order, projects, 0);
int toBeProcessed = 0;
while (toBeProcessed < order.length){
Project current = order[toBeProcessed];
if (current == null){
return null;
}
ArrayList<Project> children = current.getChildren();
for (Project child: children){
child.decrementDependencies();
}
endOfList = addNonDependent(order, children, endOfList);
toBeProcessed++;
}
return order;
}
int addNonDependent(Project[] order, ArrayList<Project> projects, int offset){
for (Project project: projects){
if (project.getNumberDependencies() == 0){
order[offset] = project;
offset++;
}
}
return offset;
}
class Graph {
private ArrayList<Project> nodes = new ArrayList<Project>();
private HashMap<String, Project> map = new HashMap<String, Project>();
public Project getOrCreateNode(String name){
if (!map.containsKey(name)){
Project node = new Project(name);
nodes.add(note);
map.put(name, node);
}
return map.get(name);
}
public void addEdge(String startName, String endName){
Project start = getOrCreateNode(startName);
Project end = getOrCreateNode(endName);
start.addNeighbor(end);
}
public ArrayList<Project> getNodes(){ return nodes;}
}
class Project{
private ArrayList<Project> children = new ArrayList<Project>();
private HashMap<String, Project> map = new HashMap<String, Project>();
private String name;
private int dependencies = 0;
public Project(String n) { name = n;}
public void addNeighbor(Project node){
if (!map.containsKey(node.getName())){
children.add(node);
node.incrementDependencies();
}
}
public void incrementDependencies(){ dependencies++;}
public void decrementDependencies(){ dependencies--;}
public String getName() { return name;}
public ArrayList<Project> getChildren() {return children;}
public int getNumberDependencies() { return dependencies;}
}
}
|
package com.example.ComicToon.Models.RequestResponseModels;
public class ViewComicSeriesForm {
private String comicSeriesName;
private String OwnerName;
private String viewerName;
/**
* @return the comicSeriesName
*/
public String getComicSeriesName() {
return comicSeriesName;
}
/**
* @return the ownerName
*/
public String getOwnerName() {
return OwnerName;
}
/**
* @param ownerName the ownerName to set
*/
public void setOwnerName(String ownerName) {
this.OwnerName = ownerName;
}
/**
* @param comicSeriesName the comicSeriesName to set
*/
public void setComicSeriesName(String comicSeriesName) {
this.comicSeriesName = comicSeriesName;
}
public String getViewerName() {
return this.viewerName;
}
public void setViewerName(String viewerName) {
this.viewerName = viewerName;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openwebbeans.junit5;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.se.SeContainer;
import jakarta.enterprise.inject.se.SeContainerInitializer;
import jakarta.enterprise.inject.spi.CDI;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CdiParameterResolversTest
{
private static SeContainer container;
@BeforeAll
static void start() {
// simulate another way than @Cdi to bootstrap the container,
// can be another server (meecrowave, tomee, playx, ...) or just a custom preconfigured setup
container = SeContainerInitializer.newInstance()
.disableDiscovery()
.addBeanClasses(CdiParameterResolversTest.SomeBean.class)
.initialize();
}
@AfterAll
static void stop() {
container.close();
}
@Test
void noParam()
{
assertNotNull(CDI.current().getBeanManager());
}
@Test
@CdiMethodParameters
void cdiParam(final SomeBean someBean)
{
assertNotNull(someBean);
assertEquals("yes", someBean.ok());
assertTrue(someBean.getClass().getName().contains("$$Owb")); // it is cdi proxy
}
@Test
@CdiMethodParameters
@ExtendWith(CustomParamResolver.class)
void mixedParams(final SomeBean cdi, @SkipInject final SomeBean notCdi)
{
assertNotNull(cdi);
assertEquals("yes", cdi.ok());
assertEquals("custom", notCdi.ok());
}
@ApplicationScoped
public static class SomeBean
{
public String ok()
{
return "yes";
}
}
public static class CustomParamResolver implements ParameterResolver
{
@Override
public boolean supportsParameter(final ParameterContext parameterContext,
final ExtensionContext extensionContext) throws ParameterResolutionException
{
return parameterContext.getIndex() == 1;
}
@Override
public Object resolveParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext)
throws ParameterResolutionException
{
return new SomeBean()
{
@Override
public String ok()
{
return "custom";
}
};
}
}
}
|
package com.eres.waiter.waiter.viewpager.fragment;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.eres.waiter.waiter.R;
import com.eres.waiter.waiter.app.App;
import com.eres.waiter.waiter.fragment.viewpager_fragment.FragmentTables;
import com.eres.waiter.waiter.model.Table;
import com.eres.waiter.waiter.model.TablesItem;
import com.eres.waiter.waiter.preferance.SettingPreferances;
import com.eres.waiter.waiter.viewpager.DepthTransformation;
import com.eres.waiter.waiter.viewpager.helper.ObservableCollection;
import com.eres.waiter.waiter.viewpager.model.Hall;
import com.eres.waiter.waiter.viewpager.viewmodel.AllTablesViewModel;
import com.labo.kaji.fragmentanimations.CubeAnimation;
public class AllTablesFragment extends Fragment {
Table table = null;
private ViewPager vPager;
private MyFragmentPagerAdapter pageAdapter;
private int numberOfColumns = 1;
private TabLayout tabLayout;
ObservableCollection<com.eres.waiter.waiter.model.Table> tables = null;
ObservableCollection<Hall> halls = new ObservableCollection<>();
private boolean isFist = false;
private int tabPos = 0;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
setRetainInstance(true);
for (Fragment fragment : getFragmentManager().getFragments()) {
if (fragment instanceof FragmentTables) {
getFragmentManager().beginTransaction().remove(fragment).commit();
Log.i("SSS", "onCreate: remove ");
}
}
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.empty_layout, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.listTab);
vPager = (ViewPager) view.findViewById(R.id.pagerInner);
AllTablesViewModel model = ViewModelProviders.of(this).get(AllTablesViewModel.class);
data = model.getData();
// halls = model.getData().getValue();
data.observe(this, new Observer<ObservableCollection<Hall>>() {
@Override
public void onChanged(@Nullable ObservableCollection<Hall> halls1) {
halls = halls1;
App.getApp().setTables(data.getValue());
pageAdapter = new MyFragmentPagerAdapter(model.getData(), getFragmentManager());
vPager.setPageTransformer(true, new DepthTransformation());
vPager.setAdapter(pageAdapter);
tabLayout.setupWithViewPager(vPager);
// vPager.setPageTransformer(false, new CubeAnimation().);
pageAdapter.notifyDataSetChanged();
if (tabLayout != null) {
TabLayout.Tab tab = tabLayout.getTabAt(SettingPreferances.preferances.getHallPosition());
if (tab != null) {
Log.d("LOG_TEST", "run: ");
tab.select();
}
}
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
View view1 = LayoutInflater.from(getContext()).inflate(R.layout.custum_view, container, false);
// TextView textView = view1.findViewById(R.id.text);
// textView.setText(halls.get(tab.getPosition()).getName());
// tab.setCustomView(view1);
Log.d("TAB_TEST", "onTabSelected: " + tab.getText());
tabPos = tab.getPosition();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
@Override
public void onPause() {
SettingPreferances.preferances.setHallPosition(tabPos);
Log.d("LOG_TEST", "onPause: " + tabPos);
super.onPause();
}
LiveData<ObservableCollection<Hall>> data = null;
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public ObservableCollection<TablesItem> getTables(long hallId) {
ObservableCollection<Hall> halls = data.getValue();
for (int ci = 0; ci < halls.size(); ci++) {
Hall hall = halls.get(ci);
if (hall.getId() == hallId)
return hall.getTables();
}
return null;
}
private class MyFragmentPagerAdapter extends FragmentPagerAdapter {
LiveData<ObservableCollection<Hall>> halldata;
public MyFragmentPagerAdapter(LiveData<ObservableCollection<Hall>> _data, FragmentManager fm) {
super(fm);
this.halldata = _data;
}
@Override
public Fragment getItem(int position) {
return FragmentTables.getInstance(position);
}
@Override
public int getCount() {
if (halldata != null && halldata.getValue() != null)
return halldata.getValue().size();
return 0;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
if (halldata != null && halldata.getValue() != null)
return halldata.getValue().get(position).getName();
return null;
}
}
}
|
package com.tencent.mm.plugin.account.bind.ui;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.EditText;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.account.a.j;
import com.tencent.mm.plugin.account.bind.a.b;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.h;
class VerifyQQUI$2 implements OnMenuItemClickListener {
final /* synthetic */ VerifyQQUI eJq;
final /* synthetic */ EditText eJr;
final /* synthetic */ EditText eJs;
VerifyQQUI$2(VerifyQQUI verifyQQUI, EditText editText, EditText editText2) {
this.eJq = verifyQQUI;
this.eJr = editText;
this.eJs = editText2;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
String trim = this.eJr.getText().toString().trim();
VerifyQQUI.a(this.eJq, this.eJs.getText().toString().trim());
try {
VerifyQQUI.a(this.eJq, bi.getLong(trim, 0));
if (VerifyQQUI.b(this.eJq) < 10000) {
h.i(this.eJq.mController.tml, j.bind_qq_verify_alert_qq, j.bind_qq_verify_alert_failed_title);
} else if (VerifyQQUI.c(this.eJq).equals("")) {
h.i(this.eJq.mController.tml, j.bind_qq_verify_alert_pwd, j.bind_qq_verify_alert_failed_title);
} else {
this.eJq.YC();
b bVar = new b(VerifyQQUI.b(this.eJq), VerifyQQUI.c(this.eJq), "", "", "", VerifyQQUI.d(this.eJq), VerifyQQUI.e(this.eJq), false);
g.DF().a(bVar, 0);
VerifyQQUI verifyQQUI = this.eJq;
ActionBarActivity actionBarActivity = this.eJq.mController.tml;
this.eJq.getString(j.bind_qq_verify_alert_title);
VerifyQQUI.a(verifyQQUI, h.a(actionBarActivity, this.eJq.getString(j.bind_qq_verify_alert_binding), true, new 1(this, bVar)));
}
} catch (Exception e) {
h.i(this.eJq.mController.tml, j.bind_qq_verify_alert_qq, j.bind_qq_verify_alert_failed_title);
}
return true;
}
}
|
package billFormApplication;
import javafx.geometry.Pos;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
public class BillFormTotal extends HBox{
private Text totalHtTxt;
private Text tvaTxt;
private Text netTtcTxt;
//Constructor
public BillFormTotal() {
//Children nodes
totalHtTxt = new Text("Total H.T");
tvaTxt = new Text("Taux Tva");
netTtcTxt = new Text("Net à payer TTC");
//Adding children
getChildren().addAll(totalHtTxt , tvaTxt , netTtcTxt);
//Styling layout
setAlignment(Pos.CENTER);
setSpacing(20);
}
}
|
package lesson3.begginer;
/**
* Created by Angelina on 21.01.2017.
*/
public class Task4 {
public static void main(String[] args) {
System.out.println("Given an array of integers. Create a method (program) which takes two arguments - this array \n" +
"and number that you are looking for - and returns quantity of this number in the array\n");
Task4 t4 = new Task4();
t4.quantityOfNum();
}
public void quantityOfNum(){
int[] arr1 = {1,20,3,4,5,2};
int a = 2;
int b=0;
for(int i=0; i<arr1.length; i++){
if (arr1[i]==a){
b++;
}
}
System.out.println("Your number is - "+ a+"\n"+"The quantity of this number in the array is "+b);
}
}
|
package com.LoginTest.server.controller;
import com.LoginTest.server.model.User;
import com.LoginTest.server.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ValidateAuthController {
@Autowired
private BCryptPasswordEncoder passwordEncoder;
@Autowired
private UserService us;
@PostMapping(value="/checkuser/{email}", consumes="application/json", produces="application/json")
public ResponseEntity<HttpStatus> validateAuth(@PathVariable("email") String email, @RequestBody User user)
{
if(user==null || email==null)
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
else {
User user1 = us.getUserByEmail(email);
if (user1.getEmail().equals(user.getEmail()))
if (passwordEncoder.matches(user.getPassword(),user1.getPassword()))
return new ResponseEntity<>(HttpStatus.ACCEPTED);
else
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
else
return new ResponseEntity<>(HttpStatus.FORBIDDEN);
}
}
}
|
package com.packers.movers.commons.utils;
import java.util.Objects;
import java.util.function.BiConsumer;
@FunctionalInterface
public interface ThrowableConsumer<T, U> {
void accept(T t, U u) throws Exception;
default BiConsumer<T, U> andThen(BiConsumer<? super T, ? super U> after) {
Objects.requireNonNull(after);
return (l, r) -> {
try {
accept(l, r);
after.accept(l, r);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
};
}
default BiConsumer<T, U> toBiConsumer() {
return (key, value) -> {
try {
accept(key, value);
} catch (Exception exception) {
throw new RuntimeException(exception);
}
};
}
}
|
package com.greenglobal.eoffice.domain.core.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private int id;
@Column(name = "createdAt", nullable = false)
private Date createdAt;
@Column(name = "modifiedAt", nullable = true)
private Date modifiedAt;
@Column(name = "isDeleted", nullable = false)
private boolean isDeleted = false;
@Column(name = "deletedAt", nullable = true)
private Date deletedAt;
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the deletedAt
*/
public Date getDeletedAt() {
return deletedAt;
}
/**
* @param deletedAt the deletedAt to set
*/
public void setDeletedAt(Date deletedAt) {
this.deletedAt = deletedAt;
}
/**
* @return the isDeleted
*/
public boolean getIsDeleted() {
return isDeleted;
}
/**
* @param isDeleted the isDeleted to set
*/
public void setIsDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
/**
* @return the modifiedAt
*/
public Date getModifiedAt() {
return modifiedAt;
}
/**
* @param modifiedAt the modifiedAt to set
*/
public void setModifiedAt(Date modifiedAt) {
this.modifiedAt = modifiedAt;
}
/**
* @return the createdAt
*/
public Date getCreatedAt() {
return createdAt;
}
/**
* @param createdAt the createdAt to set
*/
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.01.28 at 02:10:24 PM CST
//
package org.mesa.xml.b2mml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for WorkDefinitionInformationType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="WorkDefinitionInformationType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType" minOccurs="0"/>
* <element name="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="HierarchyScope" type="{http://www.mesa.org/xml/B2MML-V0600}HierarchyScopeType" minOccurs="0"/>
* <element name="PublishedDate" type="{http://www.mesa.org/xml/B2MML-V0600}PublishedDateType" minOccurs="0"/>
* <element name="WorkMaster" type="{http://www.mesa.org/xml/B2MML-V0600}WorkMasterType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="WorkDirective" type="{http://www.mesa.org/xml/B2MML-V0600}WorkDirectiveType" maxOccurs="unbounded" minOccurs="0"/>
* <group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}WorkDefinitionInformation" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "WorkDefinitionInformationType", propOrder = {
"id",
"description",
"hierarchyScope",
"publishedDate",
"workMaster",
"workDirective"
})
public class WorkDefinitionInformationType {
@XmlElement(name = "ID")
protected IdentifierType id;
@XmlElement(name = "Description")
protected List<DescriptionType> description;
@XmlElement(name = "HierarchyScope")
protected HierarchyScopeType hierarchyScope;
@XmlElement(name = "PublishedDate")
protected PublishedDateType publishedDate;
@XmlElement(name = "WorkMaster")
protected List<WorkMasterType> workMaster;
@XmlElement(name = "WorkDirective")
protected List<WorkDirectiveType> workDirective;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link IdentifierType }
*
*/
public IdentifierType getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link IdentifierType }
*
*/
public void setID(IdentifierType value) {
this.id = value;
}
/**
* Gets the value of the description property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the description property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DescriptionType }
*
*
*/
public List<DescriptionType> getDescription() {
if (description == null) {
description = new ArrayList<DescriptionType>();
}
return this.description;
}
/**
* Gets the value of the hierarchyScope property.
*
* @return
* possible object is
* {@link HierarchyScopeType }
*
*/
public HierarchyScopeType getHierarchyScope() {
return hierarchyScope;
}
/**
* Sets the value of the hierarchyScope property.
*
* @param value
* allowed object is
* {@link HierarchyScopeType }
*
*/
public void setHierarchyScope(HierarchyScopeType value) {
this.hierarchyScope = value;
}
/**
* Gets the value of the publishedDate property.
*
* @return
* possible object is
* {@link PublishedDateType }
*
*/
public PublishedDateType getPublishedDate() {
return publishedDate;
}
/**
* Sets the value of the publishedDate property.
*
* @param value
* allowed object is
* {@link PublishedDateType }
*
*/
public void setPublishedDate(PublishedDateType value) {
this.publishedDate = value;
}
/**
* Gets the value of the workMaster property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the workMaster property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWorkMaster().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link WorkMasterType }
*
*
*/
public List<WorkMasterType> getWorkMaster() {
if (workMaster == null) {
workMaster = new ArrayList<WorkMasterType>();
}
return this.workMaster;
}
/**
* Gets the value of the workDirective property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the workDirective property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getWorkDirective().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link WorkDirectiveType }
*
*
*/
public List<WorkDirectiveType> getWorkDirective() {
if (workDirective == null) {
workDirective = new ArrayList<WorkDirectiveType>();
}
return this.workDirective;
}
}
|
package Kursach.Debug;
public class PersonTags {
private static String fullName = "fullName";
private static String birthday = "birthday";
private static String birthplace = "birthplace";
private static String genre = "genre";
private static String gender = "gender";
public static String nameOpen() {
return Tag.openTag(fullName);
}
public static String birthdayOpen() {
return Tag.openTag(birthday);
}
public static String birthplaceOpen() {
return Tag.openTag(birthplace);
}
public static String genreOpen() {
return Tag.openTag(genre);
}
public static String genderOpen() {
return Tag.openTag(gender);
}
////
public static String nameClose() {
return Tag.closeTag(fullName);
}
public static String birthdayClose() {
return Tag.closeTag(birthday);
}
public static String birthplaceClose() {
return Tag.closeTag(birthplace);
}
public static String genreClose() {
return Tag.closeTag(genre);
}
public static String genderClose() {
return Tag.closeTag(gender);
}
}
|
package com.box.androidsdk.content.models;
import com.eclipsesource.json.JsonObject;
import java.util.ArrayList;
/**
* Class representing a list of representations.
*/
public class BoxIteratorRepresentations extends BoxIterator<BoxRepresentation> {
private static final long serialVersionUID = -4986439348667936122L;
private transient BoxJsonObjectCreator<BoxRepresentation> representationCreator;
public BoxIteratorRepresentations() {
}
public BoxIteratorRepresentations(JsonObject jsonObject) {
super(jsonObject);
}
@Override
protected BoxJsonObjectCreator<BoxRepresentation> getObjectCreator() {
if (representationCreator != null){
return representationCreator;
}
representationCreator = BoxJsonObject.getBoxJsonObjectCreator(BoxRepresentation.class);
return representationCreator;
}
@Deprecated
public Long offset() {
return null;
}
@Deprecated
public Long limit() {
return null;
}
@Deprecated
public Long fullSize() {
return null;
}
@Deprecated
public ArrayList<BoxOrder> getSortOrders() {
return null;
}
}
|
//2. 키보드로 부터 10개의 정수를 입력받아 배열에 저장하고 이중에서 3의 배수인 수만 골라 출력
import java.util.*;
class array_Test5 {
public static void main(String ar[]){
Scanner sc = new Scanner(System.in);
int a;
int three;
int b[]=new int[10];
for (int i=0 ; i<b.length ; i++)
{
System.out.println("변수 입력 : ");
a = sc.nextInt();
b[i]=a;
if(b[i]%3==0){
three = b[i];
System.out.println(three);
}
}
}
}
|
package uns.ac.rs.hostplatserver.constant;
public class UserRoles {
public static final String ROLE_USER = "ROLE_USER";
private UserRoles() {
}
}
|
package edu.dp;
public class AbstractFactoryDemo {
public class AbstractProductA {
}
public class AbstractProductB {
}
public class ProductA1 extends AbstractProductA {
}
public class ProductA2 extends AbstractProductA {
}
public class ProductB1 extends AbstractProductB {
}
public class ProductB2 extends AbstractProductB {
}
// 对象家族,也就是很多对象而不是一个对象,并且这些对象是相关的,也就是说必须一起创建出来
public abstract class AbstractFactory {
abstract AbstractProductA createProductA();
abstract AbstractProductB createProductB();
}
// 具体的工厂类1,这个工厂类用于实例化产品A1和B1
public class ConcreteFactory1 extends AbstractFactory{
AbstractProductA createProductA() {
return new ProductA1();
}
AbstractProductB createProductB() {
return new ProductB1();
}
}
// 具体的工厂类2,这个工厂类用于实例化产品A2和B2
public class ConcreteFactory2 extends AbstractFactory{
AbstractProductA createProductA() {
return new ProductA2();
}
AbstractProductB createProductB() {
return new ProductB2();
}
}
}
|
package robotsimulator;
import java.util.ArrayList;
import characteristics.IRadarResult;
public class Bot {
private double radius;
private double frontRange;
private double speed;
private double stepTurnAngle;
private double x;
private double y;
private double angle;
private double maxHealth;
private double health;
private Brain brain;
private SimulatorEngine engine;
private int me;
private boolean rocket;
private ArrayList<String> mailbox;
public Bot(double radius, double range, double speed, double stepTurnAngle, double x, double y, double angle,
double health, boolean rocket, Brain brain, int me) {
this.radius = radius;
frontRange = range;
this.speed = speed;
this.stepTurnAngle = stepTurnAngle;
this.x = x;
this.y = y;
this.angle = angle;
maxHealth = health;
this.health = health;
this.brain = brain;
this.me = me;
this.rocket = rocket;
mailbox = new ArrayList();
brain.bind(this);
}
protected void bind(SimulatorEngine engine) {
this.engine = engine;
}
public void activate() {
brain.activation();
}
public void step() { brain.stepAction(); }
public double getX() {
return x;
}
public double getY() { return y; }
public double getRadius() {
return radius;
}
public double getHeading() { return angle; }
public double getHealth() {
return health;
}
public double getMaxHealth() { return maxHealth; }
public int getTeam() {
return me;
}
public String getLogMessage() { return brain.getLogMessage(); }
public void takeDamage(double damage) {
health = Math.max(health - damage, 0.0D);
}
public boolean isDestroyed() { return health <= 0.0D; }
protected void move() {
double newX = x + speed * Math.cos(angle);
double newY = y + speed * Math.sin(angle);
if ((newX >= radius) && (newX <= engine.getWorld().getWidth() - radius) && (newY >= radius) && (newY <= engine
.getWorld().getHeight() - radius)) {
boolean doIt = true;
for (Bot bot : engine.getBots()) {
if (!bot.equals(this))
if ((newX - bot.getX()) * (newX - bot.getX()) + (newY - bot.getY()) * (newY - bot
.getY()) < (getRadius() + bot.getRadius()) * (getRadius() + bot.getRadius()))
doIt = false;
}
if (doIt) {
x = newX;
y = newY;
}
}
}
protected void moveBack() {
double newX = x - speed * Math.cos(angle);
double newY = y - speed * Math.sin(angle);
if ((newX >= radius) && (newX <= engine.getWorld().getWidth() - radius) && (newY >= radius) && (newY <= engine
.getWorld().getHeight() - radius)) {
boolean doIt = true;
for (Bot bot : engine.getBots()) {
if (!bot.equals(this))
if ((newX - bot.getX()) * (newX - bot.getX()) + (newY - bot.getY()) * (newY - bot
.getY()) < (getRadius() + bot.getRadius()) * (getRadius() + bot.getRadius()))
doIt = false;
}
if (doIt) {
x = newX;
y = newY;
}
}
}
protected void fire(double dir) { engine.addBullet(this, dir); }
protected void stepTurnLeft() {
angle -= stepTurnAngle;
}
protected void stepTurnRight() { angle += stepTurnAngle; }
protected void broadcast(String message) { engine.broadcast(message, me); }
protected ArrayList<String> fetchAllMessages() {
ArrayList<String> messages = (ArrayList) mailbox.clone();
mailbox.clear();
return messages;
}
protected void addMessage(String message) { mailbox.add(message); }
protected boolean hasRocket() { return rocket; }
protected FrontSensorResult detectFront() {
double frontRangeX = x + frontRange * Math.cos(angle);
double frontRangeY = y + frontRange * Math.sin(angle);
return engine.detect(x, y, frontRangeX, frontRangeY, me);
}
protected ArrayList<IRadarResult> detectRadar() { return engine.detectRadar(frontRange, this); }
}
|
package com.huhurezmarius.worldmap.request;
public class AddTimezoneRequest {
private Long id;
private String name;
private String zoneName;
private String gmt;
public AddTimezoneRequest(String name, String zoneName) {
this.name = name;
this.zoneName = zoneName;
}
public String getGmt() {
return gmt;
}
public void setGmt(String gmt) {
this.gmt = gmt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getZoneName() {
return zoneName;
}
public void setZoneName(String zoneName) {
this.zoneName = zoneName;
}
}
|
package com.codelaxy.qwertpoiuy.ModelsNew;
public class Captcha {
private String id, image, captcha_type, right_count, wrong_count, skip_count, is_right;
public Captcha(String id, String image, String captcha_type, String right_count, String wrong_count, String skip_count, String is_right) {
this.id = id;
this.image = image;
this.captcha_type = captcha_type;
this.right_count = right_count;
this.wrong_count = wrong_count;
this.skip_count = skip_count;
this.is_right = is_right;
}
public String getId() {
return id;
}
public String getImage() {
return image;
}
public String getCaptcha_type() {
return captcha_type;
}
public String getRight_count() {
return right_count;
}
public String getWrong_count() {
return wrong_count;
}
public String getSkip_count() {
return skip_count;
}
public String getIs_right() {
return is_right;
}
}
|
package com.codegym.checkinhotel.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.Min;
import java.util.List;
@Entity
@Table(name = "room_details")
@NoArgsConstructor
@AllArgsConstructor
public class RoomDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String name;
@Column(name = "quantity")
@Min(0)
private int quantity;
@OneToMany(fetch = FetchType.LAZY,mappedBy = "roomDetails",cascade = CascadeType.ALL)
@JsonIgnoreProperties(value = "room_details")
private List<Room>rooms;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public List<Room> getRooms() {
return rooms;
}
public void setRooms(List<Room> rooms) {
this.rooms = rooms;
}
@Override
public String toString() {
return "Room detail [id=" + id
+ ", name=" + name
+ ", quantity exists=" + quantity
+ "]";
}
}
|
package com.example.springakka.repository;
import com.example.springakka.entity.Tag;
/**
* Created by Ido on 2017/9/27.
*/
public class TagDao extends BasicDao<Tag> {
public TagDao() {
super(Tag.class);
}
}
|
package slepec.hra.planek.prostor.vec;
import java.util.Set;
/**
* Verejne rozhrani pro ovladani veci (predmetu ve hre)
*
* @author Pavel Jurca, xjurp20@vse.cz
* @version 2
*/
public interface IVec {
boolean pridej(Vec... veci); //jedna vec muze obsahovat dalsi veci
Vec odeber(String nazevVeci);
boolean hasVec(String nazevVeci);
Vec selectVec(String nazevVeci);
Set<Vec> getVnitrek();
String getSeznamVeci();
String getPopis();
int getVaha(); //vraci vahu veci v gramech
boolean isSchranka(); //true, pokud dana vec muze obsahovat dalsi veci
boolean isJidlo(); //true, pokud danou vec lze snist
boolean isPiti(); //true, pokud danou vec lze vypit
int getNutriCislo(); //nutricni hodnota
}
|
package com.excilys.formation.cdb.binding.mapper;
import java.sql.ResultSet;
import com.excilys.formation.cdb.core.model.Company;
import com.excilys.formation.cdb.core.model.Company.CompanyBuilder;
public class MapperCompany {
public static Company resultSetToCompany(ResultSet resultSetNextise) throws Exception{
Company company = null;
if(resultSetNextise != null && !resultSetNextise.isAfterLast() && !resultSetNextise.isBeforeFirst()) {
CompanyBuilder buildercompany = new CompanyBuilder(resultSetNextise.getLong("id")).withName(resultSetNextise.getString("name"));
company = buildercompany.build();
}
return company;
}
public static Company dataToCompany(Long id, String name) {
Company company = new CompanyBuilder(id).withName(name).build();
return company;
}
}
|
package com.tt.miniapp.follow;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import com.storage.async.Function;
import com.storage.async.Observable;
import com.storage.async.Schedulers;
import com.storage.async.Subscriber;
import com.tt.miniapp.AppbrandConstant;
import com.tt.miniapp.event.Event;
import com.tt.miniapp.manager.NetManager;
import com.tt.miniapp.process.bridge.InnerHostProcessBridge;
import com.tt.miniapp.view.dialog.LoadingDialog;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandApplication;
import com.tt.miniapphost.AppbrandContext;
import com.tt.option.q.d;
import com.tt.option.q.i;
import org.json.JSONException;
import org.json.JSONObject;
public class FollowMethodImpl {
private FollowResultCallback callback;
public boolean mShowDialog = true;
private Handler mainHandler;
public FollowMethodImpl(FollowResultCallback paramFollowResultCallback) {
this.callback = paramFollowResultCallback;
this.mainHandler = new Handler(Looper.getMainLooper());
}
public void callbackResult(int paramInt, String paramString) {
FollowResultCallback followResultCallback = this.callback;
if (followResultCallback == null)
return;
followResultCallback.callBackResult(paramInt, paramString);
}
public void dismissLoadingDialog(final Dialog dialog) {
if (dialog != null && dialog.isShowing())
this.mainHandler.post(new Runnable() {
public void run() {
_lancet.com_ss_android_ugc_aweme_lancet_DebugCheckLancet_dialogDismiss(dialog);
}
class null {}
});
}
public void doFollow(Activity paramActivity) {
this.mShowDialog = true;
final Dialog dialog = showLoadingDialog(paramActivity, paramActivity.getString(2097742033));
final i tmaPostRequest = new i(AppbrandConstant.OpenApi.getInst().getDO_FOLLOW_URL(), "POST");
try {
String str1 = (AppbrandApplication.getInst().getAppInfo()).appId;
String str2 = InnerHostProcessBridge.getPlatformSession(str1);
long l1 = Long.valueOf(d.a()).longValue();
long l2 = Long.valueOf(AppbrandContext.getInst().getInitParams().getAppId()).longValue();
i.a("session", str2);
i.a("device_id", Long.valueOf(l1));
i.a("aid", Long.valueOf(l2));
i.a("app_id", str1);
} finally {
Exception exception = null;
}
Observable.create(new Function<String>() {
public String fun() {
String str = NetManager.getInst().request(tmaPostRequest).a();
AppBrandLogger.d("FollowMethodImpl", new Object[] { "requestResult = ", str });
return str;
}
}).schudleOn(Schedulers.longIO()).subscribe((Subscriber)new Subscriber.ResultableSubscriber<String>() {
public void onError(Throwable param1Throwable) {
FollowMethodImpl followMethodImpl = FollowMethodImpl.this;
followMethodImpl.mShowDialog = false;
followMethodImpl.dismissLoadingDialog(dialog);
FollowMethodImpl.this.callbackResult(2, "network error");
}
public void onSuccess(String param1String) {
FollowMethodImpl followMethodImpl = FollowMethodImpl.this;
followMethodImpl.mShowDialog = false;
followMethodImpl.dismissLoadingDialog(dialog);
if (TextUtils.isEmpty(param1String)) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "response empty" });
FollowMethodImpl.this.callbackResult(2, "response empty");
return;
}
try {
JSONObject jSONObject = new JSONObject(param1String);
int i = jSONObject.getInt("error");
if (i != 0) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "getUserInfo error not 0" });
FollowMethodImpl.this.callbackResult(i + 20, FollowErrorMsgBuilder.getResponseCodeDescription(i));
return;
}
if (jSONObject.getJSONObject("data").getInt("followed") == 1) {
i = 1;
} else {
i = 0;
}
if (i != 0) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "has followed success" });
FollowMethodImpl.this.callbackResult(0, "followed success");
return;
}
FollowMethodImpl.this.callbackResult(2, "followed not success");
AppBrandLogger.d("FollowMethodImpl", new Object[] { "followed failed!" });
return;
} catch (JSONException jSONException) {
AppBrandLogger.eWithThrowable("FollowMethodImpl", "jsonerror", (Throwable)jSONException);
FollowMethodImpl.this.callbackResult(2, "json error");
return;
}
}
});
}
public String getAuthType(String paramString) {
if (TextUtils.isEmpty(paramString))
return "";
try {
return (new JSONObject(paramString)).optString("auth_type");
} catch (JSONException jSONException) {
AppBrandLogger.eWithThrowable("FollowMethodImpl", "error", (Throwable)jSONException);
return "";
}
}
public void getCurrentFollowStateAndShowDialog(final Activity activity, final FollowUserInfo followUserInfo) {
if (activity == null) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "activity == null || callBack == null || userInfo == null" });
return;
}
AppBrandLogger.d("FollowMethodImpl", new Object[] { "getCurrentFollowStateAndShowDialog" });
CheckFollowMethodImpl.requestFollowState(new CheckFollowMethodImpl.FollowResultCallback() {
public void failed(Throwable param1Throwable) {
FollowMethodImpl.this.showDialog(activity, followUserInfo, false);
}
public void success(boolean param1Boolean) {
FollowMethodImpl.this.showDialog(activity, followUserInfo, param1Boolean);
}
});
}
public void getUserInfo(final Activity activity) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "getUserInfo start" });
final i tmaPostRequest = new i(AppbrandConstant.OpenApi.getInst().getQUERY_ACCOUNT_URL(), "POST");
try {
String str1 = (AppbrandApplication.getInst().getAppInfo()).appId;
String str2 = InnerHostProcessBridge.getPlatformSession(str1);
long l1 = Long.valueOf(d.a()).longValue();
long l2 = Long.valueOf(AppbrandContext.getInst().getInitParams().getAppId()).longValue();
i.a("session", str2);
i.a("device_id", Long.valueOf(l1));
i.a("aid", Long.valueOf(l2));
i.a("app_id", str1);
} finally {
Exception exception = null;
}
this.mShowDialog = true;
final Dialog loadingDialog = showLoadingDialog(activity, activity.getString(2097742035));
Observable.create(new Function<String>() {
public String fun() {
String str = NetManager.getInst().request(tmaPostRequest).a();
AppBrandLogger.d("FollowMethodImpl", new Object[] { "requestResult = ", str });
return str;
}
}).schudleOn(Schedulers.longIO()).subscribe((Subscriber)new Subscriber.ResultableSubscriber<String>() {
public void onError(Throwable param1Throwable) {
FollowMethodImpl followMethodImpl = FollowMethodImpl.this;
followMethodImpl.mShowDialog = false;
followMethodImpl.dismissLoadingDialog(loadingDialog);
}
public void onSuccess(String param1String) {
FollowMethodImpl followMethodImpl = FollowMethodImpl.this;
followMethodImpl.mShowDialog = false;
followMethodImpl.dismissLoadingDialog(loadingDialog);
if (TextUtils.isEmpty(param1String)) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "getUserInfo response null" });
FollowMethodImpl.this.callbackResult(2, "response null");
return;
}
StringBuilder stringBuilder = new StringBuilder("response s:");
stringBuilder.append(param1String);
AppBrandLogger.d("FollowMethodImpl", new Object[] { stringBuilder.toString() });
try {
JSONObject jSONObject = new JSONObject(param1String);
int i = jSONObject.getInt("error");
if (i != 0) {
AppBrandLogger.d("FollowMethodImpl", new Object[] { "getUserInfo error not 0" });
FollowMethodImpl.this.callbackResult(i + 20, FollowErrorMsgBuilder.getResponseCodeDescription(i));
return;
}
jSONObject = jSONObject.getJSONObject("data");
FollowUserInfo followUserInfo = new FollowUserInfo();
followUserInfo.avatarUrl = jSONObject.optString("avatar_url");
followUserInfo.name = jSONObject.optString("name");
followUserInfo.description = jSONObject.optString("description");
followUserInfo.userDecoration = jSONObject.optString("user_decoration");
followUserInfo.userAuthInfo = jSONObject.optString("user_auth_info");
followUserInfo.authType = FollowMethodImpl.this.getAuthType(followUserInfo.userAuthInfo);
FollowMethodImpl.this.getCurrentFollowStateAndShowDialog(activity, followUserInfo);
return;
} catch (JSONException jSONException) {
AppBrandLogger.eWithThrowable("FollowMethodImpl", "jsonerror", (Throwable)jSONException);
FollowMethodImpl.this.callbackResult(2, "response json parse error");
return;
}
}
});
}
public void logEvent(String paramString) {
Event.builder(paramString).flush();
}
public void showDialog(final Activity activity, final FollowUserInfo followUserInfo, final boolean hasFollowed) {
this.mainHandler.post(new Runnable() {
public void run() {
(new MicroGameFollowDialog((Context)activity, followUserInfo, hasFollowed, new MicroGameFollowDialog.IOnClickListener() {
public void onClose() {
FollowMethodImpl.this.callbackResult(1, "user close dialog");
FollowMethodImpl.this.logEvent("mp_follow_cancel");
}
public void onConfirm() {
FollowMethodImpl.this.doFollow(activity);
FollowMethodImpl.this.logEvent("mp_follow_click");
}
})).show();
}
});
logEvent("mp_follow_show");
}
public Dialog showLoadingDialog(Activity paramActivity, String paramString) {
if (paramActivity == null)
return null;
final LoadingDialog dialog = new LoadingDialog((Context)paramActivity, paramString);
this.mainHandler.postDelayed(new Runnable() {
public void run() {
if (FollowMethodImpl.this.mShowDialog)
dialog.show();
}
}, 1000L);
return (Dialog)loadingDialog;
}
public void startFollow(final Activity activity) {
if (!d.a((Context)activity)) {
callbackResult(3, "no network");
return;
}
this.mainHandler.post(new Runnable() {
public void run() {
FollowMethodImpl.this.getUserInfo(activity);
}
});
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\follow\FollowMethodImpl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
/* 1: */ package com.kaldin.common.util;
/* 2: */
/* 3: */ import java.io.IOException;
/* 4: */ import java.net.URLDecoder;
/* 5: */ import java.net.URLEncoder;
/* 6: */ import java.util.ArrayList;
/* 7: */ import javax.servlet.Filter;
/* 8: */ import javax.servlet.FilterChain;
/* 9: */ import javax.servlet.FilterConfig;
/* 10: */ import javax.servlet.ServletException;
/* 11: */ import javax.servlet.ServletRequest;
/* 12: */ import javax.servlet.ServletResponse;
/* 13: */ import javax.servlet.http.HttpServletRequest;
/* 14: */ import javax.servlet.http.HttpServletResponse;
/* 15: */ import javax.servlet.http.HttpSession;
/* 16: */
/* 17: */ public class UserSessionFilter
/* 18: */ implements Filter
/* 19: */ {
/* 20: 26 */ private ArrayList<String> urlList = new ArrayList();
/* 21: */ private FilterConfig filterConfig;
/* 22: */
/* 23: */ public UserSessionFilter()
/* 24: */ {
/* 25: 29 */ this.urlList.add("/login.do");
/* 26: 30 */ this.urlList.add("/forgotpassword.do");
/* 27: 31 */ this.urlList.add("/forgotpasswordAdmin.do");
/* 28: 32 */ this.urlList.add("/forgotsendPassword.do");
/* 29: 33 */ this.urlList.add("/Newpassword.do");
/* 30: 34 */ this.urlList.add("/calladsignup.do");
/* 31: 35 */ this.urlList.add("/register.do");
/* 32: 36 */ this.urlList.add("/Activate.do");
/* 33: 37 */ this.urlList.add("/callusersignup.do");
/* 34: 38 */ this.urlList.add("/signupNewUser.do");
/* 35: 39 */ this.urlList.add("/exam/");
/* 36: 40 */ this.urlList.add("/usertest.do");
/* 37: 41 */ this.urlList.add("/notestfound.do");
/* 38: 42 */ this.urlList.add("/starttest.do");
/* 39: */ }
/* 40: */
/* 41: */ public void init(FilterConfig filterConfig)
/* 42: */ throws ServletException
/* 43: */ {
/* 44: 51 */ this.filterConfig = filterConfig;
/* 45: */ }
/* 46: */
/* 47: */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
/* 48: */ throws ServletException, IOException
/* 49: */ {
/* 50: 62 */ HttpServletResponse httpServletResponse = (HttpServletResponse)response;
/* 51: 63 */ HttpServletRequest httpServletRequest = (HttpServletRequest)request;
/* 52: 64 */ HttpSession httpSession = httpServletRequest.getSession();
/* 53: 65 */ String requestUrl = httpServletRequest.getServletPath();
/* 54: */
/* 55: 67 */ httpServletRequest.setCharacterEncoding("UTF-8");
/* 56: 69 */ if (requestUrl.contains(".do"))
/* 57: */ {
/* 58: 70 */ boolean isActiveSessionForAdmin = true;
/* 59: 71 */ boolean isActiveSessionForSuperAdmin = true;
/* 60: 72 */ boolean isActiveSessionForUser = true;
/* 61: 74 */ if ((httpSession.getAttribute("Admin") == null) || (httpSession.getAttribute("Admin").equals("SignUp"))) {
/* 62: 75 */ isActiveSessionForAdmin = false;
/* 63: */ } else {
/* 64: 77 */ isActiveSessionForAdmin = true;
/* 65: */ }
/* 66: 79 */ if (httpSession.getAttribute("SuperAdmin") == null) {
/* 67: 80 */ isActiveSessionForSuperAdmin = false;
/* 68: */ } else {
/* 69: 82 */ isActiveSessionForSuperAdmin = true;
/* 70: */ }
/* 71: 84 */ if (httpSession.getAttribute("User") == null) {
/* 72: 85 */ isActiveSessionForUser = false;
/* 73: */ } else {
/* 74: 87 */ isActiveSessionForUser = true;
/* 75: */ }
/* 76: 89 */ if ((!isActiveSessionForAdmin) && (!isActiveSessionForSuperAdmin) && (!isActiveSessionForUser))
/* 77: */ {
/* 78: 90 */ if ((!requestUrl.contains("/jsp/common/index.jsp")) && (!this.urlList.contains(requestUrl))) {
/* 79: 91 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/jsp/common/index.jsp");
/* 80: */ } else {
/* 81: 94 */ filterChain.doFilter(request, response);
/* 82: */ }
/* 83: */ }
/* 84: 97 */ else if (this.urlList.contains(requestUrl))
/* 85: */ {
/* 86: 98 */ if ((httpSession.getAttribute("Admin") != null) && (!httpSession.getAttribute("Admin").equals("SignUp")) && (httpSession.getAttribute("SuperAdmin") == null)) {
/* 87:101 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/sitemap.do");
/* 88:102 */ } else if ((httpSession.getAttribute("SuperAdmin") != null) && (httpSession.getAttribute("Admin") != null)) {
/* 89:104 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/superadmin.do");
/* 90:105 */ } else if ((httpSession.getAttribute("SuperAdmin") == null) && ((httpSession.getAttribute("Admin") == null) || (httpSession.getAttribute("Admin").equals("SignUp"))) && (httpSession.getAttribute("User") != null)) {
/* 91:108 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/userhome.do");
/* 92: */ }
/* 93: */ }
/* 94: */ else {
/* 95:111 */ filterChain.doFilter(request, response);
/* 96: */ }
/* 97: */ }
/* 98:114 */ else if (requestUrl.contains(".jsp"))
/* 99: */ {
/* 100:116 */ if ((requestUrl.contains("checkCaptcha.jsp")) || (requestUrl.contains("executepublictest.jsp")) || (requestUrl.contains("tracknalert.jsp"))) {
/* 101:117 */ filterChain.doFilter(request, response);
/* 102:118 */ } else if ((httpSession.getAttribute("Admin") != null) && (!httpSession.getAttribute("Admin").equals("SignUp")) && (httpSession.getAttribute("SuperAdmin") == null)) {
/* 103:121 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/sitemap.do");
/* 104:122 */ } else if ((httpSession.getAttribute("SuperAdmin") != null) && (httpSession.getAttribute("Admin") != null)) {
/* 105:124 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/superadmin.do");
/* 106:125 */ } else if ((httpSession.getAttribute("SuperAdmin") == null) && ((httpSession.getAttribute("Admin") == null) || (httpSession.getAttribute("Admin").equals("SignUp"))) && (httpSession.getAttribute("User") != null)) {
/* 107:128 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/userhome.do");
/* 108: */ } else {
/* 109:130 */ filterChain.doFilter(request, response);
/* 110: */ }
/* 111: */ }
/* 112:132 */ else if (requestUrl.contains("/exam/"))
/* 113: */ {
/* 114:133 */ String URI = httpServletRequest.getRequestURI();
/* 115:134 */ URI = URLDecoder.decode(URI, "utf-8");
/* 116:135 */ String testurl = URI.substring(URI.lastIndexOf("/") + 1, URI.length());
/* 117:136 */ testurl = URLEncoder.encode(testurl, "utf-8");
/* 118:137 */ httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/usertest.do?testurl=" + testurl);
/* 119: */ }
/* 120: */ }
/* 121: */
/* 122: */ public void destroy() {}
/* 123: */
/* 124: */ private boolean isSessionInvalid(HttpServletRequest httpServletRequest)
/* 125: */ {
/* 126:215 */ boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null) && (!httpServletRequest.isRequestedSessionIdValid());
/* 127: */
/* 128:217 */ return sessionInValid;
/* 129: */ }
/* 130: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.common.util.UserSessionFilter
* JD-Core Version: 0.7.0.1
*/
|
package com.incuube.bot.model.income;
import com.incuube.bot.model.common.IncomeType;
import com.incuube.bot.model.income.util.Messengers;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public abstract class IncomeMessage {
private Map<String, Object> params = new HashMap<>();
private String userId;
private Messengers messenger;
private IncomeType incomeType;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.vianna.aula.appteatro.infrastructure.dao;
import br.vianna.aula.appteatro.domain.entities.Pergunta;
import br.vianna.aula.appteatro.infrastructure.data.DataContext;
import java.util.List;
import javax.persistence.Query;
/**
*
* @author marco
*/
public class PerguntaDAO extends DataContext {
private String src = "br.vianna.aula.appteatro.domain.entities.dto.";
public List<Pergunta> getAllPerguntas() {
Query q = getConexao().createQuery("SELECT NEW "
+ "" + src + "PesquisaDto(p.id,p.texto,p.date,p.resposta.descricao) "
+ "FROM Pergunta p");
return q.getResultList();
}
}
|
package com.project.database.entities;
import com.project.database.dto.statement.info.StatementFooter;
import com.project.database.dto.statement.info.StatementHeader;
import com.project.database.dto.statement.info.StatementStudent;
import lombok.*;
import java.util.List;
@Getter
@Setter
@AllArgsConstructor
@ToString
@EqualsAndHashCode
public class StatementStudentEntity {
private Integer studentId; // Example: 23,
private String studentSurname; // Example: "Бойчук Олег",
private String studentName; // Example: "Бойчук Олег",
private String studentPatronymic; // Example: "Романович",
private String studentRecordBook; // Example: "І 303/10 бп",
private Integer semesterGrade; // Example: 60,
private Integer controlGrade; // Example: 30,
private Integer totalGrade; // Example: null,
private String nationalGrade; // Example: "Добре",
private String ectsGrade; // Example: 'B'
}
|
package SwordOffer;
import java.util.LinkedList;
import java.util.Queue;
/**
* @author renyujie518
* @version 1.0.0
* @ClassName firstNoDuplicationInIO_41.java
* @Description 字符流中第一个不重复的字符
* 例如,当从字符流中只读出前两个字符 "go" 时,第一个只出现一次的字符是 "g"。
* 当从该字符流中读出前六个字符“google" 时,第一个只出现一次的字符是 "l"。
* @createTime 2021年08月24日 11:48:00
*/
public class firstNoDuplicationInIO_41 {
private int[] cnts = new int[256];
private Queue<Character> queue = new LinkedList<>();
public void Insert(char ch) {
cnts[ch]++;//构建字典表 对应的索引是相应的AscII,对应的值是出现的次数
queue.add(ch);
while (!queue.isEmpty() && cnts[queue.peek()] > 1) {//第一次出现的在队列的首(先进先出),该位置的值大于1就不是第一次出现,弹出
queue.poll();
}
}
public char firstNoDuplicationInIO(){
return queue.isEmpty() ? '@' : queue.peek();
}
}
|
package com.tencent.mm.plugin.wallet.balance.a.a;
import com.tencent.mm.plugin.wallet.balance.ui.lqt.WalletLqtSaveFetchUI;
import com.tencent.mm.plugin.wallet_core.model.Bankcard;
import com.tencent.mm.pluginsdk.wallet.h;
import com.tencent.mm.vending.g.b;
import com.tencent.mm.vending.g.g;
public final class o {
public static int oZi = 123;
public static int oZj = 456;
public int accountType;
public String bOe;
public b eAc;
private m oZk = null;
public n oZl = null;
public WalletLqtSaveFetchUI oZm = null;
public String oZn;
public int oZo;
public int oZp;
public String oZq;
public Bankcard oZr;
static /* synthetic */ void a(o oVar, String str, Bankcard bankcard) {
if (bankcard == null) {
bankcard = oVar.oZr;
}
oVar.eAc = g.cBF();
oVar.eAc.cBE();
h.a(oVar.oZm, bankcard != null ? bankcard.field_bindSerial : "", str, "", oVar.accountType == 0 ? 45 : 52, oZi);
}
public o(m mVar, n nVar, WalletLqtSaveFetchUI walletLqtSaveFetchUI) {
this.oZk = mVar;
this.oZl = nVar;
this.oZm = walletLqtSaveFetchUI;
}
}
|
package example;
import java.util.Collections;
import java.util.LinkedList;
public class ListExample {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>();
for (int i=0;i<10;i++){
ll.add(i);
}
System.out.println(ll);
System.out.println(ll.getLast());
System.out.println(ll.getFirst());
ll.addFirst(56);
ll.addLast(63);
Collections.sort(ll);
System.out.println(ll);
ll.removeFirst();
ll.removeLast();
System.out.println(ll);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.blood.view.buy;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import net.proteanit.sql.DbUtils;
/**
*
* @author Shishir
*/
public class Blood_sell_list extends javax.swing.JInternalFrame {
Connection con;
String url;
PreparedStatement pst;
Statement st;
ResultSet rs;
int tabrow;
int Table_click_phone;
/**
* Creates new form Donor_list
*/
public Blood_sell_list() {
super("Sell List");
initComponents();
database();
updateTable();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
public void buyexport() {
MessageFormat header = new MessageFormat("Buy Information Report.");
MessageFormat footer = new MessageFormat("Page{0,number,integer }");
try {
table_buy.print(JTable.PrintMode.NORMAL, header, footer);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Not Export.");
}
}
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
btn_close = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
table_buy = new javax.swing.JTable();
jLabel2 = new javax.swing.JLabel();
txt_search = new javax.swing.JTextField();
btn_search = new javax.swing.JButton();
btn_delete = new javax.swing.JButton();
btn_new = new javax.swing.JButton();
btn_print = new javax.swing.JButton();
btn_search1 = new javax.swing.JButton();
combo_type = new javax.swing.JComboBox<String>();
jLabel3 = new javax.swing.JLabel();
btn_reload = new javax.swing.JButton();
setClosable(true);
jPanel1.setBackground(new java.awt.Color(255, 102, 102));
btn_close.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_close.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/cancel.png"))); // NOI18N
btn_close.setText("Close");
btn_close.setToolTipText("Close");
btn_close.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_closeActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
jLabel1.setText("Blood Sell List");
table_buy.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
table_buy.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
table_buy.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
table_buyMouseClicked(evt);
}
});
jScrollPane1.setViewportView(table_buy);
jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel2.setText("Search:");
btn_search.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_search.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/search.png"))); // NOI18N
btn_search.setText("Search");
btn_search.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_searchActionPerformed(evt);
}
});
btn_delete.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/delete.png"))); // NOI18N
btn_delete.setText("Delete");
btn_delete.setToolTipText("Delete");
btn_delete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_deleteActionPerformed(evt);
}
});
btn_new.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_new.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/Buy.png"))); // NOI18N
btn_new.setText("Blood Sell");
btn_new.setToolTipText("Blood Sell");
btn_new.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_newActionPerformed(evt);
}
});
btn_print.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_print.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/print.png"))); // NOI18N
btn_print.setText("Print");
btn_print.setToolTipText("Print Blood Buy List");
btn_print.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_printActionPerformed(evt);
}
});
btn_search1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_search1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/search.png"))); // NOI18N
btn_search1.setText("Search");
btn_search1.setToolTipText("Search");
btn_search1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_search1ActionPerformed(evt);
}
});
combo_type.setFont(new java.awt.Font("Times New Roman", 0, 13)); // NOI18N
combo_type.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "A+", "A-", "B-", "B+", "O+", "O-", "AB+", "AB-" }));
combo_type.setToolTipText("Select Blood Type");
jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
jLabel3.setText("Blood Type:");
btn_reload.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
btn_reload.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/blood/photos/refresh.png"))); // NOI18N
btn_reload.setText("Reload");
btn_reload.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_reloadActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(btn_print, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(113, 113, 113)
.addComponent(btn_reload, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btn_new, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btn_delete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btn_close, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap())
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(246, 246, 246)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGap(265, 265, 265))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(combo_type, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_search1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(27, 27, 27)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(txt_search, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_search, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(combo_type, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(btn_search1))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(txt_search))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(btn_search, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGap(13, 13, 13)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_close, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_delete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_new, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_print, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btn_reload, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
setBounds(0, 0, 680, 456);
}// </editor-fold>//GEN-END:initComponents
private void btn_closeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_closeActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_btn_closeActionPerformed
private void btn_newActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_newActionPerformed
// TODO add your handling code here:
Blood_Sell bb = new Blood_Sell();
this.getDesktopPane().add(bb);
dispose();
bb.setVisible(true);
}//GEN-LAST:event_btn_newActionPerformed
private void btn_printActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_printActionPerformed
// TODO add your handling code here:
buyexport();
}//GEN-LAST:event_btn_printActionPerformed
private void btn_deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_deleteActionPerformed
// TODO add your handling code here:
deleteData();
}//GEN-LAST:event_btn_deleteActionPerformed
private void btn_reloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_reloadActionPerformed
// TODO add your handling code here:
updateTable();
}//GEN-LAST:event_btn_reloadActionPerformed
private void table_buyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_table_buyMouseClicked
// TODO add your handling code here:
tabrow = table_buy.getSelectedRow();
Table_click_phone = (int) (table_buy.getModel().getValueAt(tabrow, 2));
}//GEN-LAST:event_table_buyMouseClicked
private void btn_searchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_searchActionPerformed
// TODO add your handling code here:
searchTable();
}//GEN-LAST:event_btn_searchActionPerformed
private void btn_search1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_search1ActionPerformed
// TODO add your handling code here:
search_type();
}//GEN-LAST:event_btn_search1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_close;
private javax.swing.JButton btn_delete;
private javax.swing.JButton btn_new;
private javax.swing.JButton btn_print;
private javax.swing.JButton btn_reload;
private javax.swing.JButton btn_search;
private javax.swing.JButton btn_search1;
private javax.swing.JComboBox<String> combo_type;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable table_buy;
private javax.swing.JTextField txt_search;
// End of variables declaration//GEN-END:variables
public void database() {
try {
url = "jdbc:ucanaccess://blood.mdb";
con = DriverManager.getConnection(url);
} catch (Exception e) {
System.out.println("Could Not Connect to Database" + e);
}
}
private void updateTable() {
try {
String sql = "Select ID, buyer_name, buyer_phone, buyer_email, blood_type, blood_quantity, blood_price from blood_buy Order By ID";
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
table_buy.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
System.out.println(e);
JOptionPane.showMessageDialog(null, e);
}
}
private void searchTable() {
try {
String sql = "SELECT ID, buyer_name, buyer_phone, buyer_email, blood_type, blood_quantity, blood_price FROM blood_buy WHERE buyer_phone LIKE ?";
pst = con.prepareStatement(sql);
pst.setString(1, txt_search.getText());
rs = pst.executeQuery();
table_buy.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error TO collection data from Blood Buy Table");
}
}
private void deleteData() {
try {
String sql2 = "Delete from blood_buy where buyer_phone = '" + Table_click_phone + "'";
st = con.createStatement();
st.executeUpdate(sql2);
con.commit();
updateTable();
JOptionPane.showMessageDialog(null, "Buy Deleted.");
} catch (SQLException | HeadlessException e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void search_type() {
String type = (String) combo_type.getSelectedItem();
//search only depertment
try {
String sql = "SELECT ID, buyer_name, buyer_phone, buyer_email, blood_type, blood_quantity, blood_price FROM blood_buy WHERE blood_type LIKE ?";
pst = con.prepareStatement(sql);
pst.setString(1, (String) combo_type.getSelectedItem());
rs = pst.executeQuery();
table_buy.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error TO collection data from Blood Buy Table By search");
}
}
}
|
package com.javaforu.util.tuple;
/**
* Author: Ashwin Jayaprakash
* Email: ashwin.jayaprakash@gmail.com
* Web: http://www.ashwinjayaprakash.com
*/
/**
* A utility class for creating various length {@link Tuple}s.
*/
public class Tuples {
public static <X> Tuple<X> newTuple(X c0, X c1) {
return new Pair<>(c0, c1);
}
public static <X> Tuple<X> newTuple(X c0, X c1, X c2) {
return new Triple<>(c0, c1, c2);
}
public static <X> Tuple<X> newTuple(X c0, X c1, X c2, X c3) {
return new Quad<>(c0, c1, c2, c3);
}
@SafeVarargs
public static <X> Tuple<X> newTuple(X... xes) {
return new LargeFlexTuple<>(xes);
}
public static <X> Tuple<X> newTuple(int capacity) {
switch (capacity) {
case 2:
return newTuple(null, null);
case 3:
return newTuple(null, null, null);
case 4:
return newTuple(null, null, null, null);
default:
return new LargeFlexTuple<>(capacity);
}
}
}
|
import static org.junit.jupiter.api.Assertions.*;
/**
* Created by Костя on 31.01.2017.
*/
class ChildrenTest {
}
|
/*
* Copyright 2007 Bastian Schenke 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 nz.org.take.r2ml.reference;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import nz.org.take.r2ml.NameMapper;
import nz.org.take.r2ml.XmlTypeHandler;
import nz.org.take.r2ml.util.DataPredicates;
public class DefaultNameMapper implements NameMapper {
private Map<QName, String[]> slotNames = new HashMap<QName, String[]>();
private Map<QName, String> attrPredNames = new HashMap<QName, String>();
public DefaultNameMapper() {
addSlotNames(new QName(DataPredicates.NS_SWRLB, "equal"), new String[]{"equal1", "equal2"});
addSlotNames(new QName(DataPredicates.NS_SWRLB, "notEqual"), new String[]{"unEqual1", "unEqual2"});
addSlotNames(new QName(DataPredicates.NS_SWRLB, "greaterThan"), new String[]{"high", "low"});
addSlotNames(new QName(DataPredicates.NS_SWRLB, "lessThan"), new String[]{"low", "high"});
}
public String[] getSlotNames(QName predicateID) {
String[] names = slotNames.get(predicateID);
return names;
}
public void addSlotNames(QName predicateName, String[] names) {
this.slotNames.put(predicateName, names);
}
protected void addSlotNames(String predicateName, String[] names) {
addSlotNames(new QName("", predicateName), names);
}
public void addSlotNames(Map<QName, String[]> names) {
slotNames.putAll(names);
}
}
|
package com.project.backend.entità;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name= "caratteristicheStrutturaSt")
public class CaratteristicheStrutturaSt {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@ManyToOne(cascade = CascadeType.ALL)
private CaratteristicheQualitativeSt caratteristica;
@ManyToOne(cascade = CascadeType.ALL)
private StrutturaSt struttura;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public CaratteristicheQualitativeSt getCaratteristica() {
return caratteristica;
}
public void setCaratteristica(CaratteristicheQualitativeSt caratteristica) {
this.caratteristica = caratteristica;
}
public StrutturaSt getStruttura() {
return struttura;
}
public void setStruttura(StrutturaSt struttura) {
this.struttura = struttura;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class cgo extends a {
public LinkedList<bax> sAM = new LinkedList();
public LinkedList<app> sAN = new LinkedList();
protected final int a(int i, Object... objArr) {
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.d(1, 8, this.sAM);
aVar.d(2, 8, this.sAN);
return 0;
} else if (i == 1) {
return (f.a.a.a.c(1, 8, this.sAM) + 0) + f.a.a.a.c(2, 8, this.sAN);
} else {
byte[] bArr;
if (i == 2) {
bArr = (byte[]) objArr[0];
this.sAM.clear();
this.sAN.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (int a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
if (!super.a(aVar2, this, a)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
cgo cgo = (cgo) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
f.a.a.a.a aVar4;
boolean z;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bax bax = new bax();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bax.a(aVar4, bax, a.a(aVar4))) {
}
cgo.sAM.add(bax);
}
return 0;
case 2:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
app app = new app();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = app.a(aVar4, app, a.a(aVar4))) {
}
cgo.sAN.add(app);
}
return 0;
default:
return -1;
}
}
}
}
}
|
package ordo;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.UnicastRemoteObject ;
import java.net.InetAddress;
import map.*;
import config.* ;
import formats.Format;
import formats.Format.OpenMode;
import formats.Format.Type;
public class DaemonImpl_test extends UnicastRemoteObject implements Daemon {
private int id;
//constructeur
public DaemonImpl_test( int i) throws RemoteException {
this.id = i;
}
//methode distante
@Override
public void runMap(final Mapper m, final Format reader, final Format writer, final CallBack cb) throws RemoteException {
System.out.println(" deamon1");
// crée un thread secondaire qui execute de map pendant qu'on redonne la main au programme principal
Thread t = new Thread() {
public void run() {
try {
System.out.println(" deamon4");
mapInterne(m, reader, writer, cb);
System.out.println(" deamon9");
} catch (RemoteException e) {
System.out.println(" deamon_problème sur le Runmap");
e.printStackTrace();
}
}
};
//lancement du thread secondaire
System.out.println(" deamon2");
t.start();
System.out.println(" deamon3");
}
public void mapInterne (Mapper m, Format reader, Format writer, CallBack cb) throws RemoteException {
try {
//Ouverture du reader et du writer
System.out.println(" deamon5");
reader.open(OpenMode.R);
writer.open(OpenMode.W);
System.out.println(" deamon6");
//Appel de la fonction map
m.map(reader, writer);
System.out.println(" deamon7");
//Fermeture du reader et du writer
reader.close();
writer.close();
System.out.println(" deamon8");
//appel du callback à la fin de l'exécution
cb.MapFinished();
System.out.println(" deamon9");
} catch (Exception e) {
System.out.println(" deamon_erreur sur le mapInterne");
e.printStackTrace();
}
}
public static void main(String args[]) {
//argument = indice correspondant à l'ID
String machine = new String("vide"); //permet d'initialiser machine dans tout les cas
// sinon ça ne compile pas
// récupération de l'id
int id = Integer.parseInt(args[0]);
//récupération du numéro de port correspondant
int port =config.Project.numPortHidoop[id];
//récupération du nom complet de la machine surlequel est lancé le daemon
try {
machine = InetAddress.getLocalHost().getHostName();
}catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
//creation du serveur de nom
try {
Registry registry = LocateRegistry.createRegistry(port);
} catch (Exception e) {
System.out.println(" registre deja cree");
}
//enregistrement auprès du serveur de nom
try{
Naming.rebind("//"+machine+":"+port+"/Daemon", new DaemonImpl_test(id));
System.out.println("le Daemon numero "+id+" est lancé sur la machine "+machine+ ", au port "+port);
} catch (Exception e) {
System.out.println(" probleme sur l'enregistrement auprès du serveur de nom");
e.printStackTrace();
System.exit(0);
}
}
}
|
package com.example.stockspring.service;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import com.example.stockspring.model.User;
public interface UserService {
public void insertUser(User user) throws SQLException;
public List<User> findByuserName(String name);
}
|
package com.maven.event;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//声明配置类
@Configuration
@ComponentScan("com.maven.event") //自动扫描包下的所使用的Controller,Service,Repository,Component的类并注册bean
public class EventConfig {
}
|
/**
* @ClassName Userinfo.java
* @author He.Feng
* @version 2.3.7
* @Date 2018-08-01
* @Copyright(C): 2018 the author chen.biao All rights reserved.
*/
package com.pcms.domain;
/**
*
* @Title userinfo 实体类
* @author He.Feng
* @version 2.3.7
* @Date 2018-08-01
* @Copyright(C) 2018 www.sandpay.com.cn Inc. All rights reserved.
*/
public class Userinfo {
/**
* @Column userinfo.id
* @author He.Feng
* @version 2.3.7
* @Date 2018-08-01 16:58:49
*/
private Long id;
/**
* @Column userinfo.userName
* @author He.Feng
* @version 2.3.7
* @Date 2018-08-01 16:58:49
*/
private String username;
/**
* @Column userinfo.passWord
* @author He.Feng
* @version 2.3.7
* @Date 2018-08-01 16:58:49
*/
private String password;
/**
* @Description 获取字段:
*
* @Title getId
* @return userinfo.id
*
* @date 2018-08-01 16:58:49
*/
public Long getId() {
return id;
}
/**
* @Description 设置 字段:
*
* @Title setId
* @param id the value for userinfo.id
*
* @date 2018-08-01 16:58:49
*/
public void setId(Long id) {
this.id = id;
}
/**
* @Description 获取字段:
*
* @Title getUsername
* @return userinfo.userName
*
* @date 2018-08-01 16:58:49
*/
public String getUsername() {
return username;
}
/**
* @Description 设置 字段:
*
* @Title setUsername
* @param username the value for userinfo.userName
*
* @date 2018-08-01 16:58:49
*/
public void setUsername(String username) {
this.username = username == null ? null : username.trim();
}
/**
* @Description 获取字段:
*
* @Title getPassword
* @return userinfo.passWord
*
* @date 2018-08-01 16:58:49
*/
public String getPassword() {
return password;
}
/**
* @Description 设置 字段:
*
* @Title setPassword
* @param password the value for userinfo.passWord
*
* @date 2018-08-01 16:58:49
*/
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
/**
* @Description toString方法对应数据库记录:userinfo
*
* @date 2018-08-01 16:58:49
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", username=").append(username);
sb.append(", password=").append(password);
sb.append("]");
return sb.toString();
}
}
|
package com.mideas.rpg.v2.callback.old;
/*package com.mideas.rpg.v2.callback;
import com.mideas.rpg.v2.Mideas;
public class PlayerManaChangedCallback implements Callback {
@Override
public void handleCallback(Object ...obj) {
if(Mideas.joueur1() != null && Mideas.joueur1().getHasManaChanged()) {
Mideas.joueur1().setManaText(Mideas.joueur1().getMana()+" / "+Mideas.joueur1().getMaxMana());
Mideas.joueur1().setHasManaChanged(false);
}
}
}*/
|
/*
* 摇号时的操作类
*/
package controller;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import model.DataBase;
import model.FileText;
import model.RandomNumber;
public class GetCode
{
private GetCode() {}
public static String code = "";//存储随机号
//检测是否摇过号的方法
private static boolean checkGetCode()
{
if(FileText.getLineText(1).equals("0"))//没摇过
return false;
else//已经注册
return true;
}
//产生号码的方法
public static void getCode(JTextField textfield)
{
if(checkGetCode())
JOptionPane.showMessageDialog(null, "您已经注册过了!", "无服务提示", 1);
else
{
do
{
code = String.valueOf(RandomNumber.getOne(100000, 1000000000));
}//获得可以使用的随机号
while (DataBase.searchDataBase("user", "Code", code, "Nickname", true) != "");
textfield.setText(code);
}
}
}
|
/*
* Copyright (c) 2009-2011 by Bjoern Kolbeck,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.foundation.pbrpc.server;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.xtreemfs.foundation.LifeCycleThread;
import org.xtreemfs.foundation.SSLOptions;
import org.xtreemfs.foundation.buffer.BufferPool;
import org.xtreemfs.foundation.buffer.ReusableBuffer;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.channels.ChannelIO;
import org.xtreemfs.foundation.pbrpc.channels.SSLChannelIO;
import org.xtreemfs.foundation.pbrpc.channels.SSLHandshakeOnlyChannelIO;
import org.xtreemfs.foundation.util.OutputUtils;
/**
*
* @author bjko
*/
public class RPCNIOSocketServer extends LifeCycleThread implements RPCServerInterface {
/**
* Maximum number of record fragments supported.
*/
public static final int MAX_FRAGMENTS = 1;
/**
* Maximum fragment size to accept. If the size is larger, the connection is
* closed.
*/
public static final int MAX_FRAGMENT_SIZE = 1024 * 1024 * 32;
/**
* the server socket
*/
private final ServerSocketChannel socket;
/**
* Selector for server socket
*/
private final Selector selector;
/**
* If set to true thei main loop will exit upon next invocation
*/
private volatile boolean quit;
/**
* The receiver that gets all incoming requests.
*/
private volatile RPCServerRequestListener receiver;
/**
* sslOptions if SSL is enabled, null otherwise
*/
private final SSLOptions sslOptions;
/**
* Connection count
*/
private final AtomicInteger numConnections;
/**
* Number of requests received but not answered
*/
private long pendingRequests;
/**
* Port on which the server listens for incoming connections.
*/
private final int bindPort;
private final List<RPCNIOSocketServerConnection> connections;
/**
* maximum number of pending client requests to allow
*/
private final int maxClientQLength;
/**
* if the Q was full we need at least CLIENT_Q_THR spaces before we start
* reading from the client again. This is to prevent it from oscillating
*/
private final int clientQThreshold;
public static final int DEFAULT_MAX_CLIENT_Q_LENGTH = 100;
public RPCNIOSocketServer(int bindPort, InetAddress bindAddr, RPCServerRequestListener rl,
SSLOptions sslOptions) throws IOException {
this(bindPort, bindAddr, rl, sslOptions, -1);
}
public RPCNIOSocketServer(int bindPort, InetAddress bindAddr, RPCServerRequestListener rl,
SSLOptions sslOptions, int receiveBufferSize) throws IOException {
this(bindPort, bindAddr, rl, sslOptions, receiveBufferSize, DEFAULT_MAX_CLIENT_Q_LENGTH);
}
public RPCNIOSocketServer(int bindPort, InetAddress bindAddr, RPCServerRequestListener rl,
SSLOptions sslOptions, int receiveBufferSize,
int maxClientQLength) throws IOException {
super("PBRPCSrv@" + bindPort);
// open server socket
socket = ServerSocketChannel.open();
socket.configureBlocking(false);
if (receiveBufferSize != -1) {
socket.socket().setReceiveBufferSize(receiveBufferSize);
try {
if (socket.socket().getReceiveBufferSize() != receiveBufferSize) {
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"could not set socket receive buffer size to " + receiveBufferSize
+ ", using default size of " + socket.socket().getReceiveBufferSize());
}
} catch (SocketException exc) {
Logging.logMessage(Logging.LEVEL_WARN, this,
"could not check whether receive buffer size was successfully set to %d bytes", receiveBufferSize);
}
} else {
socket.socket().setReceiveBufferSize(256 * 1024);
}
socket.socket().setReuseAddress(true);
try {
socket.socket().bind(
bindAddr == null ? new InetSocketAddress(bindPort) : new InetSocketAddress(bindAddr, bindPort));
} catch (BindException e) {
// Rethrow exception with the failed port number.
throw new BindException(e.getMessage() + ". Port number: " + bindPort);
}
this.bindPort = bindPort;
// create a selector and register socket
selector = Selector.open();
socket.register(selector, SelectionKey.OP_ACCEPT);
// server is ready to accept connections now
this.receiver = rl;
this.sslOptions = sslOptions;
this.numConnections = new AtomicInteger(0);
this.connections = new LinkedList<RPCNIOSocketServerConnection>();
this.maxClientQLength = maxClientQLength;
this.clientQThreshold = (maxClientQLength/2 >= 0) ? maxClientQLength/2 : 0;
if (maxClientQLength <= 1) {
Logging.logMessage(Logging.LEVEL_WARN, this, "max client queue length is 1, pipelining is disabled.");
}
}
/**
* Stop the server and close all connections.
*/
@Override
public void shutdown() {
this.quit = true;
this.interrupt();
}
/**
* sends a response.
*
* @param request
* the request
*/
@Override
public void sendResponse(RPCServerRequest request, RPCServerResponse response) {
assert (response != null);
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "response sent");
final RPCNIOSocketServerConnection connection = (RPCNIOSocketServerConnection)request.getConnection();
try {
request.freeBuffers();
} catch (AssertionError ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this, "Caught an AssertionError while trying to free buffers:");
Logging.logError(Logging.LEVEL_INFO, this, ex);
}
}
assert (connection.getServer() == this);
if (!connection.isConnectionClosed()) {
synchronized (connection) {
boolean isEmpty = connection.getPendingResponses().isEmpty();
connection.addPendingResponse(response);
if (isEmpty) {
final SelectionKey key = connection.getChannel().keyFor(selector);
if (key != null) {
try {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} catch (CancelledKeyException e) {
// Ignore it since the timeout mechanism will deal with it.
}
}
selector.wakeup();
}
}
} else {
// ignore and free bufers
response.freeBuffers();
}
}
@Override
public void run() {
notifyStarted();
if (Logging.isInfo()) {
String sslMode = "";
if (sslOptions != null) {
if (sslOptions.isFakeSSLMode()) {
sslMode = "GRID SSL mode enabled (SSL handshake only)";
} else {
sslMode = "SSL enabled";
}
}
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this, "PBRPC Srv %d ready %s", bindPort,sslMode);
}
try {
while (!quit) {
// try to select events...
int numKeys = 0;
try {
numKeys = selector.select();
} catch (CancelledKeyException ex) {
// who cares
} catch (IOException ex) {
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"Exception while selecting: %s", ex.toString());
continue;
}
if (numKeys > 0) {
// fetch events
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> iter = keys.iterator();
// process all events
while (iter.hasNext()) {
SelectionKey key = iter.next();
// remove key from the list
iter.remove();
try {
if (key.isAcceptable()) {
acceptConnection(key);
}
if (key.isReadable()) {
readConnection(key);
}
if (key.isWritable()) {
writeConnection(key);
}
} catch (CancelledKeyException ex) {
// nobody cares...
continue;
}
}
}
}
for (RPCNIOSocketServerConnection con : connections) {
try {
con.getChannel().close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
// close socket
selector.close();
socket.close();
if (Logging.isInfo())
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"PBRPC Server %d shutdown complete", bindPort);
notifyStopped();
} catch (Throwable thr) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net, this, "PBRPC Server %d CRASHED!", bindPort);
notifyCrashed(thr);
}
}
/**
* read data from a readable connection
*
* @param key
* a readable key
*/
private void readConnection(SelectionKey key) {
final RPCNIOSocketServerConnection con = (RPCNIOSocketServerConnection) key.attachment();
final ChannelIO channel = con.getChannel();
try {
if (!channel.isShutdownInProgress()) {
if (channel.doHandshake(key)) {
while (true) {
if (con.getOpenRequests().get() > maxClientQLength) {
key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"client sent too many requests... not accepting new requests from %s, q=%d", con
.getChannel().socket().getRemoteSocketAddress().toString(), con.getOpenRequests().get());
return;
}
ByteBuffer buf = null;
switch (con.getReceiveState()) {
case RECORD_MARKER: {
buf = con.getReceiveRecordMarker(); break;
}
case RPC_MESSAGE: {
buf = con.getReceiveBuffers()[1].getBuffer(); break;
}
case RPC_HEADER: {
buf = con.getReceiveBuffers()[0].getBuffer(); break;
}
case DATA: {
buf = con.getReceiveBuffers()[2].getBuffer(); break;
}
}
// read fragment header
final int numBytesRead = readData(key, channel, buf);
if (numBytesRead == -1) {
// connection closed
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"client closed connection (EOF): %s", channel.socket()
.getRemoteSocketAddress().toString());
}
closeConnection(key);
return;
}
if (buf.hasRemaining()) {
// not enough data...
break;
}
switch (con.getReceiveState()) {
case RECORD_MARKER: {
buf.position(0);
final int hdrLen = buf.getInt();
final int msgLen = buf.getInt();
final int dataLen = buf.getInt();
if ((hdrLen <= 0) || (hdrLen >= MAX_FRAGMENT_SIZE)
|| (msgLen < 0) || (msgLen >= MAX_FRAGMENT_SIZE)
|| (dataLen < 0) || (dataLen >= MAX_FRAGMENT_SIZE)) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net, this,
"invalid record marker size (%d/%d/%d) received, closing connection to client %s",
hdrLen,msgLen,dataLen,channel.socket()
.getRemoteSocketAddress().toString());
closeConnection(key);
return;
}
final ReusableBuffer[] buffers = new ReusableBuffer[]{BufferPool.allocate(hdrLen),
((msgLen > 0) ? BufferPool.allocate(msgLen) : null),
((dataLen > 0) ? BufferPool.allocate(dataLen) : null) };
con.setReceiveBuffers(buffers);
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RPC_HEADER);
continue;
}
case RPC_HEADER: {
if (con.getReceiveBuffers()[1] != null) {
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RPC_MESSAGE);
continue;
} else {
if (con.getReceiveBuffers()[2] != null) {
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.DATA);
continue;
} else {
break;
}
}
}
case RPC_MESSAGE: {
if (con.getReceiveBuffers()[2] != null) {
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.DATA);
continue;
} else {
break;
}
}
}
//assemble ServerRequest
con.setReceiveState(RPCNIOSocketServerConnection.ReceiveState.RECORD_MARKER);
con.getReceiveRecordMarker().clear();
ReusableBuffer[] receiveBuffers = con.getReceiveBuffers();
receiveBuffers[0].flip();
if (receiveBuffers[1] != null)
receiveBuffers[1].flip();
if (receiveBuffers[2] != null)
receiveBuffers[2].flip();
con.setReceiveBuffers(null);
RPCServerRequest rq = null;
try {
rq = new RPCServerRequest(con, receiveBuffers[0], receiveBuffers[1], receiveBuffers[2]);
} catch (IOException ex) {
// close connection if the header cannot be parsed
Logging.logMessage(Logging.LEVEL_ERROR, Category.net,this,"invalid PBRPC header received: "+ex);
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this,ex);
}
closeConnection(key);
BufferPool.free(receiveBuffers[1]);
BufferPool.free(receiveBuffers[2]);
return;
}
// request is
// complete... send to receiver
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, rq
.toString());
}
con.getOpenRequests().incrementAndGet();
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"request received");
pendingRequests++;
if (!receiveRequest(key, rq, con)) {
closeConnection(key);
return;
}
}
}
}
} catch (CancelledKeyException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (CancelledKeyException): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
closeConnection(key);
} catch (ClosedByInterruptException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"connection to %s closed by remote peer", con.getChannel().socket()
.getRemoteSocketAddress().toString());
}
closeConnection(key);
} catch (IOException ex) {
// simply close the connection
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, OutputUtils
.stackTraceToString(ex));
}
closeConnection(key);
}
}
/**
* write data to a writeable connection
*
* @param key
* the writable key
*/
private void writeConnection(SelectionKey key) {
final RPCNIOSocketServerConnection con = (RPCNIOSocketServerConnection) key.attachment();
final ChannelIO channel = con.getChannel();
try {
if (!channel.isShutdownInProgress()) {
if (channel.doHandshake(key)) {
while (true) {
// final ByteBuffer fragmentHeader =
// con.getSendFragHdr();
ByteBuffer[] response = con.getSendBuffers();
if (response == null) {
synchronized (con) {
RPCServerResponse rq = con.getPendingResponses().peek();
if (rq == null) {
// no more responses, stop writing...
con.setSendBuffers(null);
key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
break;
}
response = rq.packBuffers(con.getSendFragHdr());
con.setSendBuffers(response);
con.setExpectedRecordSize(rq.getRpcMessageSize());
}
}
/*
* if (fragmentHeader.hasRemaining()) { final int
* numBytesWritten = writeData(key, channel,
* fragmentHeader); if (numBytesWritten == -1) {
* //connection closed closeConnection(key); return; }
* if (fragmentHeader.hasRemaining()) { //not enough
* data... break; } //finished sending... send fragment
* data now... } else {
*/
// send fragment data
assert(response != null);
final long numBytesWritten = channel.write(response);
if (numBytesWritten == -1) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket()
.getRemoteSocketAddress().toString());
}
// connection closed
closeConnection(key);
return;
}
con.recordBytesSent(numBytesWritten);
if (response[response.length-1].hasRemaining()) {
// not enough data...
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
break;
}
con.checkEnoughBytesSent();
// finished sending fragment
// clean up :-) request finished
pendingRequests--;
RPCServerResponse rq = con.getPendingResponses().poll();
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"sent response for %s", rq.toString());
}
rq.freeBuffers();
con.setSendBuffers(null);
con.getSendFragHdr().clear();
int numRq = con.getOpenRequests().decrementAndGet();
if ((key.interestOps() & SelectionKey.OP_READ) == 0) {
if (numRq < clientQThreshold) {
// read from client again
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
Logging.logMessage(Logging.LEVEL_WARN, Category.net, this,
"client allowed to send data again: %s, q=%d", con.getChannel().socket()
.getRemoteSocketAddress().toString(), numRq);
}
}
continue;
}
}
}
} catch (CancelledKeyException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (CancelledKeyException): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
closeConnection(key);
} catch (ClosedByInterruptException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection (EOF): %s", channel.socket().getRemoteSocketAddress()
.toString());
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"connection to %s closed by remote peer", con.getChannel().socket()
.getRemoteSocketAddress().toString());
}
closeConnection(key);
} catch (IOException ex) {
// simply close the connection
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, OutputUtils
.stackTraceToString(ex));
}
closeConnection(key);
}
}
/**
* Reads data from the socket, ensures that SSL connection is ready
*
* @param key
* the SelectionKey
* @param channel
* the channel to read from
* @param buf
* the buffer to read to
* @return number of bytes read, -1 on EOF
* @throws java.io.IOException
*/
public static int readData(SelectionKey key, ChannelIO channel, ByteBuffer buf) throws IOException {
return channel.read(buf);
/*
* if (!channel.isShutdownInProgress()) { if (channel.doHandshake(key))
* { return channel.read(buf); } else { return 0; } } else { return 0; }
*/
}
public static int writeData(SelectionKey key, ChannelIO channel, ByteBuffer buf) throws IOException {
return channel.write(buf);
/*
* if (!channel.isShutdownInProgress()) { if (channel.doHandshake(key))
* { return channel.write(buf); } else { return 0; } } else { return 0;
* }
*/
}
/**
* close a connection
*
* @param key
* matching key
*/
private void closeConnection(SelectionKey key) {
final RPCNIOSocketServerConnection con = (RPCNIOSocketServerConnection) key.attachment();
final ChannelIO channel = con.getChannel();
// remove the connection from the selector and close socket
try {
connections.remove(con);
con.setConnectionClosed(true);
key.cancel();
channel.close();
} catch (Exception ex) {
} finally {
// adjust connection count and make sure buffers are freed
numConnections.decrementAndGet();
con.freeBuffers();
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "closing connection to %s", channel
.socket().getRemoteSocketAddress().toString());
}
}
/**
* accept a new incomming connection
*
* @param key
* the acceptable key
*/
private void acceptConnection(SelectionKey key) {
SocketChannel client = null;
RPCNIOSocketServerConnection con = null;
ChannelIO channelIO = null;
// FIXME: Better exception handling!
try {
// accept that connection
client = socket.accept();
if (sslOptions == null) {
channelIO = new ChannelIO(client);
} else {
if (sslOptions.isFakeSSLMode()) {
channelIO = new SSLHandshakeOnlyChannelIO(client, sslOptions, false);
} else {
channelIO = new SSLChannelIO(client, sslOptions, false);
}
}
con = new RPCNIOSocketServerConnection(this,channelIO);
// and configure it to be non blocking
// IMPORTANT!
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ, con);
client.socket().setTcpNoDelay(true);
numConnections.incrementAndGet();
this.connections.add(con);
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this, "connect from client at %s",
client.socket().getRemoteSocketAddress().toString());
}
} catch (ClosedChannelException ex) {
if (Logging.isInfo()) {
Logging.logMessage(Logging.LEVEL_INFO, Category.net, this,
"client closed connection during accept");
}
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"cannot establish connection: %s", ex.toString());
if (channelIO != null) {
try {
channelIO.close();
} catch (IOException ex2) {
}
}
} catch (IOException ex) {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"cannot establish connection: %s", ex.toString());
if (channelIO != null) {
try {
channelIO.close();
} catch (IOException ex2) {
}
}
}
}
/**
*
* @param key
* @param request
* @param con
* @return true on success, false on error
*/
private boolean receiveRequest(SelectionKey key, RPCServerRequest request, RPCNIOSocketServerConnection con) {
try {
request.getHeader();
receiver.receiveRecord(request);
return true;
} catch (IllegalArgumentException ex) {
Logging.logMessage(Logging.LEVEL_ERROR, Category.net,this,"invalid PBRPC header received: "+ex);
if (Logging.isDebug()) {
Logging.logError(Logging.LEVEL_DEBUG, this,ex);
}
return false;
//closeConnection(key);
}
}
public int getNumConnections() {
return this.numConnections.get();
}
public long getPendingRequests() {
return this.pendingRequests;
}
/**
* Updates the listener. Handle with care.
*
* @param rl
*/
public void updateRequestDispatcher(RPCServerRequestListener rl) {
this.receiver = rl;
}
}
|
package com.rex.demo.study.demo.sink;
import com.alibaba.fastjson.JSON;
import com.rex.demo.study.demo.entity.Student;
import com.rex.demo.study.demo.util.DBConnectUtil;
import com.rex.demo.study.demo.util.DruidConnectionPool;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeutils.base.VoidSerializer;
import org.apache.flink.api.java.typeutils.runtime.kryo.JavaSerializer;
import org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.functions.sink.TwoPhaseCommitSinkFunction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
*
* @Author li zhiqang
* @create 2020/11/26
*/
public class MySqlTwoPhaseCommitSink extends TwoPhaseCommitSinkFunction<ObjectNode, Connection, Void> {
public MySqlTwoPhaseCommitSink() {
super(new KryoSerializer<>(Connection.class, new ExecutionConfig()), VoidSerializer.INSTANCE);
// super(new JavaSerializer<ObjectNode>(), VoidSerializer.INSTANCE);
}
/**
* 执行数据入库操作
* @param connection
* @param objectNode
* @param context
* @throws Exception
*/
@Override
protected void invoke(Connection connection, ObjectNode objectNode, SinkFunction.Context context) throws Exception {
System.err.println("start invoke.......");
String stu = objectNode.get("value").toString();
Student student = JSON.parseObject(stu, Student.class);
String sql = "insert into student(id,name,password,age) values (?,?,?,?)";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, student.getId());
ps.setString(2, student.getName());
ps.setString(3, student.getPassword());
ps.setInt(4, student.getAge());
// ps.executeUpdate();
ps.execute();
}
/**
* 获取连接,开启手动提交事物(getConnection方法中)
* @return
* @throws Exception
*/
@Override
protected Connection beginTransaction() throws Exception {
//使用单个连接
// String url = "jdbc:mysql://172.26.55.109:3306/dc?characterEncoding=utf8&useSSL=false";
// Connection connection = DBConnectUtil.getConnection(url, "root", "t4*9&/y?c,h.e17!");
//使用连接池,不使用单个连接
Connection connection = DruidConnectionPool.getConnection();
connection.setAutoCommit(false);//关闭自动提交
System.err.println("start beginTransaction......."+connection);
return connection;
}
/**
* 预提交,这里预提交的逻辑在invoke方法中
* @param connection
* @throws Exception
*/
@Override
protected void preCommit(Connection connection) throws Exception {
System.err.println("start preCommit......."+connection);
}
/**
* 如果invoke执行正常则提交事物
* @param connection
*/
@Override
protected void commit(Connection connection) {
System.err.println("start commit......."+connection);
DBConnectUtil.commit(connection);
}
@Override
protected void recoverAndCommit(Connection connection) {
System.err.println("start recoverAndCommit......."+connection);
}
@Override
protected void recoverAndAbort(Connection connection) {
System.err.println("start abort recoverAndAbort......."+connection);
}
/**
* 如果invoke执行异常则回滚事物,下一次的checkpoint操作也不会执行
* @param connection
*/
@Override
protected void abort(Connection connection) {
System.err.println("start abort rollback......."+connection);
DBConnectUtil.rollback(connection);
}
}
|
package com.IRCTradingDataGenerator.tradingDataGenerator.Models;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.util.Objects;
@Entity
@Table(name = "trade")
public class Trade {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int trade_Id;
@Column
private String trade_type;
@Column
private String trade_quality;
@Column
private String trade_level;
@Column
private String action_type;
@Column
private String reporting_timestamp;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "trade_transaction", referencedColumnName = "transaction_id")
private Transaction trade_transaction;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "trade_counterparty", referencedColumnName = "counterparty_id")
private Counterparty trade_counterparty;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "trade_collateral", referencedColumnName = "collateral_id")
private Collateral trade_collateral;
@OneToOne(cascade = CascadeType.MERGE)
@JoinColumn(name = "trade_principle", referencedColumnName = "principle_id")
private Principle trade_principle;
public Trade() {
super();
}
public Trade(String trade_type, String trade_quality, String trade_level, String action_type,
String reporting_timestamp, Transaction trade_transaction, Counterparty trade_counterparty,
Collateral trade_collateral, Principle trade_principle) {
this.trade_type = trade_type;
this.trade_quality = trade_quality;
this.trade_level = trade_level;
this.action_type = action_type;
this.reporting_timestamp = reporting_timestamp;
this.trade_transaction = trade_transaction;
this.trade_counterparty = trade_counterparty;
this.trade_collateral = trade_collateral;
this.trade_principle = trade_principle;
}
public int getTrade_Id() {
return trade_Id;
}
public void setTrade_Id(int trade_Id) {
this.trade_Id = trade_Id;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public String getTrade_quality() {
return trade_quality;
}
public void setTrade_quality(String trade_quality) {
this.trade_quality = trade_quality;
}
public String getTrade_level() {
return trade_level;
}
public void setTrade_level(String trade_level) {
this.trade_level = trade_level;
}
public String getAction_type() {
return action_type;
}
public void setAction_type(String action_type) {
this.action_type = action_type;
}
public String getReporting_timestamp() {
return reporting_timestamp;
}
public void setReporting_timestamp(String reporting_timestamp) {
this.reporting_timestamp = reporting_timestamp;
}
public Transaction getTrade_transaction() {
return trade_transaction;
}
public void setTrade_transaction(Transaction trade_transaction) {
this.trade_transaction = trade_transaction;
}
public Counterparty getTrade_counterparty() {
return trade_counterparty;
}
public void setTrade_counterparty(Counterparty trade_counterparty) {
this.trade_counterparty = trade_counterparty;
}
public Collateral getTrade_collateral() {
return trade_collateral;
}
public void setTrade_collateral(Collateral trade_collateral) {
this.trade_collateral = trade_collateral;
}
public Principle getTrade_principle() {
return trade_principle;
}
public void setTrade_principle(Principle trade_principle) {
this.trade_principle = trade_principle;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Trade trade = (Trade) o;
return trade_Id == trade.trade_Id &&
Objects.equals(trade_type, trade.trade_type) &&
Objects.equals(trade_quality, trade.trade_quality) &&
Objects.equals(trade_level, trade.trade_level) &&
Objects.equals(action_type, trade.action_type) &&
Objects.equals(reporting_timestamp, trade.reporting_timestamp) &&
Objects.equals(trade_transaction, trade.trade_transaction) &&
Objects.equals(trade_counterparty, trade.trade_counterparty) &&
Objects.equals(trade_collateral, trade.trade_collateral) &&
Objects.equals(trade_principle, trade.trade_principle);
}
@Override
public int hashCode() {
return Objects.hash(trade_Id, trade_type, trade_quality, trade_level, action_type, reporting_timestamp, trade_transaction, trade_counterparty, trade_collateral, trade_principle);
}
@Override
public String toString() {
return "Trade{" +
"trade_Id=" + trade_Id +
", trade_type='" + trade_type + '\'' +
", trade_quality='" + trade_quality + '\'' +
", trade_level='" + trade_level + '\'' +
", action_type='" + action_type + '\'' +
", reporting_timestamp='" + reporting_timestamp + '\'' +
", trade_transaction=" + trade_transaction +
", trade_counterparty=" + trade_counterparty +
", trade_collateral=" + trade_collateral +
", trade_principle=" + trade_principle +
'}';
}
}
|
// Sun Certified Java Programmer
// Chapter 5, P340_2
// Flow Control, Exceptions, and Assertions
class Tester340_2 {
public static void main(String[] args) {
//int x = someNumberBetweenOneAndTen;
int x = 8;
switch (x) {
case 2:
case 4:
case 6:
case 8:
case 10: {
System.out.println("x is an even number");
break;
}
}
}
}
|
//****************** October 13 *****************
package JavaSessions;
public class FunctionsInJava {
public static void main(String[] args) {
// Functions and methods are synonyms
// Functions will reduce code
//We can achieve reuseability using functions
//Functions are independent of each other
//Functions are parallel to each other
//We can't create a function inside a function
//main()method is also a function
//Functions are created inside the class
//we can call a function from another function
//a function can or cant return anything
FunctionsInJava obj=new FunctionsInJava();
obj.test();
//FunctionsInJava obj1=new FunctionsInJava();
//obj1.test();
obj.printName();
obj.total();
int sum=obj.add();
System.out.println(sum+5-10);
System.out.println(obj.add());
String city=obj.printCityName();
System.out.println(city);
int s1=obj.getSum(90, 20);
System.out.println(s1);
int s2=obj.getSum(900, 20);
System.out.println(s2);
String cityName=obj.getCapitalName("UA");
System.out.println(cityName);
String cityName2=obj.getCapitalName("USA");
System.out.println(cityName2);
int m=obj.getStudentMarks("Uttam");
System.out.println(m);
if(obj.launchBrowser("IE")) {
System.out.println("start executing test casess");
}else {
System.out.println("Test cases not executed");
}
}
//public -> publicly accessible
//void -> doesnt return anything
//Functions - 3 types
//1. no input and no return
public void test() {
System.out.println("Inside test method");
}
//naming convention -camel case : lowerUpper
public void printName() {
System.out.println("Java and Selenium");
}
public void total() {
System.out.println("Inside total method");
int x=10;
int y=20;
int z=x+y;
System.out.println(z);
}
//2. no input and some return
public int add() {
System.out.println("Inside add method");
int a=100;
int b=200;
int c=a+b;
return c;//c=300
}
//a method can return only one value at a time.
public String printCityName() {
System.out.println("Print city name");
String cityName="Montreal";
int t=100;
return cityName;
//return t;
}
//3. some input and some return
public int getSum(int a, int b) {
System.out.println("inside getSum method");
int sum=a+b;
return sum;
}
//WAP to get the capital name of a country
public String getCapitalName(String countryName) {
System.out.println("Getting capital name for " + countryName );
if(countryName.equals("India")){
return "New Delhi";
}else if(countryName.equals("USA")) {
return "Washington DC";
}else if(countryName.equals("UK")) {
return "London";
}else {
System.out.println("Country name not listed");
return null;
}
}
//WAM where I will be passing a student name(String) and then function should
//return the marks(int) of that student.
//some input and some output
public int getStudentMarks(String name) {
int marks=0;
//null is used for strings and objects
System.out.println("getting marks for student " +name);
if(name.equals("Mohan")) {
marks=90;
}
else if(name.equals("Kanika")) {
marks=95;
}
else if(name.equals("Pratik")) {
marks=100;
}
else if(name.equals("Manish")) {
marks=10;
}
else {
System.out.println("This student not found in the database");
return -1;
}
return marks;
}
// WAM where we will pass the browsername and launch the browser
//use switch statement
public boolean launchBrowser(String browserName) {
System.out.println("Launching browser: " +browserName);
boolean flag=false;
switch (browserName) {
case "chrome":
System.out.println("launching chrome");
flag=true;
break;
case "firefox":
System.out.println("launching firefox");
flag=true;
break;
case "safari":
System.out.println("launching safari");
flag=true;
break;
default:
System.out.println("browser not found");
break;
}
return flag;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mmt11.tuan3;
/**
*
* @author Dell
*/
public class DEMOtinhtoan extends javax.swing.JFrame {
/**
* Creates new form DEMOtinhtoan
*/
public DEMOtinhtoan() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox<>();
JPtren = new javax.swing.JPanel();
tieude = new javax.swing.JButton();
jPcuoi = new javax.swing.JPanel();
c1 = new javax.swing.JButton();
c2 = new javax.swing.JButton();
c3 = new javax.swing.JButton();
jPgiua = new javax.swing.JPanel();
thaotac = new javax.swing.JPanel();
tacvu = new javax.swing.JButton();
giai = new javax.swing.JButton();
xoa = new javax.swing.JButton();
thoat = new javax.swing.JButton();
jPanel5 = new javax.swing.JPanel();
nhâp = new javax.swing.JLabel();
nhapb = new javax.swing.JLabel();
jPanel6 = new javax.swing.JPanel();
pheptoan = new javax.swing.JLabel();
cong = new javax.swing.JRadioButton();
nhan = new javax.swing.JRadioButton();
tru = new javax.swing.JRadioButton();
chia = new javax.swing.JRadioButton();
so6 = new javax.swing.JButton();
so7 = new javax.swing.JButton();
ketqua = new javax.swing.JLabel();
xuatkqua = new javax.swing.JButton();
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
JPtren.setBackground(new java.awt.Color(255, 255, 51));
tieude.setBackground(new java.awt.Color(255, 153, 51));
tieude.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
tieude.setForeground(new java.awt.Color(255, 0, 204));
tieude.setText("CỘNG TRỪ NHÂN CHIA");
tieude.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tieudeActionPerformed(evt);
}
});
JPtren.add(tieude);
getContentPane().add(JPtren, java.awt.BorderLayout.PAGE_START);
jPcuoi.setBackground(new java.awt.Color(204, 204, 255));
jPcuoi.setForeground(new java.awt.Color(255, 153, 153));
c1.setBackground(new java.awt.Color(204, 0, 51));
c1.setForeground(new java.awt.Color(204, 0, 0));
c2.setBackground(new java.awt.Color(255, 102, 102));
c2.setForeground(new java.awt.Color(102, 255, 102));
c2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
c2ActionPerformed(evt);
}
});
c3.setBackground(new java.awt.Color(255, 0, 0));
javax.swing.GroupLayout jPcuoiLayout = new javax.swing.GroupLayout(jPcuoi);
jPcuoi.setLayout(jPcuoiLayout);
jPcuoiLayout.setHorizontalGroup(
jPcuoiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPcuoiLayout.createSequentialGroup()
.addGap(180, 180, 180)
.addComponent(c1)
.addGap(35, 35, 35)
.addComponent(c2)
.addGap(35, 35, 35)
.addComponent(c3)
.addContainerGap(200, Short.MAX_VALUE))
);
jPcuoiLayout.setVerticalGroup(
jPcuoiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPcuoiLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(jPcuoiLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(c1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(c2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(c3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(46, Short.MAX_VALUE))
);
getContentPane().add(jPcuoi, java.awt.BorderLayout.PAGE_END);
jPgiua.setBackground(new java.awt.Color(255, 51, 51));
thaotac.setToolTipText("");
thaotac.setName("Tác Vụ"); // NOI18N
tacvu.setForeground(new java.awt.Color(255, 0, 51));
tacvu.setText("Tác Vụ");
giai.setForeground(new java.awt.Color(0, 102, 204));
giai.setText("Giải");
giai.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
giaiActionPerformed(evt);
}
});
xoa.setForeground(new java.awt.Color(0, 51, 51));
xoa.setText("Xóa");
thoat.setForeground(new java.awt.Color(255, 102, 102));
thoat.setText("Thoát");
javax.swing.GroupLayout thaotacLayout = new javax.swing.GroupLayout(thaotac);
thaotac.setLayout(thaotacLayout);
thaotacLayout.setHorizontalGroup(
thaotacLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(thaotacLayout.createSequentialGroup()
.addContainerGap()
.addGroup(thaotacLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tacvu)
.addGroup(thaotacLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addGroup(thaotacLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(xoa)
.addComponent(giai))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, thaotacLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(thoat)
.addContainerGap())
);
thaotacLayout.setVerticalGroup(
thaotacLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(thaotacLayout.createSequentialGroup()
.addComponent(tacvu)
.addGap(4, 4, 4)
.addComponent(giai)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(xoa)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(thoat)
.addGap(0, 0, Short.MAX_VALUE))
);
nhâp.setText("nhập a:");
nhapb.setText("nhập b:");
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(nhapb)
.addComponent(nhâp))
.addGap(29, 29, 29))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(nhâp)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nhapb)
.addContainerGap(83, Short.MAX_VALUE))
);
jPanel6.setBackground(new java.awt.Color(102, 255, 153));
pheptoan.setText("Phép Toán");
cong.setSelected(true);
cong.setText("Cộng");
nhan.setText("Nhân");
tru.setText("Trừ");
chia.setText("Chia");
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addGap(23, 23, 23)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(nhan)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(chia))
.addGroup(jPanel6Layout.createSequentialGroup()
.addComponent(cong)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tru)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pheptoan)
.addGap(25, 25, 25))
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel6Layout.createSequentialGroup()
.addContainerGap()
.addComponent(pheptoan)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cong)
.addComponent(tru))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nhan)
.addComponent(chia))
.addContainerGap(19, Short.MAX_VALUE))
);
so6.setText("6");
so7.setText("7");
ketqua.setText("Kết Quả:");
xuatkqua.setText("13");
javax.swing.GroupLayout jPgiuaLayout = new javax.swing.GroupLayout(jPgiua);
jPgiua.setLayout(jPgiuaLayout);
jPgiuaLayout.setHorizontalGroup(
jPgiuaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPgiuaLayout.createSequentialGroup()
.addComponent(thaotac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(117, 117, 117)
.addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPgiuaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPgiuaLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPgiuaLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPgiuaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(so6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(so7, javax.swing.GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE))))
.addGap(58, 58, 58))
.addGroup(jPgiuaLayout.createSequentialGroup()
.addGap(210, 210, 210)
.addComponent(ketqua)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(xuatkqua, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(64, Short.MAX_VALUE))
);
jPgiuaLayout.setVerticalGroup(
jPgiuaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPgiuaLayout.createSequentialGroup()
.addComponent(thaotac, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPgiuaLayout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPgiuaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(ketqua)
.addComponent(xuatkqua))
.addGap(43, 43, 43))
.addGroup(jPgiuaLayout.createSequentialGroup()
.addGap(33, 33, 33)
.addComponent(so6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(so7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(103, 103, 103))
);
getContentPane().add(jPgiua, java.awt.BorderLayout.CENTER);
pack();
}// </editor-fold>//GEN-END:initComponents
private void c2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_c2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_c2ActionPerformed
private void tieudeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tieudeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tieudeActionPerformed
private void giaiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_giaiActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_giaiActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DEMOtinhtoan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DEMOtinhtoan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DEMOtinhtoan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DEMOtinhtoan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DEMOtinhtoan().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel JPtren;
private javax.swing.JButton c1;
private javax.swing.JButton c2;
private javax.swing.JButton c3;
private javax.swing.JRadioButton chia;
private javax.swing.JRadioButton cong;
private javax.swing.JButton giai;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPcuoi;
private javax.swing.JPanel jPgiua;
private javax.swing.JLabel ketqua;
private javax.swing.JRadioButton nhan;
private javax.swing.JLabel nhapb;
private javax.swing.JLabel nhâp;
private javax.swing.JLabel pheptoan;
private javax.swing.JButton so6;
private javax.swing.JButton so7;
private javax.swing.JButton tacvu;
private javax.swing.JPanel thaotac;
private javax.swing.JButton thoat;
private javax.swing.JButton tieude;
private javax.swing.JRadioButton tru;
private javax.swing.JButton xoa;
private javax.swing.JButton xuatkqua;
// End of variables declaration//GEN-END:variables
}
|
package sukerPkg;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import org.jfree.chart.JFreeChart;
import org.jfree.experimental.chart.swt.ChartComposite;
public class AndroSuker_TabItem_Profiling implements AndroSuker_Definition {
private final static int MAX_LISTUP_SIZE = 8;
private final static int MAX_CORE_COUNT = 4;
private static boolean l_createFirstData = false;
private static FileHandler resultFile = new FileHandler();
private static AndroSuker_Execute mExe;
private static Timer timerProfile = null;
private static Timer timerProfile2 = null;
private static Timer timerProfile3 = null;
private static Timer timerProfile4 = null;
private List<String> readList;
private List<String> writeList;
private String mHelpTip = null;
private Combo comboCoreCount;
private static int coreCountByUser;
private static Composite Profiling_composite;
private static Text edit_processName1;
private static Text edit_processName2;
private static Text edit_processName3;
private static StyledText mIopCmdInfoText;
private static StyledText mCpuUsageText;
private static StyledText mCpuCoreClockText;
private static StyledText mCpuThermalText;
// private String info_highlight_keyword;
private static Button btnRadioGB;
private static Button btnRadioICS;
private static Button btnRadioJB;
private static Button btnRadioKK;
private static Button adbShell_ProcMonitoring; //프로세스 모니터링(adb shell top -m 20 -n 20 -s cpu [-t 쓰레드])
private static Button adbShell_ProfileReset;
private static AndroSuker_Graph graph;
private Label[] labelCore = new Label[MAX_CORE_COUNT];
private static List<Double> mNoticeCpu;
private static List<Double> analysisCPUList;
private static List<Double> analysisCoreUsage;
private static List<Double> analysisCoreClock;
//private static List<String> analysisPIDList = new ArrayList<String>();
//private static List<String> analysisNameList = new ArrayList<String>();
private final int ADBPROFILING_RUN = 400;
private final int ADBPROFILING_RESET = 401;
private final int ADBPROFILING_RADIO_BTN_GB = 402;
private final int ADBPROFILING_RADIO_BTN_ICS = 403;
private final int ADBPROFILING_RADIO_BTN_JB = 404;
private final int ADBPROFILING_RADIO_BTN_KK = 405;
private final int[] ADB_TOP_GB_PROCNAME = {1,8};
private final int[] ADB_TOP_ICS_PROCNAME = {1,2,9};
private final int[] ADB_TOP_JB_PROCNAME = {1,2,8};
private final int[] ADB_TOP_KK_PROCNAME = {1,2,8};
//private final int[] ADB_TOP_LL_PROCNAME = {1,2,8};
private final static int ADB_TOP_GB = 300;
private final static int ADB_TOP_ICS = 301;
private final static int ADB_TOP_JB = 302;
private final static int ADB_TOP_KK = 303;
//private final static int ADB_TOP_LL = 304;
private static int[] CurrentTargetOS;
private static int CurrentTargetOSFlag;
private final static int CPU_USAGE_LOCATION = 1;
private final static int CPU_USAGE_LOCATION_FOR_ONLY_GB = 0;
private static String mCurrentHandlingFilePath;
private static String mCurrentCoreUsageFilePath;
private static String mCurrentClockFilePath;
private static String mCurrentThermalFilePath;
private final int PROFILING_PERIOD = 1000; //1.0 sec
final Timer timer = new Timer();
static List<String> swapStr = new ArrayList<String>();
private static CpuStat cpuStat;
public AndroSuker_TabItem_Profiling(TabFolder tabFolder, AndroSuker_Execute mExecute) {
initHelpTipSet();
createPage(tabFolder);
initPage();
mExe = mExecute;
mCurrentHandlingFilePath = AndroSuker_INIFile.RESULT_FILE_PATH_PROF;
mCurrentCoreUsageFilePath = AndroSuker_INIFile.RESULT_FILE_PATH_PROCSTAT;
mCurrentClockFilePath = AndroSuker_INIFile.RESULT_FILE_PATH_PROCSTAT2;
mCurrentThermalFilePath = AndroSuker_INIFile.RESULT_FILE_PATH_PROCSTAT3;
mNoticeCpu = new ArrayList<Double>();
mNoticeCpu.add(0, 0.0);
mNoticeCpu.add(1, 0.0);
mNoticeCpu.add(2, 0.0);
analysisCPUList = new ArrayList<Double>();
for (int i = 0; i < MAX_LISTUP_SIZE; i++) {
analysisCPUList.add(i, 0.0);
}
analysisCoreUsage = new ArrayList<Double>();
for (int i = 0; i < MAX_CORE_COUNT; i++) {
analysisCoreUsage.add(i, 0.0);
}
analysisCoreClock = new ArrayList<Double>();
for (int i = 0; i < MAX_CORE_COUNT; i++) {
analysisCoreClock.add(i, 0.0);
}
cpuStat = new CpuStat(MAX_CORE_COUNT);
}
public String getCurrentClsName() {
return this.getClass().getName();
}
private static void initProfiling() {
drawSetDataGraph();
startProfiling();
}
private void reCreateProfilingChart() {
stopProfiling();
if (graph != null)
graph.drawDestroy();
l_createFirstData = false;
//drawSetDataGraph();
}
private static void startProfiling() {
arrayListsReset();
graph.drawStart(AndroSuker_MainCls.getShellInstance(), graph, coreCountByUser);
}
private static void stopProfiling() {
arrayListsReset();
if (graph != null)
graph.drawStop();
}
public void __onFinally() {
l_createFirstData = false;
writeList = AndroSuker_Main_Layout.getWriteFileList();
if (edit_processName1.getText().length() <= 1)
edit_processName1.setText("none");
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_MONITORING_NOTICE1", edit_processName1.getText(), writeList);
if (edit_processName2.getText().length() <= 1)
edit_processName2.setText("none");
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_MONITORING_NOTICE2", edit_processName2.getText(), writeList);
if (edit_processName3.getText().length() <= 1)
edit_processName3.setText("none");
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_MONITORING_NOTICE3", edit_processName3.getText(), writeList);
if (CurrentTargetOSFlag == ADB_TOP_GB)
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_OS_TYPE", "GB", writeList);
else if (CurrentTargetOSFlag == ADB_TOP_ICS)
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_OS_TYPE", "ICS", writeList);
else if (CurrentTargetOSFlag == ADB_TOP_JB)
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_OS_TYPE", "JB", writeList);
else
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_OS_TYPE", "KK/LL", writeList);
AndroSuker_INIFile.writeIniFile("ADB_PROFILE_CORE_COUNT", String.valueOf(coreCountByUser), writeList);
if (timerProfile != null) {
timerProfile.cancel();
timerProfile.purge();
timerProfile = null;
}
if (timerProfile2 != null) {
timerProfile2.cancel();
timerProfile2.purge();
timerProfile2 = null;
}
if (timerProfile3 != null) {
timerProfile3.cancel();
timerProfile3.purge();
timerProfile3 = null;
}
if (timerProfile4 != null) {
timerProfile4.cancel();
timerProfile4.purge();
timerProfile4 = null;
}
stopProfiling();
if (graph != null)
graph.drawDestroy();
mExe.killProcess();
}
private void initPage() {
String resultStr = "none";
readList = AndroSuker_Main_Layout.getReadFileList();
btnRadioGB.setSelection(false);
btnRadioICS.setSelection(false);
btnRadioJB.setSelection(false);
btnRadioKK.setSelection(false);
if (readList != null){
resultStr = AndroSuker_INIFile.readIniFile(readList, "ADB_PROFILE_MONITORING_NOTICE1");
edit_processName1.setText(resultStr);
resultStr = AndroSuker_INIFile.readIniFile(readList, "ADB_PROFILE_MONITORING_NOTICE2");
edit_processName2.setText(resultStr);
resultStr = AndroSuker_INIFile.readIniFile(readList, "ADB_PROFILE_MONITORING_NOTICE3");
edit_processName3.setText(resultStr);
resultStr = AndroSuker_INIFile.readIniFile(readList, "ADB_PROFILE_OS_TYPE");
if (resultStr.equals("GB")) {
btnRadioGB.setSelection(true);
CurrentTargetOS = ADB_TOP_GB_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_GB;
}
else if (resultStr.equals("ICS")) {
btnRadioICS.setSelection(true);
CurrentTargetOS = ADB_TOP_ICS_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_ICS;
}
else if (resultStr.equals("JB")) {
btnRadioJB.setSelection(true);
CurrentTargetOS = ADB_TOP_JB_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_JB;
}
else {
btnRadioKK.setSelection(true);
CurrentTargetOS = ADB_TOP_KK_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_KK;
}
resultStr = AndroSuker_INIFile.readIniFile(readList, "ADB_PROFILE_CORE_COUNT");
if (resultStr.length() < 1)
resultStr = "1";
setCoreCountIndex(resultStr);
}
}
public static Composite getInstance() {
return Profiling_composite;
}
private void createPage(TabFolder tabFolder) {
//--------------------------------######### Main Frame ##########--------------------------------
Profiling_composite = new Composite(tabFolder, SWT.FILL);
GridLayout gl = new GridLayout(7, false);
Profiling_composite.setLayout(gl);
new Label(Profiling_composite, SWT.NONE);
new Label(Profiling_composite, SWT.NONE);
new Label(Profiling_composite, SWT.NONE);
//------------------------------------------------------------------------------------
Label label_processName1 = new Label(Profiling_composite, SWT.BORDER | SWT.SHADOW_NONE | SWT.CENTER);
label_processName1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
label_processName1.setText("notice process name 1");
label_processName1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
label_processName1.setBackground(SWTResourceManager.getColor(SWT.COLOR_RED));
//------------------------------------------------------------------------------------
Label label_processName2 = new Label(Profiling_composite, SWT.BORDER | SWT.SHADOW_NONE | SWT.CENTER);
label_processName2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
label_processName2.setText("notice process name 2");
label_processName2.setBackground(SWTResourceManager.getColor(SWT.COLOR_GREEN));
//------------------------------------------------------------------------------------
Label label_processName3 = new Label(Profiling_composite, SWT.BORDER | SWT.SHADOW_NONE | SWT.CENTER);
label_processName3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
label_processName3.setText("notice process name 3");
label_processName3.setBackground(SWTResourceManager.getColor(SWT.COLOR_YELLOW));
//------------------------------------------------------------------------------------
adbShell_ProcMonitoring = new Button(Profiling_composite, SWT.NONE);
GridData gd_btnNewButton_1 = new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1);
gd_btnNewButton_1.widthHint = 410;
adbShell_ProcMonitoring.setLayoutData(gd_btnNewButton_1);
adbShell_ProcMonitoring.setText("System Monitoring Start...");
adbShell_ProcMonitoring.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ADBPROFILING_RUN);
}
public void widgetDefaultSelected(SelectionEvent event) {
_actionPerformed(ADBPROFILING_RUN);
}
});
//------------------------------------------------------------------------------------
adbShell_ProfileReset = new Button(Profiling_composite, SWT.NONE);
adbShell_ProfileReset.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
adbShell_ProfileReset.setText("Plot Reset");
adbShell_ProfileReset.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
_actionPerformed(ADBPROFILING_RESET);
}
public void widgetDefaultSelected(SelectionEvent event) {
_actionPerformed(ADBPROFILING_RESET);
}
});
//------------------------------------------------------------------------------------
edit_processName1 = new Text(Profiling_composite, SWT.BORDER);
edit_processName1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
//------------------------------------------------------------------------------------
edit_processName2 = new Text(Profiling_composite, SWT.BORDER);
edit_processName2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
//------------------------------------------------------------------------------------
edit_processName3 = new Text(Profiling_composite, SWT.BORDER);
edit_processName3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
//------------------------------------------------------------------------------------
Group grpAndroidOs = new Group(Profiling_composite, SWT.NO_RADIO_GROUP);
grpAndroidOs.setText("Android OS");
GridData gd_grpAndroidOs = new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1);
gd_grpAndroidOs.widthHint = 410;
grpAndroidOs.setLayoutData(gd_grpAndroidOs);
btnRadioGB = new Button(grpAndroidOs, SWT.RADIO);
btnRadioGB.setBounds(21, 20, 48, 16);
btnRadioGB.setText("GB");
btnRadioGB.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
_actionPerformed(ADBPROFILING_RADIO_BTN_GB);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
btnRadioICS = new Button(grpAndroidOs, SWT.RADIO);
btnRadioICS.setBounds(91, 20, 48, 16);
btnRadioICS.setText("ICS");
btnRadioICS.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
_actionPerformed(ADBPROFILING_RADIO_BTN_ICS);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
btnRadioJB = new Button(grpAndroidOs, SWT.RADIO);
btnRadioJB.setBounds(164, 20, 48, 16);
btnRadioJB.setText("JB");
btnRadioJB.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
_actionPerformed(ADBPROFILING_RADIO_BTN_JB);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
btnRadioKK = new Button(grpAndroidOs, SWT.RADIO);
btnRadioKK.setBounds(233, 20, 86, 16);
btnRadioKK.setText("KK/LL");
btnRadioKK.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
_actionPerformed(ADBPROFILING_RADIO_BTN_KK);
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
//new Label(Profiling_composite, SWT.NONE);
//------------------------------------------------------------------------------------
graph = new AndroSuker_Graph(300000, null, MAX_CORE_COUNT);
JFreeChart chart = AndroSuker_Graph.getChartPanel();
ChartComposite chartcomp = new ChartComposite(Profiling_composite, SWT.NONE, chart, true);
GridData gd_composite = new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 3);
gd_composite.widthHint = 784;
gd_composite.heightHint = 500;
chartcomp.setLayoutData(gd_composite);
//------------------------------------------------------------------------------------
mIopCmdInfoText = new StyledText(Profiling_composite, SWT.BORDER);
GridData gd_styledText = new GridData(SWT.FILL, SWT.TOP, true, false, 2, 1);
gd_styledText.widthHint = 410;
gd_styledText.heightHint = 326;
mIopCmdInfoText.setLayoutData(gd_styledText);
/*mPage5Text.addLineStyleListener(new LineStyleListener() {
public void lineGetStyle(LineStyleEvent event) {
if(info_highlight_keyword == null || info_highlight_keyword.length() == 0) {
event.styles = new StyleRange[0];
return;
}
String line = event.lineText;
int cursor = -1;
LinkedList<StyleRange> list = new LinkedList<StyleRange>();
while( (cursor = line.indexOf(info_highlight_keyword, cursor+1)) >= 0) {
list.add(getHighlightStyle(event.lineOffset+cursor, info_highlight_keyword.length()));
}
event.styles = (StyleRange[]) list.toArray(new StyleRange[list.size()]);
}
});*/
new Label(Profiling_composite, SWT.NONE);
//------------------------------------------------------------------------------------
mCpuUsageText = new StyledText(Profiling_composite, SWT.BORDER);
GridData styledtext2 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
styledtext2.widthHint = 200;
mCpuUsageText.setLayoutData(styledtext2);
mCpuCoreClockText = new StyledText(Profiling_composite, SWT.BORDER);
GridData styledtext3 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
styledtext3.widthHint = 200;
mCpuCoreClockText.setLayoutData(styledtext3);
new Label(Profiling_composite, SWT.NONE);
mCpuThermalText = new StyledText(Profiling_composite, SWT.BORDER);
GridData styledtext4 = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 3);
styledtext4.widthHint = 400;
mCpuThermalText.setLayoutData(styledtext4);
new Label(Profiling_composite, SWT.NONE);
new Label(Profiling_composite, SWT.NONE);
//------------------------------------------------------------------------------------
labelCore[0] = new Label(Profiling_composite, SWT.SHADOW_NONE | SWT.CENTER);
labelCore[0].setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
labelCore[0].setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelCore[0].setBackground(SWTResourceManager.getColor(PANEL_COLOR_CORE_USAGE[0]));
labelCore[0].setText("core 0");
labelCore[1] = new Label(Profiling_composite, SWT.SHADOW_NONE | SWT.CENTER);
labelCore[1].setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
labelCore[1].setBackground(SWTResourceManager.getColor(PANEL_COLOR_CORE_USAGE[1]));
labelCore[1].setText("core 1");
Label lblCoreCount = new Label(Profiling_composite, SWT.NONE);
lblCoreCount.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
lblCoreCount.setText("Core Count");
new Label(Profiling_composite, SWT.NONE);
new Label(Profiling_composite, SWT.NONE);
new Label(Profiling_composite, SWT.NONE);
labelCore[2] = new Label(Profiling_composite, SWT.SHADOW_NONE | SWT.CENTER);
labelCore[2].setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
labelCore[2].setBackground(SWTResourceManager.getColor(PANEL_COLOR_CORE_USAGE[2]));
labelCore[2].setText("core 2");
labelCore[3] = new Label(Profiling_composite, SWT.SHADOW_NONE | SWT.CENTER);
labelCore[3].setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
labelCore[3].setBackground(SWTResourceManager.getColor(PANEL_COLOR_CORE_USAGE[3]));
labelCore[3].setText("core 3");
comboCoreCount = new Combo(Profiling_composite, SWT.NONE);
comboCoreCount.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
comboCoreCount.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
coreCountByUser = comboCoreCount.getSelectionIndex() + 1;
for (int i = 0; i < coreCountByUser; i++) {
labelCore[i].setVisible(true);
}
for (int i = coreCountByUser; i < MAX_CORE_COUNT; i++) {
labelCore[i].setVisible(false);
}
}
});
comboCoreCount.add("1");
comboCoreCount.add("2");
comboCoreCount.add("3");
comboCoreCount.add("4");
//------------------------------------------------------------------------------------
Label label_help = new Label(Profiling_composite, SWT.NONE);
label_help.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 6, 1));
label_help.setText(mHelpTip);
}
private static void arrayListsReset() {
for (int i = 0; i < MAX_LISTUP_SIZE; i++) {
analysisCPUList.set(i, 0.0);
}
for (int i = 0; i < MAX_CORE_COUNT; i++) {
analysisCoreUsage.set(i, 0.0);
analysisCoreClock.set(i, 0.0);
}
}
public void _actionPerformed(int action) {
if (ADBPROFILING_RUN == action) {
//adb shell top : 프로세스 모니터링(adb shell top -m 20 -n 20 -s cpu [-t 쓰레드])
if (adbShell_ProcMonitoring.getText().equals("System Monitoring Start...")) {
actionStart();
} else {
actionStop();
}
}
else if (ADBPROFILING_RESET == action) {
if (adbShell_ProfileReset.isEnabled() == true) {
graph.clearXYPlots();
reCreateProfilingChart();
adbShell_ProfileReset.setEnabled(false);
edit_processName1.setEditable(true);
edit_processName2.setEditable(true);
edit_processName3.setEditable(true);
mNoticeCpu.set(0, 0.0);
mNoticeCpu.set(1, 0.0);
mNoticeCpu.set(2, 0.0);
arrayListsReset();
}
}
else if (ADBPROFILING_RADIO_BTN_GB == action) {
CurrentTargetOS = ADB_TOP_GB_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_GB;
btnRadioGB.setSelection(true);
btnRadioICS.setSelection(false);
btnRadioJB.setSelection(false);
btnRadioKK.setSelection(false);
}
else if (ADBPROFILING_RADIO_BTN_ICS == action) {
CurrentTargetOS = ADB_TOP_ICS_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_ICS;
btnRadioGB.setSelection(false);
btnRadioICS.setSelection(true);
btnRadioJB.setSelection(false);
btnRadioKK.setSelection(false);
}
else if (ADBPROFILING_RADIO_BTN_JB == action) {
CurrentTargetOS = ADB_TOP_JB_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_JB;
btnRadioGB.setSelection(false);
btnRadioICS.setSelection(false);
btnRadioJB.setSelection(true);
btnRadioKK.setSelection(false);
}
else if (ADBPROFILING_RADIO_BTN_KK == action) {
CurrentTargetOS = ADB_TOP_KK_PROCNAME;
CurrentTargetOSFlag = ADB_TOP_KK;
btnRadioGB.setSelection(false);
btnRadioICS.setSelection(false);
btnRadioJB.setSelection(false);
btnRadioKK.setSelection(true);
}
}
public void actionStart() {
adbShell_ProcMonitoring.setText("System Monitoring Stop...");
//-----------------------------------------------------------------------------------------------
//CPU PID usage
//-----------------------------------------------------------------------------------------------
String text = "perl~~script/adbShellCmd.pl" + "~~" + String.valueOf(MAX_LISTUP_SIZE) + "~~"+ mCurrentHandlingFilePath;
String[] cmdList = text.split("~~");
/*String text = "cmd.exe~~/C~~adb~~shell~~top~~-m~~" + String.valueOf(MAX_LISTUP_SIZE) + "~~-n~~1~~-d~~1~~-s~~cpu~~>~~" + mCurrentHandlingFilePath;
String[] cmdList = text.split("~~");*/
if (cmdList != null) {
if (timerProfile == null) {
timerProfile = new Timer();
}
timerProfile.schedule(new DelayAnalysis(cmdList, mExe, getCurrentClsName(), null), 500, PROFILING_PERIOD);
}
// if (AndroSuker_Debug.DEBUG_MODE_ON)
// AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Debugging", "Debugging Step 1", SWT.OK);
//-----------------------------------------------------------------------------------------------
//CPU core usage
//-----------------------------------------------------------------------------------------------
String cmd = "perl~~script/adbShellCmdSimple.pl" + "~~" + "cat /proc/stat" + "~~" + mCurrentCoreUsageFilePath;
String[] cmdList2 = cmd.split("~~");
/*String cmd = "cmd.exe~~/C~~adb~~shell~~cat~~/proc/stat~~>~~" + mCurrentCoreUsageFilePath;
String[] cmdList2 = cmd.split("~~");*/
if (cmdList2 != null) {
if (timerProfile2 == null) {
timerProfile2 = new Timer();
}
timerProfile2.schedule(new DelayAnalysis(cmdList2, mExe, getCurrentClsName()+"2", null), 500, PROFILING_PERIOD);
}
// if (AndroSuker_Debug.DEBUG_MODE_ON)
// AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Debugging", "Debugging Step 2", SWT.OK);
//-----------------------------------------------------------------------------------------------
//CPU clock
//-----------------------------------------------------------------------------------------------
String cmd2 = "perl~~script/adbCpuFreqCheck.pl~~" + mCurrentClockFilePath;
String[] cmdList3 = cmd2.split("~~");
if (cmdList3 != null) {
if (timerProfile3 == null) {
timerProfile3 = new Timer();
}
timerProfile3.schedule(new DelayAnalysis(cmdList3, mExe, getCurrentClsName()+"3", null), 500, PROFILING_PERIOD);
}
// if (AndroSuker_Debug.DEBUG_MODE_ON)
// AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Debugging", "Debugging Step 3", SWT.OK);
//-----------------------------------------------------------------------------------------------
//CPU clock
//-----------------------------------------------------------------------------------------------
String cmd_thermal = "perl~~script/adbThermalCheck.pl~~" + mCurrentThermalFilePath;
String[] cmdList_thermal = cmd_thermal.split("~~");
if (cmdList_thermal != null) {
if (timerProfile4 == null) {
timerProfile4 = new Timer();
}
timerProfile4.schedule(new DelayAnalysis(cmdList_thermal, mExe, getCurrentClsName()+"3", null), 500, PROFILING_PERIOD);
}
// if (AndroSuker_Debug.DEBUG_MODE_ON)
// AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Debugging", "Debugging Step 3", SWT.OK);
//-----------------------------------------------------------------------------------------------
if (l_createFirstData) {
startProfiling();
}
adbShell_ProfileReset.setEnabled(false);
edit_processName1.setEditable(false);
edit_processName2.setEditable(false);
edit_processName3.setEditable(false);
btnRadioGB.setEnabled(false);
btnRadioICS.setEnabled(false);
btnRadioJB.setEnabled(false);
btnRadioKK.setEnabled(false);
comboCoreCount.setEnabled(false);
//if (AndroSuker_Debug.DEBUG_MODE_ON)
//AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Debugging", "Debugging Step3", SWT.OK);
}
public void actionStop() {
timerProfile.cancel();
timerProfile.purge();
timerProfile = null;
timerProfile2.cancel();
timerProfile2.purge();
timerProfile2 = null;
timerProfile3.cancel();
timerProfile3.purge();
timerProfile3 = null;
timerProfile4.cancel();
timerProfile4.purge();
timerProfile4 = null;
if (mExe.process != null) {
mExe.process.destroy();
}
adbShell_ProcMonitoring.setText("System Monitoring Start...");
stopProfiling();
adbShell_ProfileReset.setEnabled(true);
edit_processName1.setEditable(true);
edit_processName2.setEditable(true);
edit_processName3.setEditable(true);
btnRadioGB.setEnabled(true);
btnRadioICS.setEnabled(true);
btnRadioJB.setEnabled(true);
btnRadioKK.setEnabled(true);
comboCoreCount.setEnabled(true);
}
public static void resultAnalysis(boolean update) {
final boolean doUpdate = update;
if (AndroSuker_MainCls.getShellInstance().isDisposed())
return ;
AndroSuker_MainCls.getShellInstance().getDisplay().syncExec(new Runnable() {
public void run(){
if (!doUpdate) {
List<String> resultList = null;
StringBuilder resultText;
String[] analysisText = null;
String tempText = "";
try {
resultList = resultFile.readFile(mCurrentHandlingFilePath);
} catch (Exception e) {
e.printStackTrace();
}
int resultListSize = 0;
resultListSize = resultList.size();
if (resultList != null){
resultText = new StringBuilder(resultListSize * TEXT_LINE_WIDTH);
for (int i = 0; i < resultListSize; i++) {
resultText.append(resultList.get(i));
if (resultList.get(i).length() > 0) {
resultText.append("\n\n");
}
}
if (mIopCmdInfoText != null && !mIopCmdInfoText.isDisposed() && resultText.length() > 1) {
if (AndroSuker_Debug.DEBUG_MODE_ON) {
System.out.print("resultAnalysis print text \n");
}
mIopCmdInfoText.setText(resultText.toString());
}
//graph
int j = 0;
int frontSplitLength;
int behindSplitLength = 3;
int debuggingCnt = 0;
boolean bCanListUpStart = false;
boolean bProc1Exist = false;
boolean bProc2Exist = false;
boolean bProc3Exist = false;
if (CurrentTargetOSFlag == ADB_TOP_GB)
frontSplitLength = CurrentTargetOS[CPU_USAGE_LOCATION_FOR_ONLY_GB]+2;
else
frontSplitLength = CurrentTargetOS[CPU_USAGE_LOCATION]+2;
resultListSize = resultList.size();
for (int i = 5; i < resultListSize; i++) {
tempText = resultList.get(i);
if (resultList.get(i).length() > 0) {
int t = 0;
analysisText = tempText.split("[ ]+");
for (int k = 0; k < analysisText.length; k++) {
if (!(analysisText[k].length() <= 0)) {
swapStr.add(t, analysisText[k].toString());
t++;
if (t >= frontSplitLength)
break;
if (AndroSuker_Debug.DEBUG_MODE_ON) {
debuggingCnt++;
}
}
}
for (int k = analysisText.length - behindSplitLength; k < analysisText.length; k++) {
if (!(analysisText[k].length() <= 0)) {
swapStr.add(t, analysisText[k].toString());
t++;
if (AndroSuker_Debug.DEBUG_MODE_ON) {
debuggingCnt++;
}
}
}
}
if (AndroSuker_Debug.DEBUG_MODE_ON) {
System.out.println("debuggingCnt = "+debuggingCnt+"\n");
}
if (swapStr != null && swapStr.size() > 0) {
if (swapStr.get(0).equals("PID")) {
bCanListUpStart = true;
}
else if (j < MAX_LISTUP_SIZE && bCanListUpStart == true) {
String temp;
if (CurrentTargetOSFlag == ADB_TOP_GB)
temp = swapStr.get(CurrentTargetOS[CPU_USAGE_LOCATION_FOR_ONLY_GB]).toString().trim();
else
temp = swapStr.get(CurrentTargetOS[CPU_USAGE_LOCATION]).toString().trim();
String tempResult = temp.replace("%", "");
Double uTempResult = Double.valueOf(tempResult);
//CPU pid Usage
int nameLocation = swapStr.size()-1;
if (edit_processName1.getText().trim().equals(swapStr.get(nameLocation).toString().trim())) {
mNoticeCpu.set(0, uTempResult);
bProc1Exist = true;
if (AndroSuker_Debug.DEBUG_MODE_ON)
System.out.print("process 1 : " + edit_processName1.getText() + "\n");
} else if (edit_processName2.getText().trim().equals(swapStr.get(nameLocation).toString().trim())) {
mNoticeCpu.set(1, uTempResult);
bProc2Exist = true;
if (AndroSuker_Debug.DEBUG_MODE_ON)
System.out.print("process 2 : " + edit_processName2.getText() + "\n");
} else if (edit_processName3.getText().trim().equals(swapStr.get(nameLocation).toString().trim())) {
mNoticeCpu.set(2, uTempResult);
bProc3Exist = true;
if (AndroSuker_Debug.DEBUG_MODE_ON)
System.out.print("process 3 : " + edit_processName3.getText() + "\n");
} else {
if (AndroSuker_Debug.DEBUG_MODE_ON)
System.out.print("else \n");
//analysisPIDList.add(j, swapStr.get(0).toString().trim()); //PID
analysisCPUList.set(j, uTempResult); //CPU
//analysisNameList.add(j, swapStr.get(nameLocation).toString().trim()); //pkg Name
j++;
}
}
}
swapStr.clear();
}
if (bCanListUpStart == true) {
if (bProc1Exist == false)
mNoticeCpu.set(0, 0.0);
if (bProc2Exist == false)
mNoticeCpu.set(1, 0.0);
if (bProc3Exist == false)
mNoticeCpu.set(2, 0.0);
}
}
}
else { //doUpdate == true
//CPU Usage
if (cpuStat == null) {
mCpuUsageText.setText("busy wait...");
}
else {
//CPU core Usage
mCpuUsageText.setText(cpuStat.setCoreUsageInfo(mCurrentCoreUsageFilePath));
for (int i = 0; i < cpuStat.getCoreUsageInfo().size(); i++) {
analysisCoreUsage.set(i, cpuStat.getCoreUsageInfo().get(i));
}
//CPU clk
mCpuCoreClockText.setText(" cpuinfo_cur_freq \n");
mCpuCoreClockText.append( "------------------------");
mCpuCoreClockText.append(cpuStat.setCoreClockInfo(mCurrentClockFilePath));
for (int i = 0; i < cpuStat.getCoreClockInfo().size(); i++) {
if (cpuStat.getCoreClockInfo().size() > 4) {
System.out.print("result debug : " + i + " " + cpuStat.getCoreClockInfo().size() + "\n");
System.out.print("result debug : " + cpuStat.getCoreClockInfo() + "\n");
}
analysisCoreClock.set(i, cpuStat.getCoreClockInfo().get(i));
}
if (analysisCPUList.size()>0 && analysisCoreUsage.size()>0 && analysisCoreClock.size()>0) {
drawSetDataGraph();
}
//Thermal Check
mCpuThermalText.setText(cpuStat.setThermalInfo(mCurrentThermalFilePath));
}
}
}}
);
}
private static void drawSetDataGraph() {
if (!l_createFirstData) {
l_createFirstData = true;
initProfiling();
return ;
}
AndroSuker_Graph.setFeedData(analysisCPUList, mNoticeCpu, analysisCoreUsage, analysisCoreClock);
}
private void initHelpTipSet() {
mHelpTip = "** 우측 상단에 tracing하고 싶은 process name을 입력하면 해당 색상으로 graph가 표시됨. " +
"** 다른 색상으로 표시되는 graph는 현재 cpu 점유율이 가장 높은 상위 3개 process 값.";
}
private void setCoreCountIndex(String index) {
comboCoreCount.select(Integer.parseInt(index)-1);
coreCountByUser = comboCoreCount.getSelectionIndex()+1;
for (int i = 0; i < coreCountByUser; i++) {
labelCore[i].setVisible(true);
}
for (int i = coreCountByUser; i < MAX_CORE_COUNT; i++) {
labelCore[i].setVisible(false);
}
}
}
class CpuStat {
private RandomAccessFile statFile;
private RandomAccessFile statFile2;
private RandomAccessFile statFile3;
private CpuInfo mCpuInfoTotal;
private ArrayList<CpuInfo> mCpuInfoList;
private ArrayList<String> mCpuClockOnlineList = new ArrayList<String>();
private ArrayList<Double> mCpuClockFreqList = new ArrayList<Double>();
private ArrayList<String> mThermalList = new ArrayList<String>();
private List<Double> usage = new ArrayList<Double>();
private List<String> clock = new ArrayList<String>();
private int updateCnt = 0;
private int maxCoreCount;
private String onlineListTemp = "0.0";
private StringBuffer buf = new StringBuffer();
public CpuStat(int count) {
int i;
maxCoreCount = count;
for (i = 0; i < maxCoreCount; i++) {
usage.add(i, 0.0);
clock.add(i, "");
}
}
public void update(String filename) {
try {
createFile(filename);
parseFile();
closeFile();
} catch (FileNotFoundException e) {
statFile = null;
} catch (IOException e) {
}
}
public void update2(String filename) {
try {
createFile2(filename);
parseFile2();
closeFile2();
} catch (FileNotFoundException e) {
statFile2 = null;
} catch (IOException e) {
}
}
public void update3(String filename) {
try {
createFile3(filename);
parseFile3();
closeFile3();
} catch (FileNotFoundException e) {
statFile3 = null;
} catch (IOException e) {
}
}
private void createFile(String filename) {
try {
statFile = new RandomAccessFile(filename, "r");
} catch (FileNotFoundException e) {
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Error1", "Tracing File not create or exist!!\nMaybe your device did not rooting", SWT.OK);
}
}
private void createFile2(String filename) {
try {
statFile2 = new RandomAccessFile(filename, "r");
} catch (FileNotFoundException e) {
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Error2", "Tracing File not create or exist!!\nMaybe your device did not rooting", SWT.OK);
}
}
private void createFile3(String filename) {
try {
statFile3 = new RandomAccessFile(filename, "r");
} catch (FileNotFoundException e) {
AsyncMsgBoxDraw.MessageBoxDraw(AndroSuker_MainCls.getShellInstance(), "Error3", "Tracing File not create or exist!!\nMaybe your device did not rooting", SWT.OK);
}
}
public void closeFile() throws IOException {
if (statFile != null)
statFile.close();
}
public void closeFile2() throws IOException {
if (statFile2 != null)
statFile2.close();
}
public void closeFile3() throws IOException {
if (statFile3 != null)
statFile3.close();
}
private void parseFile() {
if (statFile != null) {
try {
statFile.seek(0);
String cpuLine = "";
int cpuId = -1;
boolean ret = false;
do {
cpuLine = statFile.readLine();
ret = parseCpuLine(cpuId, cpuLine);
if (ret == true)
cpuId++;
} while (cpuLine != null);
} catch (IOException e) {
}
}
}
private void parseFile2() {
if (statFile2 != null) {
clock.clear();
try {
statFile2.seek(0);
String read_cpuinfo = "";
int i = 0;
do {
read_cpuinfo = statFile2.readLine();
if (read_cpuinfo == null)
return ;
if (read_cpuinfo.length() > 0) {
clock.add(i, read_cpuinfo);
i++;
}
} while (true);
} catch (IOException e) {
}
}
}
private void parseFile3() {
if (statFile3 != null) {
try {
statFile3.seek(0);
String read_thermalinfo = "";
do {
read_thermalinfo = statFile3.readLine();
if (read_thermalinfo == null)
return ;
if (read_thermalinfo.length() > 0) {
mThermalList.add(read_thermalinfo);
}
} while (true);
} catch (IOException e) {
}
}
}
private boolean parseCpuLine(int cpuId, String cpuLine) {
if (cpuLine != null && cpuLine.length() > 0) {
String[] parts = cpuLine.split("[ ]+");
String cpuLabel = "cpu";
if ( parts[0].indexOf(cpuLabel) != -1) {
createCpuInfo(cpuId, parts);
}
else
return false;
} else {
return false;
}
return true;
}
private void createCpuInfo(int cpuId, String[] parts) {
if (cpuId == -1) {
if (mCpuInfoTotal == null)
mCpuInfoTotal = new CpuInfo();
mCpuInfoTotal.update(parts);
} else {
updateCnt++;
if (mCpuInfoList == null)
mCpuInfoList = new ArrayList<CpuInfo>();
if (cpuId < mCpuInfoList.size())
mCpuInfoList.get(cpuId).update(parts);
else {
CpuInfo info = new CpuInfo();
info.update(parts);
mCpuInfoList.add(info);
}
}
}
public String setCoreUsageInfo(String filename) {
updateCnt = 0;
update(filename);
if (mCpuInfoList == null)
return "error";
if (mCpuInfoList.size() > updateCnt && updateCnt > 0) {
for (int i = mCpuInfoList.size()-updateCnt; i > 0; i--) {
mCpuInfoList.remove(i);
usage.remove(i);
}
}
buf.setLength(0);
buf.append("\n");
if (mCpuInfoTotal != null) {
buf.append(" Cpu Total : ");
buf.append(mCpuInfoTotal.getUsage());
buf.append("%\n");
}
if (mCpuInfoList != null) {
for (int i=0; i < mCpuInfoList.size(); i++) {
CpuInfo info = mCpuInfoList.get(i);
buf.append(" Cpu Core " + i + " : ");
buf.append(info.getUsage());
buf.append("%\n");
if (usage.size() < mCpuInfoList.size())
{
usage.clear();
for (int j = 0; j < maxCoreCount; j++) {
usage.add(j, 0.0);
}
}
usage.set(i, (double)info.getUsage());
}
}
return buf.toString();
}
public String setCoreClockInfo(String filename) {
String temp = "";
buf.setLength(0);
buf.append("\n");
updateCnt = 0;
update2(filename);
if (clock.size() < maxCoreCount*2) {
return "\nWarning : strange read device!";
}
mCpuClockFreqList.clear();
mCpuClockOnlineList.clear();
for (int i=0; i < maxCoreCount; i++) {
mCpuClockOnlineList.add(clock.get(i));
}
for (int i=maxCoreCount; i < maxCoreCount*2; i++) {
temp = clock.get(i);
if (temp.length() < 9) {
mCpuClockFreqList.add(Double.valueOf(clock.get(i)));
} else {
mCpuClockFreqList.add(0.0);
}
}
for (int i=0; i < maxCoreCount; i++) {
temp = String.valueOf(mCpuClockFreqList.get(i));
if (mCpuClockOnlineList.get(i).equals("1")) {
onlineListTemp = String.valueOf(mCpuClockFreqList.get(i));
if (onlineListTemp.equals("0.0")) {
buf.append(" Cpu " + i + " freq : off \n");
} else {
buf.append(" Cpu " + i + " freq : " + onlineListTemp + "\n");
}
} else {
mCpuClockFreqList.set(i, 0.0);
buf.append(" Cpu " + i + " freq : off \n");
}
}
return buf.toString();
}
public String setThermalInfo(String filename) {
buf.setLength(0);
buf.append("pa_therm Result ==> \n");
mThermalList.clear();
updateCnt = 0;
update3(filename);
for (int i=0; i < mThermalList.size(); i++) {
buf.append(" " + mThermalList.get(i) + "\n");
}
return buf.toString();
}
public List<Double> getCoreUsageInfo() {
return usage;
}
public List<Double> getCoreClockInfo() {
return mCpuClockFreqList;
}
public int getReadCoreCount() {
return mCpuInfoList.size();
}
public class CpuInfo {
private int mUsage;
private long mLastTotal;
private long mLastIdle;
public CpuInfo() {
mUsage = 0;
mLastTotal = 0;
mLastIdle = 0;
}
private int getUsage() {
return mUsage;
}
public void update(String[] parts) {
// the columns are:
//
// 0 "cpu": the string "cpu" that identifies the line
// 1 user: normal processes executing in user mode
// 2 nice: niced processes executing in user mode
// 3 system: processes executing in kernel mode
// 4 idle: twiddling thumbs
// 5 iowait: waiting for I/O to complete
// 6 irq: servicing interrupts
// 7 softirq: servicing softirqs
//
if (parts.length < 5)
return ;
long idle = Long.parseLong(parts[4], 10);
long total = 0;
boolean head = true;
for (String part : parts) {
if (head) {
head = false;
continue;
}
total += Long.parseLong(part, 10);
}
long diffIdle = idle - mLastIdle;
long diffTotal = total - mLastTotal;
mUsage = (int)((float)(diffTotal - diffIdle) / diffTotal * 100);
mLastTotal = total;
mLastIdle = idle;
//Log.i(TAG, "CPU total=" + total + "; idle=" + idle + "; usage=" + mUsage);
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Audio;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
/**
*
* @author Alberto Ortiz
*/
public class AdministradorSonidos {
private Player p;
private boolean reproduciendo;
public AdministradorSonidos() {
reproduciendo = false;
}
public void Reproducir(String archivo) {
try {
if (p != null) {
p.stop();
p.deallocate();
p = null;
reproduciendo = false;
}
InputStream input = getClass().getResourceAsStream(archivo);
Player p = Manager.createPlayer(input, "audio/sp-midi");
p.realize();
p.prefetch();
p.start();
reproduciendo = true;
} catch (MediaException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void parar() {
try {
p.stop();
} catch(MediaException ex) {
ex.printStackTrace();
}
p.deallocate();
p = null;
reproduciendo = false;
}
public boolean estaReproduciendo() {
return reproduciendo;
}
}
|
package com.tencent.mm.plugin.honey_pay.ui;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.wallet_core.ui.a;
class HoneyPayGiveCardUI$5 implements a {
final /* synthetic */ HoneyPayGiveCardUI kls;
HoneyPayGiveCardUI$5(HoneyPayGiveCardUI honeyPayGiveCardUI) {
this.kls = honeyPayGiveCardUI;
}
public final void fI(boolean z) {
if (z) {
HoneyPayGiveCardUI.a(this.kls, HoneyPayGiveCardUI.e(this.kls), HoneyPayGiveCardUI.f(this.kls));
return;
}
HoneyPayGiveCardUI.e(this.kls).scrollTo(0, 0);
HoneyPayGiveCardUI.b(this.kls).bqm();
if (bi.oW(HoneyPayGiveCardUI.b(this.kls).getText())) {
HoneyPayGiveCardUI.b(this.kls).setVisibility(8);
HoneyPayGiveCardUI.c(this.kls).setVisibility(0);
HoneyPayGiveCardUI.g(this.kls);
HoneyPayGiveCardUI.h(this.kls);
}
}
}
|
package com.supconit.kqfx.web.xtgl.entities;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import jodd.util.StringUtil;
import hc.base.domains.AuditedSimpleEntity;
import hc.base.domains.ImprovedTree;
import hc.base.domains.Tableable;
import hc.base.domains.XssFilterSupport;
import hc.orm.search.Conditional;
import hc.orm.search.SQLTerm;
import hc.orm.search.Term;
/**
* 机构信息
*
* @author shenxinfeng@supcon.com
*
*/
public class Jgxx extends AuditedSimpleEntity implements ImprovedTree<Jgxx>, Tableable, Conditional, XssFilterSupport {
/**
*
*/
private static final long serialVersionUID = -5395396941129313754L;
public static final long ROOT_PID = 0L;
public static final Long ROOT_ID = 1L;
public static final String TABLE_NAME = "T_XTGL_ZHGL_JGXX";
private String name;
private Boolean expanded=true;
private Boolean hasChildren;
private Long parentId;
private long modifier=1;
/** 机构名称 */
protected String jgmc;
/** 机构简称 */
protected String jgjc;
/** 组织机构代码 */
protected String zzjgdm;
/** 行政区划代码 */
protected String xzqhdm;
/** 上级主管部门 */
protected Long pid;
/** 负责人 */
protected String fzr;
/** 负责人联系电话 */
protected String fzrlxfs;
/** 传真 */
protected String cz;
/** 详细地址 */
protected String xxdz;
/** 邮编 */
protected String yb;
/** 经度 */
protected BigDecimal jd;
/** 纬度 */
protected BigDecimal wd;
/** 备注 */
protected String bz;
/** */
protected Long lft;
/** */
protected Long rgt;
/** 删除标记默认0,1表示删除 */
protected Integer deleted;
/** 机构等级 */
protected String jgdj;
/** 统计分析简称 */
protected String tjfxjc;
/** 机构拼音简称 */
protected String jgpyjc;
protected Jgxx parent;
protected List<Jgxx> children;
private String parentJgmc;
private String parentJgId;
private String xzqhmc;
public String getParentJgId() {
return parentJgId;
}
public void setParentJgId(String parentJgId) {
this.parentJgId = parentJgId;
}
public String getParentJgmc() {
return parentJgmc;
}
public void setParentJgmc(String parentJgmc) {
this.parentJgmc = parentJgmc;
}
public Jgxx(){
super();
}
public Jgxx(Long id){
setId(id);
}
public String getJgmc() {
return jgmc;
}
public void setJgmc(String jgmc) {
this.jgmc = jgmc;
}
public String getJgjc() {
return jgjc;
}
public void setJgjc(String jgjc) {
this.jgjc = jgjc;
}
public String getZzjgdm() {
return zzjgdm;
}
public void setZzjgdm(String zzjgdm) {
this.zzjgdm = zzjgdm;
}
public String getXzqhdm() {
return xzqhdm;
}
public void setXzqhdm(String xzqhdm) {
this.xzqhdm = xzqhdm;
}
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getFzr() {
return fzr;
}
public void setFzr(String fzr) {
this.fzr = fzr;
}
public String getFzrlxfs() {
return fzrlxfs;
}
public void setFzrlxfs(String fzrlxfs) {
this.fzrlxfs = fzrlxfs;
}
public String getCz() {
return cz;
}
public void setCz(String cz) {
this.cz = cz;
}
public String getXxdz() {
return xxdz;
}
public void setXxdz(String xxdz) {
this.xxdz = xxdz;
}
public String getYb() {
return yb;
}
public void setYb(String yb) {
this.yb = yb;
}
public BigDecimal getJd() {
return jd;
}
public void setJd(BigDecimal jd) {
this.jd = jd;
}
public BigDecimal getWd() {
return wd;
}
public void setWd(BigDecimal wd) {
this.wd = wd;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public Integer getDeleted() {
return deleted;
}
public void setDeleted(Integer deleted) {
this.deleted = deleted;
}
public void setLft(Long lft) {
this.lft = lft;
}
public void setRgt(Long rgt) {
this.rgt = rgt;
}
public void setParent(Jgxx parent) {
this.parent = parent;
}
public void setChildren(List<Jgxx> children) {
this.children = children;
}
@Override
public Jgxx getParent() {
return this.parent;
}
@SuppressWarnings("unchecked")
@Override
public List<Jgxx> getChildren() {
return this.children;
}
@Override
public void addChild(Jgxx child) {
if (null == children) children = new ArrayList<Jgxx>();
children.add(child);
}
@Override
public Term getTerm(String prefix) {
StringBuilder sql = new StringBuilder();
List<Object> params = new ArrayList<Object>();
if (null != this.getId()) {
buildSQLAnd(sql, prefix, "ID");
params.add(this.getId());
}
if (null != this.getPid() && this.getPid() > 0) {
buildSQLAnd(sql, prefix, "PID");
params.add(this.getPid());
}
if (StringUtil.isNotBlank(this.getJgmc())) {
buildSQLLike(sql, prefix, "JGMC");
params.add("%" + this.getJgmc() + "%");
}
if (StringUtil.isNotBlank(this.getZzjgdm())) {
buildSQLLike(sql, prefix, "ZZJGDM");
params.add("%" + this.getZzjgdm() + "%");
}
if (StringUtil.isNotBlank(this.getFzr())) {
buildSQLLike(sql, prefix, "FZR");
params.add("%" + this.getFzr() + "%");
}
if (StringUtil.isNotBlank(this.getJgdj())){
buildSQLAnd(sql, prefix, "JGDJ");
params.add(this.getJgdj());
}
//获取未删除的记录
buildSQLAnd(sql, prefix, "DELETED");
params.add(0);
if (sql.indexOf("AND ") == 0)
sql.delete(0, 3);
SQLTerm term = new SQLTerm(sql.toString());
term.setParams(params.toArray());
return term;
}
@Override
public String getTableName() {
return TABLE_NAME;
}
@Override
public Long getLft() {
return this.lft;
}
@Override
public Long getRgt() {
return this.rgt;
}
public String getJgdj() {
return jgdj;
}
public Boolean getExpanded() {
return expanded;
}
public void setExpanded(Boolean expanded) {
this.expanded = expanded;
}
public void setJgdj(String jgdj) {
this.jgdj = jgdj;
}
public String getTjfxjc() {
return tjfxjc;
}
public void setTjfxjc(String tjfxjc) {
this.tjfxjc = tjfxjc;
}
public String getJgpyjc() {
return jgpyjc;
}
public void setJgpyjc(String jgpyjc) {
this.jgpyjc = jgpyjc;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getHasChildren() {
return hasChildren;
}
public void setHasChildren(Boolean hasChildren) {
this.hasChildren = hasChildren;
}
public Long getModifier() {
return modifier;
}
public void setModifier(long modifier) {
this.modifier = modifier;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getXzqhmc() {
return xzqhmc;
}
public void setXzqhmc(String xzqhmc) {
this.xzqhmc = xzqhmc;
}
}
|
package com.product.productcat.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.product.productcat.entity.ProductCategory;
@Repository
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer>{
}
|
package DPI.wecontroller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import DPI.entity.Sport;
import DPI.service.SportService;
@RestController
public class SportController {
@Autowired
SportService sportService;
@PostMapping("/updateSportByOpenid")
public int updateByOpenid(HttpServletRequest request, @RequestBody Sport record) {
record.setOpenid(request.getSession().getAttribute("openId").toString());
return sportService.updateByOpenid(record);
}
@RequestMapping("/selectSportByOpenid")
public Sport selectByOpenid(HttpServletRequest request, String exerciseDate) {
return sportService.selectByOpenid(request.getSession().getAttribute("openId").toString(), exerciseDate);
}
@RequestMapping("/insertSport")
public int insertSport(HttpServletRequest request,@RequestBody Sport record) {
record.setOpenid(request.getSession().getAttribute("openId").toString());
return sportService.insertSport(record);
}
}
|
class Node
{
int data;
Node left, right;
public Node(int item){
data = item;
left = null;
right = null;
}
}
public class BinaryTree
{
Node root;
static boolean v1= false, v2= false;
Node findLCAUtil(Node node, int n1, int n2)
{
if(node == null)
{
return null;
}
if(node.data == n1)
{
v1=true;
return node;
}
if(node.data == n2)
{
v2=true;
return node;
}
Node left_lca = findLCAUtil(node.left, n1, n2);
Node right_lca = findLCAUtil(node.right, n1,n2);
if(left_lca != null && right_lca != null)
{
return node;
}
return(left_lca != null) ? left_lca : right_lca ;
}
Node findLCA(int n1, int n2)
{
v1= false;
v2 = false;
Node lca = findLCAUtil(root, n1, n2);
if(v1 && v2)
return lca;
return null;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
Node lca = tree.findLCA(4, 5);
if (lca != null)
System.out.println("LCA(4, 5) = " + lca.data);
else
System.out.println("Keys are not present");
lca = tree.findLCA(4, 10);
if (lca != null)
System.out.println("LCA(4, 10) = " + lca.data);
else
System.out.println("Keys are not present");
}
}
//Time Complexity: O(n)
|
package com.example.healthmanage.ui.activity.memberdetail;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import androidx.databinding.BindingAdapter;
import com.example.healthmanage.BR;
import com.example.healthmanage.R;
import com.example.healthmanage.base.BaseActivity;
import com.example.healthmanage.databinding.ActivityMemberDetailBinding;
import com.example.healthmanage.utils.LocationUtil;
import com.example.healthmanage.dialog.EditTextDialog;
import com.example.healthmanage.widget.DropdownBar;
import com.example.healthmanage.widget.TitleToolBar;
import com.jeremyliao.liveeventbus.LiveEventBus;
import java.util.ArrayList;
import java.util.List;
import static com.example.healthmanage.utils.Constants.HTAG;
public class MemberDetailActivity extends BaseActivity<ActivityMemberDetailBinding,
MemberDetailViewModel> implements TitleToolBar.OnTitleIconClickCallBack, View.OnClickListener {
private TitleToolBar titleToolBar = new TitleToolBar();
private Bundle bundle;
private boolean b;
private int memberId;
private String memberName;
private EditTextDialog editTextDialog;
DropdownBar dropdownBarTodayEnvironment;
@Override
protected void initData() {
bundle = this.getIntent().getExtras();
memberName = bundle.getString("MemberName");
memberId = bundle.getInt("MemberId");
b = bundle.getBoolean("FocusState");
titleToolBar.setTitle(memberName + "会员详情");
titleToolBar.setLeftIconVisible(true);
titleToolBar.setRightIconVisible(true);
titleToolBar.setRightIconSrc(R.drawable.ic_md_more_vert);
dataBinding.includeTitle.ivRight.setVisibility(View.INVISIBLE);
dataBinding.includeTitle.ivRight.setImageResource(R.drawable.ic_md_more_vert);
showFocus(b);
viewModel.setTitleToolBar(titleToolBar);
LocationUtil.getAddress(this);
LocationUtil.city.observe(this, String -> {
if (String != null) {
viewModel.location.setValue(LocationUtil.city.getValue().substring(0, 2));
viewModel.getWeather();
LocationUtil.stopLocation();
}
});
// viewModel.getHealthDataList(String.valueOf(memberId));
/**空气检测仪数据*/
viewModel.getAirList(String.valueOf(memberId));
/**护理仪数据*/
viewModel.getNursingData(memberId);
dropdownBarTodayEnvironment = new DropdownBar("今日环境", false,
viewModel.todayAirVisible.getValue(), false);
DropdownBar dropdownBarTodayHealth = new DropdownBar("今日健康", false, false, false);
DropdownBar dropdownBarBodyHealth = new DropdownBar("身体健康", viewModel.bodyHealthVisible.getValue(), false, false);
DropdownBar dropdownBarSpiritHealth = new DropdownBar("精神健康", false, false, false);
DropdownBar dropdownBarHealthDataAnalyse = new DropdownBar("健康数据分析", false, false, false);
DropdownBar dropdownBarInspectionQuantity = new DropdownBar("定期服务", false, false, false);
ArrayList<DropdownBar> dropdownBarArrayList = new ArrayList<>();
dropdownBarArrayList.add(dropdownBarTodayEnvironment);
dropdownBarArrayList.add(dropdownBarTodayHealth);
dropdownBarArrayList.add(dropdownBarBodyHealth);
dropdownBarArrayList.add(dropdownBarSpiritHealth);
dropdownBarArrayList.add(dropdownBarHealthDataAnalyse);
dropdownBarArrayList.add(dropdownBarInspectionQuantity);
viewModel.dropdownBarLists.setValue(dropdownBarArrayList);
}
@Override
public void initViewParameters() {
super.initViewParameters();
}
@Override
protected void registerUIChangeEventObserver() {
super.registerUIChangeEventObserver();
viewModel.currentFocusState.observe(this, aBoolean -> {
LiveEventBus.get("refresh").post("value");
b = aBoolean;
if (aBoolean) {
dataBinding.includeTitle.ivRight.setImageResource(R.drawable.fragment_main_my_member_focus_selected);
} else {
dataBinding.includeTitle.ivRight.setImageResource(R.drawable.fragment_main_my_member_focus_normal);
}
});
viewModel.todayAirVisible.observe(this, aBoolean -> {
if (aBoolean) {
dataBinding.includeTodayEnvironment.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeTodayEnvironmentNull.setVisibility(View.VISIBLE);
} else {
dataBinding.includeTodayEnvironment.tvExpand.setVisibility(View.GONE);
dataBinding.includeTodayEnvironmentNull.setVisibility(View.GONE);
}
});
viewModel.todayHealthVisible.observe(this, aBoolean -> {
if (aBoolean) {
dataBinding.includeTodayHealthNull.setVisibility(View.VISIBLE);
} else {
dataBinding.includeTodayHealthNull.setVisibility(View.GONE);
}
});
dataBinding.includeTodayHealth.tvExpand.setOnClickListener(v -> {
dataBinding.includeTodayHealth.tvExpand.setVisibility(View.GONE);
dataBinding.includeTodayHealth.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.includeTodayHealthData.getRoot().setVisibility(View.VISIBLE);
});
dataBinding.includeTodayHealth.tvCollapse.setOnClickListener(v -> {
dataBinding.includeTodayHealth.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeTodayHealth.tvCollapse.setVisibility(View.GONE);
dataBinding.includeTodayHealthData.getRoot().setVisibility(View.GONE);
});
dataBinding.includeTodayEnvironment.tvExpand.setOnClickListener(v -> {
dataBinding.includeTodayEnvironment.tvExpand.setVisibility(View.GONE);
dataBinding.includeTodayEnvironment.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.includeTodayEnvironmentDataDevice.getRoot().setVisibility(View.VISIBLE);
});
dataBinding.includeTodayEnvironment.tvCollapse.setOnClickListener(v -> {
dataBinding.includeTodayEnvironment.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeTodayEnvironment.tvCollapse.setVisibility(View.GONE);
dataBinding.includeTodayEnvironmentDataDevice.getRoot().setVisibility(View.GONE);
});
dataBinding.tvCreateTask.setOnClickListener(this::onClick);
}
@Override
public void initViewListener() {
super.initViewListener();
titleToolBar.setOnClickCallBack(this);
}
@Override
public void onRightIconClick() {
// viewModel.changeFocus(String.valueOf(memberId), b);
}
@Override
public void onBackIconClick() {
finish();
}
private void showFocus(boolean focus) {
Log.d(HTAG, "showFocus: ====>" + focus);
if (focus) {
titleToolBar.setRightIconSrc(R.drawable.fragment_main_my_member_focus_selected);
} else {
titleToolBar.setRightIconSrc(R.drawable.fragment_main_my_member_focus_normal);
}
}
@BindingAdapter("android:ImageSrc")
public static void setImageResource(ImageView imageView, int resource) {
imageView.setImageResource(resource);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_create_task:
editTextDialog = new EditTextDialog(MemberDetailActivity.this,
R.layout.dialog_create_task, memberName);
editTextDialog.show();
editTextDialog.setOnEditTextDialogClickListener(new EditTextDialog.OnEditTextDialogClickListener() {
@Override
public void doCreate(List<String> content) {
// viewModel.createMyTask(memberId, memberName, content.get(0));
}
@Override
public void doSend() {
}
});
break;
}
}
@Override
protected int initVariableId() {
return BR.ViewModel;
}
@Override
protected int setContentViewSrc(Bundle savedInstanceState) {
return R.layout.activity_member_detail;
}
}
|
package com.lti.exceptionhandson;
import java.io.IOException;
import java.util.Scanner;
public class CrewMember
{
public static void main(String[] args)throws IOException,ArithmeticException,NumberFormatException,Exception
{
Scanner s=new Scanner(System.in);
System.out.println("Enter the age:");
int age=s.nextInt();
if(age<18||age>22)
{
throw new MinMaxAgeException(age);
}
else
{
System.out.println("You are a crewmember" +age);
}
}
}
|
package com.example.jinliyu.shoppingapp_1.activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.jinliyu.shoppingapp_1.R;
import com.example.jinliyu.shoppingapp_1.adapter.OrderHistoryAdapter;
import com.example.jinliyu.shoppingapp_1.adapter.SubCateAdapter;
import com.example.jinliyu.shoppingapp_1.data.Order;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class OrderHistoryActivity extends AppCompatActivity {
ArrayList<Order> orderlist;
SharedPreferences sharedPreferences;
String apikey, userid, mobile;
StaggeredGridLayoutManager staggeredGridLayoutManager;
RecyclerView recyclerView;
ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_history);
recyclerView = findViewById(R.id.recyclerviewhistory);
actionBar = getSupportActionBar();
actionBar.setTitle("Order History");
sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
apikey = sharedPreferences.getString("apikey","");
userid = sharedPreferences.getString("userid","");
mobile = sharedPreferences.getString("mobile","");
orderlist = new ArrayList<Order>();
getOrderHistory();
staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, LinearLayoutManager.VERTICAL);
}
private void getOrderHistory(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, "http://rjtmobile.com/aamir/e-commerce/android-app/"+
"order_history.php?api_key="+apikey+"&user_id="+userid+"&mobile="+ mobile, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray orderhistory = response.getJSONArray("Order history");
for(int i= 0; i< orderhistory.length(); i++)
{
JSONObject order =(JSONObject) orderhistory.get(i);
String orderid = order.getString("orderid");
String orderstatus = order.getString("orderstatus");
String shippingName = order.getString("name");
String billingaddr = order.getString("billingadd");
String delivAddr = order.getString("deliveryadd");
String ordermobile = order.getString("mobile");
String orderemail = order.getString("email");
String itemid = order.getString("itemid");
String itemname = order.getString("itemname");
String itemquantity = order.getString("itemquantity");
String totalprice = order.getString("totalprice");
String paidprice = order.getString("paidprice");
String placedon = order.getString("placedon");
Log.i("test","Order placed on : "+ placedon);
Order o = new Order(orderid, orderstatus, shippingName, billingaddr, delivAddr, ordermobile, orderemail, itemid, itemname,itemquantity, totalprice, paidprice,placedon);
orderlist.add(o);
}
recyclerView.setLayoutManager(staggeredGridLayoutManager); // set LayoutManager to RecyclerView
OrderHistoryAdapter orderHistoryAdapter = new OrderHistoryAdapter(OrderHistoryActivity.this, orderlist);
orderHistoryAdapter.notifyDataSetChanged();
recyclerView.setAdapter(orderHistoryAdapter);
} catch (JSONException e) {
e.printStackTrace();
Log.i("test", e.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"System error",Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
}
|
/*
* Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.CertPath;
import java.security.cert.CertificateFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipFile;
import jdk.security.jarsigner.JarSigner;
public class CreateMultiReleaseTestJars {
final private String main =
"package version;\n\n"
+ "public class Main {\n"
+ " public static void main(String[] args) {\n"
+ " Version v = new Version();\n"
+ " System.out.println(\"I am running on version \" + v.getVersion());\n"
+ " }\n"
+ "}\n";
final private String java8 =
"package version;\n\n"
+ "public class Version {\n"
+ " public int getVersion() {\n"
+ " return 8;\n"
+ " }\n"
+ "}\n";
final private String java9 =
"package version;\n\n"
+ "public class Version {\n"
+ " public int getVersion() {\n"
+ " int version = (new PackagePrivate()).getVersion();\n"
+ " if (version == 9) return 9;\n" // strange I know, but easy to test
+ " return version;\n"
+ " }\n"
+ "}\n";
final private String ppjava9 =
"package version;\n\n"
+ "class PackagePrivate {\n"
+ " int getVersion() {\n"
+ " return 9;\n"
+ " }\n"
+ "}\n";
final int currentVersion = Runtime.version().feature();
final String currentVersionStr = Integer.toString(currentVersion);
final private String javaCurrent = java8.replace("8", currentVersionStr);
final String readme8 = "This is the root readme file";
final String readme9 = "This is the version nine readme file";
final String readmeCurrent = "This is the current version readme file";
private Map<String,byte[]> rootClasses;
private Map<String,byte[]> version9Classes;
private Map<String,byte[]> versionCurrentClasses;
public void buildUnversionedJar() throws IOException {
JarBuilder jb = new JarBuilder("unversioned.jar");
jb.addEntry("README", readme8.getBytes());
jb.addEntry("version/Main.java", main.getBytes());
jb.addEntry("version/Main.class", rootClasses.get("version.Main"));
jb.addEntry("version/Version.java", java8.getBytes());
jb.addEntry("version/Version.class", rootClasses.get("version.Version"));
jb.build();
}
public void buildMultiReleaseJar() throws IOException {
JarBuilder jb = customMultiReleaseJar("multi-release.jar", "true");
addEntries(jb);
jb.addEntry("META-INF/versions/9/version/Version.class", version9Classes.get("version.Version"));
jb.build();
}
public void buildShortMultiReleaseJar() throws IOException {
JarBuilder jb = customMultiReleaseJar("short-multi-release.jar", "true");
addEntries(jb);
jb.build();
}
private JarBuilder customMultiReleaseJar(String filename, String multiReleaseValue)
throws IOException {
JarBuilder jb = new JarBuilder(filename);
jb.addAttribute("Multi-Release", multiReleaseValue);
return jb;
}
public void buildCustomMultiReleaseJar(String filename, String multiReleaseValue,
Map<String, String> extraAttributes) throws IOException {
buildCustomMultiReleaseJar(filename, multiReleaseValue, extraAttributes, false);
}
public void buildCustomMultiReleaseJar(String filename, String multiReleaseValue,
Map<String, String> extraAttributes, boolean addEntries) throws IOException {
JarBuilder jb = new JarBuilder(filename);
extraAttributes.entrySet()
.forEach(entry -> jb.addAttribute(entry.getKey(), entry.getValue()));
if (addEntries) {
addEntries(jb);
}
jb.addAttribute("Multi-Release", multiReleaseValue);
jb.build();
}
private void addEntries(JarBuilder jb) {
jb.addEntry("README", readme8.getBytes());
jb.addEntry("version/Main.java", main.getBytes());
jb.addEntry("version/Main.class", rootClasses.get("version.Main"));
jb.addEntry("version/Version.java", java8.getBytes());
jb.addEntry("version/Version.class", rootClasses.get("version.Version"));
jb.addEntry("META-INF/versions/9/README", readme9.getBytes());
jb.addEntry("META-INF/versions/9/version/Version.java", java9.getBytes());
jb.addEntry("META-INF/versions/9/version/PackagePrivate.java", ppjava9.getBytes());
jb.addEntry("META-INF/versions/9/version/PackagePrivate.class", version9Classes.get("version.PackagePrivate"));
jb.addEntry("META-INF/versions/" + currentVersionStr + "/README", readmeCurrent.getBytes());
jb.addEntry("META-INF/versions/" + currentVersionStr + "/version/Version.java", javaCurrent.getBytes());
jb.addEntry("META-INF/versions/" + currentVersionStr + "/version/Version.class", versionCurrentClasses.get("version.Version"));
}
public void buildSignedMultiReleaseJar() throws Exception {
buildSignedMultiReleaseJar("multi-release.jar", "signed-multi-release.jar");
}
public void buildSignedMultiReleaseJar(String multiReleaseJar,
String signedMultiReleaseJar) throws Exception
{
String testsrc = System.getProperty("test.src",".");
String testdir = findTestDir(testsrc);
String keystore = testdir + "/sun/security/tools/jarsigner/JarSigning.keystore";
// jarsigner -keystore keystore -storepass "bbbbbb"
// -signedJar signed-multi-release.jar multi-release.jar b
char[] password = "bbbbbb".toCharArray();
KeyStore ks = KeyStore.getInstance(new File(keystore), password);
PrivateKey pkb = (PrivateKey)ks.getKey("b", password);
CertPath cp = CertificateFactory.getInstance("X.509")
.generateCertPath(Arrays.asList(ks.getCertificateChain("b")));
JarSigner js = new JarSigner.Builder(pkb, cp).build();
try (ZipFile in = new ZipFile(multiReleaseJar);
FileOutputStream os = new FileOutputStream(signedMultiReleaseJar))
{
js.sign(in, os);
}
}
String findTestDir(String dir) throws IOException {
Path path = Paths.get(dir).toAbsolutePath();
Path child = null;
while (path != null && !path.endsWith("test")) {
child = path;
path = path.getParent();
}
if (child == null) {
throw new IllegalArgumentException(dir + " is not in a test directory");
}
if (!Files.isDirectory(child)) {
throw new IOException(child.toString() + " is not a directory");
}
return child.toString();
}
void compileEntries() {
Map<String,String> input = new HashMap<>();
input.put("version.Main", main);
input.put("version.Version", java8);
rootClasses = (new Compiler(input)).setRelease(8).compile();
input.clear();
input.put("version.Version", java9);
input.put("version.PackagePrivate", ppjava9);
version9Classes = (new Compiler(input)).setRelease(9).compile();
input.clear();
input.put("version.Version", javaCurrent);
versionCurrentClasses = (new Compiler(input)).compile(); // Use default release
}
}
|
package GenericDemo;
/**
* A generic type can be restricted, by type of class or/and one to many
* interface types (by using logical operator AND). Keyword 'extends' to set the
* upper boundaries. Keyword 'super' to set the lover boundaries.
*
* @author Bohdan Skrypnyk
*/
// non generic superclass
class NonGen {
int num;
public NonGen(int num) {
this.num = num;
}
public void setNum(int num) {
this.num = num;
}
}
// the class 'Gen1' is the generic subclass
class Gen1<T> extends NonGen {
T obj;// object of the type 'T'
// the class 'Gen1' receive generic object and int
public Gen1(T obj, int num) {
super(num);
this.obj = obj;
}
// getter for 'obj'
public T getObj() {
return obj;
}
}
public class GenSuperDemo1 {
public static void main(String args[]) {
// create an object of the type 'Gen1' for strings
Gen1<String> gener2 = new Gen1<String>("'new line'", 44);
System.out.println("String : " + gener2.obj);
System.out.println("int : " + gener2.num);
}
}
|
package com.beiyelin.common.document;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by newmann on 2017-09-12.
*/
@XmlRootElement(name = "word")
public class WordInfo extends OfficeInfo{
}
|
package com.snab.tachkit.fragments;
import com.snab.tachkit.ClassesJson.ListAdverts;
import com.snab.tachkit.globalOptions.SharedPreferencesCustom;
import com.snab.tachkit.additional.TableNews;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.snab.tachkit.allForm.FormLogIn;
import android.widget.GridView;
import com.snab.tachkit.R;
import com.snab.tachkit.additional.TableRow;
import java.util.ArrayList;
/**
* Created by Таня on 25.12.2014.
* Фрагмент, относящийся к меню (таблица с объявлениями)
*/
public class DrawerPlaceholder extends FragmentWithUpdate{
private static final String ARG_NAME_LAYOUT = "name_layout";
View view;
int lastIndex = -1;
ArrayList<ListAdverts.OptionsAdvert> adverts;
Integer countLoadingPage;
TableRow tableRow;
public static DrawerPlaceholder newInstance(int nameLayout) {
DrawerPlaceholder fragment = new DrawerPlaceholder();
Bundle args = new Bundle();
args.putInt(ARG_NAME_LAYOUT, nameLayout);
fragment.setArguments(args);
fragment.setRetainInstance(true);
return fragment;
}
public final int nameLayout(){
return getArguments().getInt(ARG_NAME_LAYOUT);
}
public DrawerPlaceholder() {
}
/**
* инициализация внутреностей фрагмента
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(lastIndex == nameLayout() && nameLayout() == 1){
((ViewGroup) view.getParent()).removeView(view);
}else {
switch (nameLayout()) {
case 0:
if (SharedPreferencesCustom.containsSearchStrUser(getActivity())) {
SharedPreferencesCustom.setSearchStrUser(getActivity(), null);
}
view = inflater.inflate(R.layout.fragment_main_advert, container, false);
initView(view, 0);
if(adverts != null && countLoadingPage != null){
tableRow = new TableRow(this, (GridView) view.findViewById(R.id.my_advert_1), 0, adverts, countLoadingPage, view);
}else{
tableRow = new TableRow(this, (GridView) view.findViewById(R.id.my_advert_1), 0);
}
break;
case 1:
view = inflater.inflate(R.layout.fragment_main_news, container, false);
new TableNews(this, (GridView) view.findViewById(R.id.my_advert_1));
initView(view);
break;
case 2:
FormLogIn formLogIn = new FormLogIn(inflater, this, container);
view = formLogIn.getView();
break;
}
}
lastIndex = nameLayout();
return view;
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if(nameLayout() == 0) {
adverts = tableRow.getAdverts();
countLoadingPage = tableRow.getCountPage();
}
}
}
|
package com.onplan.service;
import com.onplan.adviser.strategy.Strategy;
import com.onplan.domain.transitory.PriceTick;
import java.util.List;
public interface StrategyService extends StrategyServiceRemote {
public void onPriceTick(final PriceTick priceTick);
public void setInstrumentSubscriptionListener(
InstrumentSubscriptionListener instrumentSubscriptionListener);
public List<Strategy> getStrategies();
public void loadAllStrategies() throws Exception;
public void unLoadAllStrategies() throws Exception;
}
|
package org.simpleflatmapper.converter.protobuf;
import com.google.protobuf.Timestamp;
import org.simpleflatmapper.converter.AbstractConverterFactoryProducer;
import org.simpleflatmapper.converter.ConverterFactory;
import org.simpleflatmapper.util.Consumer;
import java.util.Date;
public class ProtobufConverterFactoryProducer extends AbstractConverterFactoryProducer {
@Override
public void produce(Consumer<? super ConverterFactory<?, ?>> consumer) {
constantConverter(consumer, Date.class, Timestamp.class, new DateToPTimestampConverter());
constantConverter(consumer, Long.class, Timestamp.class, new LongToPTimestampConverter());
}
}
|
package com.avogine.junkyard.audio;
import org.lwjgl.openal.AL10;
import com.avogine.junkyard.audio.data.OggData;
import com.avogine.junkyard.audio.data.WaveData;
import com.avogine.junkyard.memory.MemoryManaged;
public class AudioBuffer implements MemoryManaged {
private int id;
public AudioBuffer() {
this.id = AL10.alGenBuffers();
}
// XXX BLEH
public void loadToBuffer(WaveData data) {
AL10.alBufferData(id, data.getFormat(), data.getData(), data.getFrequency());
}
public void loadToBuffer(OggData data) {
AL10.alBufferData(id, data.getFormat(), data.getData(), data.getFrequency());
}
public int getId() {
return id;
}
@Override
public void cleanUp() {
AL10.alDeleteBuffers(id);
}
}
|
package com.dyny.gms.db.pojo;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WarningExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public WarningExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andStIdIsNull() {
addCriterion("st_id is null");
return (Criteria) this;
}
public Criteria andStIdIsNotNull() {
addCriterion("st_id is not null");
return (Criteria) this;
}
public Criteria andStIdEqualTo(Integer value) {
addCriterion("st_id =", value, "stId");
return (Criteria) this;
}
public Criteria andStIdNotEqualTo(Integer value) {
addCriterion("st_id <>", value, "stId");
return (Criteria) this;
}
public Criteria andStIdGreaterThan(Integer value) {
addCriterion("st_id >", value, "stId");
return (Criteria) this;
}
public Criteria andStIdGreaterThanOrEqualTo(Integer value) {
addCriterion("st_id >=", value, "stId");
return (Criteria) this;
}
public Criteria andStIdLessThan(Integer value) {
addCriterion("st_id <", value, "stId");
return (Criteria) this;
}
public Criteria andStIdLessThanOrEqualTo(Integer value) {
addCriterion("st_id <=", value, "stId");
return (Criteria) this;
}
public Criteria andStIdIn(List<Integer> values) {
addCriterion("st_id in", values, "stId");
return (Criteria) this;
}
public Criteria andStIdNotIn(List<Integer> values) {
addCriterion("st_id not in", values, "stId");
return (Criteria) this;
}
public Criteria andStIdBetween(Integer value1, Integer value2) {
addCriterion("st_id between", value1, value2, "stId");
return (Criteria) this;
}
public Criteria andStIdNotBetween(Integer value1, Integer value2) {
addCriterion("st_id not between", value1, value2, "stId");
return (Criteria) this;
}
public Criteria andStNoIsNull() {
addCriterion("st_no is null");
return (Criteria) this;
}
public Criteria andStNoIsNotNull() {
addCriterion("st_no is not null");
return (Criteria) this;
}
public Criteria andStNoEqualTo(String value) {
addCriterion("st_no =", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoNotEqualTo(String value) {
addCriterion("st_no <>", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoGreaterThan(String value) {
addCriterion("st_no >", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoGreaterThanOrEqualTo(String value) {
addCriterion("st_no >=", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoLessThan(String value) {
addCriterion("st_no <", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoLessThanOrEqualTo(String value) {
addCriterion("st_no <=", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoLike(String value) {
addCriterion("st_no like", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoNotLike(String value) {
addCriterion("st_no not like", value, "stNo");
return (Criteria) this;
}
public Criteria andStNoIn(List<String> values) {
addCriterion("st_no in", values, "stNo");
return (Criteria) this;
}
public Criteria andStNoNotIn(List<String> values) {
addCriterion("st_no not in", values, "stNo");
return (Criteria) this;
}
public Criteria andStNoBetween(String value1, String value2) {
addCriterion("st_no between", value1, value2, "stNo");
return (Criteria) this;
}
public Criteria andStNoNotBetween(String value1, String value2) {
addCriterion("st_no not between", value1, value2, "stNo");
return (Criteria) this;
}
public Criteria andMachNoIsNull() {
addCriterion("mach_no is null");
return (Criteria) this;
}
public Criteria andMachNoIsNotNull() {
addCriterion("mach_no is not null");
return (Criteria) this;
}
public Criteria andMachNoEqualTo(String value) {
addCriterion("mach_no =", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoNotEqualTo(String value) {
addCriterion("mach_no <>", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoGreaterThan(String value) {
addCriterion("mach_no >", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoGreaterThanOrEqualTo(String value) {
addCriterion("mach_no >=", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoLessThan(String value) {
addCriterion("mach_no <", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoLessThanOrEqualTo(String value) {
addCriterion("mach_no <=", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoLike(String value) {
addCriterion("mach_no like", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoNotLike(String value) {
addCriterion("mach_no not like", value, "machNo");
return (Criteria) this;
}
public Criteria andMachNoIn(List<String> values) {
addCriterion("mach_no in", values, "machNo");
return (Criteria) this;
}
public Criteria andMachNoNotIn(List<String> values) {
addCriterion("mach_no not in", values, "machNo");
return (Criteria) this;
}
public Criteria andMachNoBetween(String value1, String value2) {
addCriterion("mach_no between", value1, value2, "machNo");
return (Criteria) this;
}
public Criteria andMachNoNotBetween(String value1, String value2) {
addCriterion("mach_no not between", value1, value2, "machNo");
return (Criteria) this;
}
public Criteria andActionTypeIsNull() {
addCriterion("action_type is null");
return (Criteria) this;
}
public Criteria andActionTypeIsNotNull() {
addCriterion("action_type is not null");
return (Criteria) this;
}
public Criteria andActionTypeEqualTo(Integer value) {
addCriterion("action_type =", value, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeNotEqualTo(Integer value) {
addCriterion("action_type <>", value, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeGreaterThan(Integer value) {
addCriterion("action_type >", value, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeGreaterThanOrEqualTo(Integer value) {
addCriterion("action_type >=", value, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeLessThan(Integer value) {
addCriterion("action_type <", value, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeLessThanOrEqualTo(Integer value) {
addCriterion("action_type <=", value, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeIn(List<Integer> values) {
addCriterion("action_type in", values, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeNotIn(List<Integer> values) {
addCriterion("action_type not in", values, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeBetween(Integer value1, Integer value2) {
addCriterion("action_type between", value1, value2, "actionType");
return (Criteria) this;
}
public Criteria andActionTypeNotBetween(Integer value1, Integer value2) {
addCriterion("action_type not between", value1, value2, "actionType");
return (Criteria) this;
}
public Criteria andActionIsNull() {
addCriterion("action is null");
return (Criteria) this;
}
public Criteria andActionIsNotNull() {
addCriterion("action is not null");
return (Criteria) this;
}
public Criteria andActionEqualTo(String value) {
addCriterion("action =", value, "action");
return (Criteria) this;
}
public Criteria andActionNotEqualTo(String value) {
addCriterion("action <>", value, "action");
return (Criteria) this;
}
public Criteria andActionGreaterThan(String value) {
addCriterion("action >", value, "action");
return (Criteria) this;
}
public Criteria andActionGreaterThanOrEqualTo(String value) {
addCriterion("action >=", value, "action");
return (Criteria) this;
}
public Criteria andActionLessThan(String value) {
addCriterion("action <", value, "action");
return (Criteria) this;
}
public Criteria andActionLessThanOrEqualTo(String value) {
addCriterion("action <=", value, "action");
return (Criteria) this;
}
public Criteria andActionLike(String value) {
addCriterion("action like", value, "action");
return (Criteria) this;
}
public Criteria andActionNotLike(String value) {
addCriterion("action not like", value, "action");
return (Criteria) this;
}
public Criteria andActionIn(List<String> values) {
addCriterion("action in", values, "action");
return (Criteria) this;
}
public Criteria andActionNotIn(List<String> values) {
addCriterion("action not in", values, "action");
return (Criteria) this;
}
public Criteria andActionBetween(String value1, String value2) {
addCriterion("action between", value1, value2, "action");
return (Criteria) this;
}
public Criteria andActionNotBetween(String value1, String value2) {
addCriterion("action not between", value1, value2, "action");
return (Criteria) this;
}
public Criteria andSeeIsNull() {
addCriterion("see is null");
return (Criteria) this;
}
public Criteria andSeeIsNotNull() {
addCriterion("see is not null");
return (Criteria) this;
}
public Criteria andSeeEqualTo(Boolean value) {
addCriterion("see =", value, "see");
return (Criteria) this;
}
public Criteria andSeeNotEqualTo(Boolean value) {
addCriterion("see <>", value, "see");
return (Criteria) this;
}
public Criteria andSeeGreaterThan(Boolean value) {
addCriterion("see >", value, "see");
return (Criteria) this;
}
public Criteria andSeeGreaterThanOrEqualTo(Boolean value) {
addCriterion("see >=", value, "see");
return (Criteria) this;
}
public Criteria andSeeLessThan(Boolean value) {
addCriterion("see <", value, "see");
return (Criteria) this;
}
public Criteria andSeeLessThanOrEqualTo(Boolean value) {
addCriterion("see <=", value, "see");
return (Criteria) this;
}
public Criteria andSeeIn(List<Boolean> values) {
addCriterion("see in", values, "see");
return (Criteria) this;
}
public Criteria andSeeNotIn(List<Boolean> values) {
addCriterion("see not in", values, "see");
return (Criteria) this;
}
public Criteria andSeeBetween(Boolean value1, Boolean value2) {
addCriterion("see between", value1, value2, "see");
return (Criteria) this;
}
public Criteria andSeeNotBetween(Boolean value1, Boolean value2) {
addCriterion("see not between", value1, value2, "see");
return (Criteria) this;
}
public Criteria andInterTimeIsNull() {
addCriterion("inter_time is null");
return (Criteria) this;
}
public Criteria andInterTimeIsNotNull() {
addCriterion("inter_time is not null");
return (Criteria) this;
}
public Criteria andInterTimeEqualTo(Date value) {
addCriterion("inter_time =", value, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeNotEqualTo(Date value) {
addCriterion("inter_time <>", value, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeGreaterThan(Date value) {
addCriterion("inter_time >", value, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeGreaterThanOrEqualTo(Date value) {
addCriterion("inter_time >=", value, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeLessThan(Date value) {
addCriterion("inter_time <", value, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeLessThanOrEqualTo(Date value) {
addCriterion("inter_time <=", value, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeIn(List<Date> values) {
addCriterion("inter_time in", values, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeNotIn(List<Date> values) {
addCriterion("inter_time not in", values, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeBetween(Date value1, Date value2) {
addCriterion("inter_time between", value1, value2, "interTime");
return (Criteria) this;
}
public Criteria andInterTimeNotBetween(Date value1, Date value2) {
addCriterion("inter_time not between", value1, value2, "interTime");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
class Point {
int x, y;
Point(int a, int b) {
x = a;
y = b;
}
}
public class ep3_7 {
public static void main(String args[]) {
Point p1, p2; // 声明对象p1和p2
p1 = new Point(10, 10); // 为对象分配内存,使用 new 和类中的构造方法
p2 = new Point(23, 35); // 为对象分配内存,使用 new 和类中的构造方法
System.out.println(p1 == p2);
p1 = p2;
System.out.println(p1 == p2);
}
}
|
package com.smxknife.servlet.tomcat.getParameter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author smxknife
* 2019/8/26
*/
@WebServlet("/multiformdata")
@MultipartConfig(
location = "/Users/ShaoYun/local/workstation/programs/smxknife/smxknife/smxknife-servlet/smxknife-servlet-tomcat/target/temp"
)
public class RequestGetParameterWith_enctype_multipart_form_data extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("content type = " + req.getContentType());
System.out.println("request parameters =======================");
String boundary = req.getHeader("boundary");
System.out.println("request boundary = " + boundary);
Part name = req.getPart("name");
System.out.println("part name : " + name.getName());
req.getParts().stream().forEach(part -> {
System.out.println(part.getName());
part.getHeaderNames().forEach(headername -> {
System.out.println(part.getName() + " - headerName = " + headername);
});
System.out.println(part.getName() + " - submittedFileName = " + part.getSubmittedFileName());
try {
char[] chars = new char[(int) part.getSize()];
new InputStreamReader(part.getInputStream()).read(chars);
System.out.println(part.getName() + " - content = " + new String(chars));
} catch (IOException e) {
e.printStackTrace();
}
});
// req.getParameterMap().entrySet().forEach(entry -> {
// String name = entry.getKey();
// String value = Arrays.asList(entry.getValue()).stream().collect(Collectors.joining(", "));
// System.out.printf("name = %s, value = %s\r\n", name, value);
// });
System.out.println("==========================================");
}
}
|
package fun.witt.lambda;
/**
* @author witt
* @fileName RunnableDemo
* @date 2018/8/18 13:17
* @description
* @history <author> <time> <version> <desc>
*/
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println("start ...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end ...");
}
public static void main(String[] args) {
new Thread(new RunnableDemo()).start();
new Thread(() -> System.out.println("start")).start();
}
}
|
package ua.project.protester.model.executable.result.subtype;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import ua.project.protester.exception.executable.action.ActionExecutionException;
import ua.project.protester.model.executable.result.ActionResultDto;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ActionResultUiDto extends ActionResultDto {
private String path;
public ActionResultUiDto(ActionExecutionException e, String path) {
super(e);
this.path = path;
}
public ActionResultUiDto(ActionResultDto that, String path) {
super(that);
this.path = path;
}
}
|
package com.tencent.mm.ui.gridviewheaders;
import android.database.DataSetObserver;
final class f$a extends DataSetObserver {
final /* synthetic */ f uuD;
private f$a(f fVar) {
this.uuD = fVar;
}
/* synthetic */ f$a(f fVar, byte b) {
this(fVar);
}
public final void onChanged() {
f.a(this.uuD, this.uuD.a(f.a(this.uuD)));
this.uuD.notifyDataSetChanged();
}
public final void onInvalidated() {
f.a(this.uuD, this.uuD.a(f.a(this.uuD)));
this.uuD.notifyDataSetInvalidated();
}
}
|
package com.yunhe.basicdata.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunhe.basicdata.entity.Commclass;
import com.yunhe.basicdata.entity.CommodityList;
import com.yunhe.basicdata.dao.CommodityListMapper;
import com.yunhe.basicdata.entity.WarehouseManagement;
import com.yunhe.basicdata.service.ICommodityListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 商品列表 服务实现类
* </p>
*
* @author 李恒逵, 唐凯宽
* @since 2019-01-02
*/
@Service
public class CommodityListServiceImpl extends ServiceImpl<CommodityListMapper, CommodityList> implements ICommodityListService {
@Resource
CommodityListMapper commodityListMapper;
/**
* 查询列表 分页
* @param current 当前页
* @param size 每页的条数
* @param commodityList 查询商品的实体类
* @return 返回分页的信息
*/
@Override
public Map selectAllcommList(int current, int size,CommodityList commodityList) {
Page page=new Page(current,size);
List<CommodityList> comlist = commodityListMapper.selectAllCommmList(page);
Map map = new HashMap();
map.put("total", page.getTotal());
map.put("pages", page.getPages());
map.put("commodityList",commodityList);
map.put("comlist", comlist);
return map;
}
/**
* 增加商品的信息
* @param commodityList 增加商品的实体类
* @return 返回增加后的商品信息
*/
@Override
public int insertComm(CommodityList commodityList) {
return commodityListMapper.insertComm(commodityList);
}
/**
* 查询用户的详细信息
* @param id 查询用户的id
* @return 根据id查询的信息
*/
@Override
public CommodityList selectCommById(int id) {
return commodityListMapper.selectCommById(id);
}
/**
* 更改商品的信息
*
* @param commodityList 更改商品的实体类
* @return 返回更改后的信息
*/
@Override
public int updateComm(CommodityList commodityList) {
return commodityListMapper.updateComm(commodityList);
}
/**
* 删除商品的信息
*
* @param commodityList 删除商品的实体类
* @return 无返回
*/
@Override
public int deleteComm(CommodityList commodityList) {
return commodityListMapper.deleteComm(commodityList);
}
/**
* 模糊查询
*
* @param data 模糊查询的条件
* @return 返回模糊查询的信息
*/
@Override
public List<CommodityList> selectCommstlist(String data) {
List<CommodityList> commodityLists = (List<CommodityList>) commodityListMapper.selectList(new QueryWrapper<CommodityList>().like("cl_name", data).or().like("cl_scan", data));
return commodityLists;
}
/**
* 导出excel
* @return
*/
@Override
public List<CommodityList> ExportExcel() {
return commodityListMapper.selectExcel();
}
/**
* 查询仓库名
* @param id 商品id
* @return
*/
@Override
public WarehouseManagement selectWmAndComm(int id) {
return commodityListMapper.selectwmandcomm(id);
}
/**
* 查询商品的分类
* @param id 商品的id
* @return
*/
@Override
public Commclass selectclassAndComm(int id) {
return commodityListMapper.selectComclassAndCommdity(id);
}
@Override
public Map selectComclassList1() {
List<CommodityList> list = commodityListMapper.selectComclassList1();
Map<String, Object> map = new HashMap<>();
map.put("list",list);
return map;
}
/**
* 根据商品名查询
* @author 史江浩
* @param clName 查询的条件
* @return
*/
@Override
public CommodityList selectListByClName(String clName) {
CommodityList list = commodityListMapper.selectListByClName(clName);
return list;
}
}
|
package bdapp;
import java.util.List;
public interface UsuarioInterface {
public usuario getUser(String username);
public List<usuario> getUsers();
}
|
package com.xueqiu.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
@WebServlet(name="fakeUrl", urlPatterns="/12308/safeteam/verifyuser")
public class FakeUrl extends HttpServlet {
private static final long serialVersionUID = 8319413355379882134L;
private static Logger logger = Logger.getLogger(FakeUrl.class);
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
logger.warn("someone is connect to me");
req.setCharacterEncoding("UTF-8");
req.getRequestDispatcher("/12308.jsp").forward(req, res);
}
}
|
package com.zh.ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.*;
public class MyStartFlashingPanel extends JPanel implements Runnable{
int times=1;
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(0, 0, 600, 600);
if(times%2==0)
{
//给出提示信息
g.setColor(Color.yellow);
Font mtFont=new Font("华文新魏",Font.BOLD,30);
g.setFont(mtFont);
g.drawString("贪吃蛇游戏", 200, 280);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
try{
Thread.sleep(800);
}catch(Exception e)
{
e.printStackTrace();
}
times++;
//重画
this.repaint();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
package ThreadDemo;
/**
*
* @author Bohdan Skrypnyk
*/
class NewThread2 implements Runnable {
String name;
Thread tred;
NewThread2(String treadname) {
name = treadname;
tred = new Thread(this, name); //Doesn't whant to run without traget and name
//tred.setPriority(Thread.MAX_PRIORITY);
tred.setPriority(Thread.MIN_PRIORITY);
System.out.println("New thread" + tred);
tred.start();
}
@Override
public void run() {
try {
for (int i = 10; i > 0; --i) {
System.out.println(name + " thread : " + i);
Thread.sleep(1000);
}
} catch (InterruptedException ex) {
System.out.println(name + "thread interrupted");
}
System.out.println(name + "thread finished");
}
}
public class DemoJoin {
public static void main(String args[]) {
NewThread2 mytred1 = new NewThread2("First");
NewThread2 mytred2 = new NewThread2("Second");
NewThread2 mytred3 = new NewThread2("Third");
//isAlive() check if thread is active adn return true/false
System.out.println("First thread runned " + mytred1.tred.isAlive());
System.out.println("Second thread runned " + mytred2.tred.isAlive());
System.out.println("Third thread runned " + mytred3.tred.isAlive());
//Threads finished after method join(); return control
try {
System.out.println("Waiting while threads will be finished");
mytred1.tred.join();
mytred2.tred.join();
mytred3.tred.join();
} catch (InterruptedException ex) {
System.out.println("Thread interrupted");
}
System.out.println("First thread runned " + mytred1.tred.isAlive());
System.out.println("Second thread runned " + mytred2.tred.isAlive());
System.out.println("Third thread runned " + mytred3.tred.isAlive());
System.out.println("Main thread finished");
}
}
|
package com.liufeng.domian.dto.request;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
@ApiModel(description = "用户更新信息表")
public class UserModifyRequestDTO {
@ApiModelProperty(value = "id不为空时表示修改")
private Integer id;
@ApiModelProperty(value = "phone", required = true)
@NotBlank(message = "phone不能为空")
private String phone;
@ApiModelProperty(value = "姓名", required = true)
private String name;
@ApiModelProperty(value = "密码", required = true)
@NotBlank(message = "密码不能为空")
private String password;
@ApiModelProperty(value = "用户状态", required = true)
@NotBlank(message = "用户状态不能为空")
private String lockStatus;
@ApiModelProperty(value = "操作人", required = true)
@NotBlank(message = "操作人不能为空")
private String user;
}
|
package com.espendwise.manta.dao;
import com.espendwise.manta.model.data.AddressData;
import com.espendwise.manta.model.view.ContactView;
import com.espendwise.manta.util.Utility;
import javax.persistence.EntityManager;
public class AddressDAOImpl extends DAOImpl implements AddressDAO{
public AddressDAOImpl(EntityManager entityManager) {
super(entityManager);
}
@Override
public AddressData create(AddressData address) {
return super.create(address);
}
@Override
public AddressData update(AddressData addressData) {
return super.update(addressData);
}
@Override
public AddressData updateEntityAddress(Long busEntityId, AddressData addressData) {
if (addressData != null && Utility.longNN(busEntityId) > 0) {
addressData.setBusEntityId(busEntityId);
if (addressData.getAddressId() == null) {
addressData = super.create(addressData);
} else {
addressData = super.update(addressData);
}
}
return addressData;
}
@Override
public AddressData updateUserAddress(Long userId, AddressData addressData) {
if (addressData != null && Utility.longNN(userId) > 0) {
addressData.setUserId(userId);
if (addressData.getAddressId() == null) {
addressData = super.create(addressData);
} else {
addressData = super.update(addressData);
}
}
return addressData;
}
@Override
public void removeContact(ContactView contact) {
if (contact != null) {
if (contact.getAddress() != null) {
em.remove(contact.getAddress());
}
if (contact.getEmail() != null) {
em.remove(contact.getEmail());
}
if (contact.getFaxPhone() != null) {
em.remove(contact.getFaxPhone());
}
if (contact.getMobilePhone() != null) {
em.remove(contact.getMobilePhone());
}
if (contact.getPhone() != null) {
em.remove(contact.getPhone());
}
}
}
}
|
import java.util.*;
class Solution {
public List<String> generateParenthesis(int n) {
List<String> r = new ArrayList<String>();
generate(r, n, 0, 0, "");
return r;
}
public void generate(List<String> result, int n, int l, int r, String s) {
if (r == n)
result.add(s);
if (l < n) generate(result, n, l+1, r, s+"(");
if (r < l) generate(result, n, l, r+1, s+")");
}
public static void main(String[] args) {
Solution s = new Solution();
List<String> r = s.generateParenthesis(3);
for (String str : r) {
System.out.println(str);
}
}
}
|
package com.stackInstance.HighChartDatabase.model;
public class CountList {
private Long count;
private int day;
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
public CountList(Long count, int day) {
super();
this.count = count;
this.day = day;
}
}
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.bwcompat;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.util.English;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.count.CountResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.routing.IndexRoutingTable;
import org.elasticsearch.cluster.routing.IndexShardRoutingTable;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.decider.EnableAllocationDecider;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ElasticsearchBackwardsCompatIntegrationTest;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
/**
*/
public class BasicBackwardsCompatibilityTest extends ElasticsearchBackwardsCompatIntegrationTest {
/**
* Basic test using Index & Realtime Get with external versioning. This test ensures routing works correctly across versions.
*/
@Test
public void testExternalVersion() throws Exception {
createIndex("test");
final boolean routing = randomBoolean();
int numDocs = randomIntBetween(10, 20);
for (int i = 0; i < numDocs; i++) {
String id = Integer.toString(i);
String routingKey = routing ? randomRealisticUnicodeOfLength(10) : null;
client().prepareIndex("test", "type1", id).setRouting(routingKey).setVersion(1).setVersionType(VersionType.EXTERNAL).setSource("field1", English.intToEnglish(i)).get();
GetResponse get = client().prepareGet("test", "type1", id).setRouting(routingKey).get();
assertThat("Document with ID " +id + " should exist but doesn't", get.isExists(), is(true));
assertThat(get.getVersion(), equalTo(1l));
client().prepareIndex("test", "type1", id).setRouting(routingKey).setVersion(2).setVersionType(VersionType.EXTERNAL).setSource("field1", English.intToEnglish(i)).get();
get = client().prepareGet("test", "type1", id).setRouting(routingKey).get();
assertThat("Document with ID " +id + " should exist but doesn't", get.isExists(), is(true));
assertThat(get.getVersion(), equalTo(2l));
}
}
/**
* Basic test using Index & Realtime Get with internal versioning. This test ensures routing works correctly across versions.
*/
@Test
public void testInternalVersion() throws Exception {
createIndex("test");
final boolean routing = randomBoolean();
int numDocs = randomIntBetween(10, 20);
for (int i = 0; i < numDocs; i++) {
String routingKey = routing ? randomRealisticUnicodeOfLength(10) : null;
String id = Integer.toString(i);
assertThat(id, client().prepareIndex("test", "type1", id).setRouting(routingKey).setSource("field1", English.intToEnglish(i)).get().isCreated(), is(true));
GetResponse get = client().prepareGet("test", "type1", id).setRouting(routingKey).get();
assertThat("Document with ID " +id + " should exist but doesn't", get.isExists(), is(true));
assertThat(get.getVersion(), equalTo(1l));
client().prepareIndex("test", "type1", id).setRouting(routingKey).setSource("field1", English.intToEnglish(i)).execute().actionGet();
get = client().prepareGet("test", "type1", id).setRouting(routingKey).get();
assertThat("Document with ID " +id + " should exist but doesn't", get.isExists(), is(true));
assertThat(get.getVersion(), equalTo(2l));
}
}
/**
* Very basic bw compat test with a mixed version cluster random indexing and lookup by ID via term query
*/
@Test
public void testIndexAndSearch() throws Exception {
createIndex("test");
int numDocs = randomIntBetween(10, 20);
List<IndexRequestBuilder> builder = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
String id = Integer.toString(i);
builder.add(client().prepareIndex("test", "type1", id).setSource("field1", English.intToEnglish(i), "the_id", id));
}
indexRandom(true, builder);
for (int i = 0; i < numDocs; i++) {
String id = Integer.toString(i);
assertHitCount(client().prepareSearch().setQuery(QueryBuilders.termQuery("the_id", id)).get(), 1);
}
}
@Test
public void testRecoverFromPreviousVersion() throws ExecutionException, InterruptedException {
assertAcked(prepareCreate("test").setSettings(ImmutableSettings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
ensureYellow();
assertAllShardsOnNodes("test", backwardsCluster().backwardsNodePattern());
int numDocs = randomIntBetween(100, 150);
IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex("test", "type1", randomRealisticUnicodeOfLength(10) + String.valueOf(i)).setSource("field1", English.intToEnglish(i));
}
indexRandom(true, docs);
CountResponse countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
backwardsCluster().allowOnlyNewNodes("test");
ensureYellow("test");// move all shards to the new node
final int numIters = randomIntBetween(10, 20);
for (int i = 0; i < numIters; i++) {
countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
}
}
/**
* Test that ensures that we will never recover from a newer to an older version (we are not forward compatible)
*/
@Test
public void testNoRecoveryFromNewNodes() throws ExecutionException, InterruptedException {
assertAcked(prepareCreate("test").setSettings(ImmutableSettings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().backwardsNodePattern()).put(indexSettings())));
if (backwardsCluster().numNewDataNodes() == 0) {
backwardsCluster().startNewNode();
}
ensureYellow();
assertAllShardsOnNodes("test", backwardsCluster().newNodePattern());
if (randomBoolean()) {
backwardsCluster().allowOnAllNodes("test");
}
int numDocs = randomIntBetween(100, 150);
IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex("test", "type1", randomRealisticUnicodeOfLength(10) + String.valueOf(i)).setSource("field1", English.intToEnglish(i));
}
indexRandom(true, docs);
backwardsCluster().allowOnAllNodes("test");
while(ensureYellow() != ClusterHealthStatus.GREEN) {
backwardsCluster().startNewNode();
}
assertAllShardsOnNodes("test", backwardsCluster().newNodePattern());
CountResponse countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
final int numIters = randomIntBetween(10, 20);
for (int i = 0; i < numIters; i++) {
countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
}
}
public void assertAllShardsOnNodes(String index, String pattern) {
ClusterState clusterState = client().admin().cluster().prepareState().execute().actionGet().getState();
for (IndexRoutingTable indexRoutingTable : clusterState.routingTable()) {
for (IndexShardRoutingTable indexShardRoutingTable : indexRoutingTable) {
for (ShardRouting shardRouting : indexShardRoutingTable) {
if (shardRouting.currentNodeId() != null && index.equals(shardRouting.getIndex())) {
String name = clusterState.nodes().get(shardRouting.currentNodeId()).name();
assertThat("Allocated on new node: " + name, Regex.simpleMatch(pattern, name), is(true));
}
}
}
}
}
/**
* Upgrades a single node to the current version
*/
@Test
public void testIndexUpgradeSingleNode() throws Exception {
assertAcked(prepareCreate("test").setSettings(ImmutableSettings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
int numDocs = randomIntBetween(100, 150);
IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex("test", "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i));
}
indexRandom(true, docs);
assertAllShardsOnNodes("test", backwardsCluster().backwardsNodePattern());
client().admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, "none")).get();
backwardsCluster().allowOnAllNodes("test");
CountResponse countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
backwardsCluster().upgradeOneNode();
ensureYellow("test");
if (randomBoolean()) {
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex("test", "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i));
}
indexRandom(true, docs);
}
client().admin().indices().prepareUpdateSettings("test").setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, "all")).get();
final int numIters = randomIntBetween(10, 20);
for (int i = 0; i < numIters; i++) {
countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
}
}
/**
* Test that allocates an index on one or more old nodes and then do a rolling upgrade
* one node after another is shut down and restarted from a newer version and we verify
* that all documents are still around after each nodes upgrade.
*/
@Test
public void testIndexRollingUpgrade() throws Exception {
String[] indices = new String[randomIntBetween(1,3)];
for (int i = 0; i < indices.length; i++) {
indices[i] = "test" + i;
assertAcked(prepareCreate(indices[i]).setSettings(ImmutableSettings.builder().put("index.routing.allocation.exclude._name", backwardsCluster().newNodePattern()).put(indexSettings())));
}
int numDocs = randomIntBetween(100, 150);
IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
String[] indexForDoc = new String[docs.length];
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex(indexForDoc[i] = RandomPicks.randomFrom(getRandom(), indices), "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i));
}
indexRandom(true, docs);
for (int i = 0; i < indices.length; i++) {
assertAllShardsOnNodes(indices[i], backwardsCluster().backwardsNodePattern());
}
client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, "none")).get();
backwardsCluster().allowOnAllNodes(indices);
logClusterState();
boolean upgraded;
do {
logClusterState();
CountResponse countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
upgraded = backwardsCluster().upgradeOneNode();
ensureYellow();
countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
for (int i = 0; i < numDocs; i++) {
docs[i] = client().prepareIndex(indexForDoc[i], "type1", String.valueOf(i)).setSource("field1", English.intToEnglish(i));
}
indexRandom(true, docs);
} while (upgraded);
client().admin().indices().prepareUpdateSettings(indices).setSettings(ImmutableSettings.builder().put(EnableAllocationDecider.INDEX_ROUTING_ALLOCATION_ENABLE, "all")).get();
CountResponse countResponse = client().prepareCount().get();
assertHitCount(countResponse, numDocs);
}
}
|
package com.icleveret.recipes.service.impl;
import com.icleveret.recipes.component.SessionHolder;
import com.icleveret.recipes.dao.IngredientDao;
import com.icleveret.recipes.model.Ingredient;
import com.icleveret.recipes.service.IngredientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("ingredientService")
public class IngredientServiceImpl implements IngredientService {
private IngredientDao ingredientDao;
public IngredientDao getIngredientDao() {
return ingredientDao;
}
@Autowired
public void setIngredientDao(IngredientDao ingredientDao) {
this.ingredientDao = ingredientDao;
}
@Override
public Ingredient add(Ingredient ingredient, SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.add(ingredient, sessionContainer);
}
@Override
public Ingredient addMeasure(Ingredient ingredient, SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.addMeasure(ingredient, sessionContainer);
}
@Override
public Ingredient deleteMeasure(Ingredient ingredient, Integer measureId,
SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.deleteMeasure(ingredient, measureId, sessionContainer);
}
@Override
public Ingredient updateName(String name, Integer ingredientId, SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.updateName(name, ingredientId, sessionContainer);
}
@Override
public Ingredient findOne(Integer ingredientId, SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.findOne(ingredientId, sessionContainer);
}
@Override
public Ingredient findByName(String name, SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.findByName(name, sessionContainer);
}
@Override
public List<Ingredient> findAll(SessionHolder.SessionContainer sessionContainer) {
return ingredientDao.findAll(sessionContainer);
}
@Override
public void delete(Ingredient ingredient, SessionHolder.SessionContainer sessionContainer) {
ingredientDao.delete(ingredient, sessionContainer);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pe.gob.onpe.adan.service.Adan;
import java.util.List;
import pe.gob.onpe.adan.model.adan.Local;
/**
*
* @author bvaldez
*/
public interface LocalService {
List<Local> findAllLocalByUbigeo(String ubigeo, String code);
List<Local> findAllLocal();
void saveLocal(Local local);
String disabledLocal(String user, String code);
String enabledLocal(String user, String code);
Local findLocalByCode(String code);
}
|
package nc.model.passive;
import nc.model.PathElement;
/**
* Created by samok on 26.04.2017.
*/
public class PassiveElement implements PathElement {
public PassiveElement(double cost,double delay){
this.cost = cost;
this.delay = delay;
}
private double cost;
private double delay;
public double getDelay() {
return delay;
}
@Override
public double getCost() {
return cost;
}
public String getName() {
return null;
}
@Override
public Integer getID() {
return null;
}
}
|
package com.question.service;
import com.question.model.Selections;
import java.util.List;
public interface SelectionsService {
List<Selections> getSelections(int questionId);
}
|
// This file is a part of Humanoid project.
// Copyright (C) 2020 Aleksander Gajewski <adiog@mindblow.io>.
package io.mindblow.humanoid.canvas.core;
import android.opengl.GLSurfaceView;
import android.support.v7.app.AppCompatActivity;
import io.mindblow.humanoid.context.MasterContext;
public class Canvas {
private GLSurfaceView glSurfaceView;
private AppCompatActivity activity;
public void onCreate(AppCompatActivity activity_, MasterContext masterContext) {
activity = activity_;
glSurfaceView = new SurfaceView(activity, masterContext);
activity.setContentView(glSurfaceView);
}
public void onPause() {
glSurfaceView.onPause();
}
public void onResume() {
glSurfaceView.onResume();
}
public void tick() {
glSurfaceView.requestRender();
}
}
|
package com.spower.basesystem.common.flash;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.regex.Pattern;
/**
* PDF转SWF工具
*
* @date 2013-7-17
* @author manxj
*
*/
public class PDF2SWF {
/**
* pdf文件后缀名
*/
public static final String FILE_NAME_OF_PDF = "pdf";
/**
* swf文件后缀名
*/
public static final String FILE_NAME_OF_SWF = "swf";
private static String projName;
/**
* @param swftoolsPath
* 用于进行把文件转化为swf的工具地址
*/
public PDF2SWF() {
try {
this.projName=FlashCfigUtil.readValue("projName");;
} catch (Exception e) {
System.out.println("flashConfig.properties the swfTools.path is null ");
}
}
/**
* 获得文件的路径
*
* @param file
* 文件的路径 ,如:"c:/test/test.swf"
* @return 文件的路径
*/
public static String getFilePath(String file) {
String result = file.substring(0, file.lastIndexOf("/"));
if (file.substring(2, 3) == "/") {
result = file.substring(0, file.lastIndexOf("/"));
} else if (file.substring(2, 3) == "\\") {
result = file.substring(0, file.lastIndexOf("\\"));
}
return result;
}
/**
* 新建一个目录
*
* @param folderPath
* 新建目录的路径 如:"c:\\newFolder"
*/
public static void newFolder(String folderPath) {
try {
File myFolderPath = new File(folderPath.toString());
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
}
/**
* the exit value of the subprocess represented by this Process object. By
* convention, the value 0 indicates normal termination.
*
* @param sourcePath
* pdf文件路径 ,如:"c:/hello.pdf"
* @param destPath
* swf文件路径,如:"c:/test/test.swf"
* @return 正常情况下返回:0,失败情况返回:1
* @throws IOException
*/
public static int convertPDF2SWF(String sourcePath, String destPath) throws IOException {
// 如果目标文件的路径是新的,则新建路径
newFolder(getFilePath(destPath));
// 源文件不存在则返回
File source = new File(sourcePath);
if (!source.exists()) {
try {
String path=System.getProperty("user.dir");
String filePath=path.substring(0,path.indexOf("\\bin"));
copyFile(filePath+"\\webapps\\"+FlashCfigUtil.readValue("projName")+"\\FlexPaper_2.0.2\\Erro.swf",destPath);
} catch (IOException e) {
}
return 0;
}
// 调用pdf2swf命令进行转换
String command ="";
String osName = System.getProperty("os.name");
if (Pattern.matches("Linux.*", osName)) {
command ="pdf2swf " + sourcePath + " " + destPath + " -s flashversion=9 -s languagedir="+FlashCfigUtil.readValue("xpdf.path");
} else if (Pattern.matches("Windows.*", osName)) {
command =FlashCfigUtil.readValue("swfTools.path")+"/pdf2swf.exe -t \"" + sourcePath + "\" -o \"" + destPath + "\" -s flashversion=9 -s languagedir="+FlashCfigUtil.readValue("xpdf.path");
}
else{
}
System.out.println("命令操作:" + command + "\n开始转换...");
// 调用外部程序
Process process = Runtime.getRuntime().exec(command);
final InputStream is1 = process.getInputStream();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(is1));
try {
while (br.readLine() != null)
;
} catch (IOException e) {
e.printStackTrace();
}
}
}).start(); // 启动单独的线程来清空process.getInputStream()的缓冲区
InputStream is2 = process.getErrorStream();
BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
// 保存输出结果流
StringBuilder buf = new StringBuilder();
String line = null;
while ((line = br2.readLine()) != null)
// 循环等待ffmpeg进程结束
buf.append(line);
while (br2.readLine() != null)
;
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println("转换结束...");
return process.exitValue();
}
/**
* pdf文件转换为swf文件操作
*
* @param sourcePath
* pdf文件路径 ,如:"c:/hello.pdf"
* @param destPath
* swf文件路径,如:"c:/test/test.swf"
*/
public static void pdf2swf(String sourcePath, String destPath) {
long begin_time = new Date().getTime();
try {
PDF2SWF.convertPDF2SWF(sourcePath, destPath);
} catch (Exception ex) {
try {
String path=System.getProperty("user.dir");
String filePath=path.substring(0,path.indexOf("\\bin"));
copyFile(filePath+"\\webapps\\"+FlashCfigUtil.readValue("projName")+"\\FlexPaper_2.0.2\\Erro.swf",destPath);
} catch (IOException e) {
}
System.out.println("转换过程失败!!");
return;
}
long end_time = new Date().getTime();
// File f =new File(sourcePath);
// f.delete();
//System.out.println("转换共耗时 :[" + (end_time - begin_time) + "]ms");
//System.out.println("转换文件成功!!");
}
// public static void main(String[] args) throws IOException {
// String sourcePath = "e:/test." + FILE_NAME_OF_PDF;
// String destPath = "e:/test_1352107155307_" + new Date().getTime() + "." + FILE_NAME_OF_SWF;
// pdf2swf(sourcePath, destPath);
// }
public static void copyFile(String sourceFile, String targetFile) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try {
// 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));
// 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
} finally {
// 关闭流
if (inBuff != null)
inBuff.close();
if (outBuff != null)
outBuff.close();
}
}
}
|
package org.motechproject.server.model;
import org.apache.commons.lang.StringUtils;
import org.motechproject.server.strategy.MessageContentExtractionStrategy;
import org.motechproject.ws.RequestParameterBuilder;
import org.motechproject.ws.SMS;
import java.io.UnsupportedEncodingException;
public class IncomingMessage {
private Long id;
private String text;
private String number;
private String key;
private String code;
private String time;
private static final String AMP = "&";
public IncomingMessage() {
}
public IncomingMessage(SMS sms) {
text = sms.getText();
number = sms.getNumber();
key = sms.getKey();
code = sms.getCode();
time = sms.getTime();
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public Boolean hasSufficientInformation() {
return isNotBlank(key) && isNotBlank(text) && isNotBlank(code);
}
private Boolean isNotBlank(String value) {
return StringUtils.isNotBlank(value);
}
public String extractDateWith(MessageContentExtractionStrategy strategy) {
return strategy.extractDateFrom(time);
}
public String extractPhoneNumberWith(MessageContentExtractionStrategy strategy) {
return strategy.extractPhoneNumberFrom(number);
}
public String extractSenderWith(MessageContentExtractionStrategy strategy) {
return strategy.extractSenderFrom(text);
}
public String extractDescriptionWith(MessageContentExtractionStrategy strategy) {
return strategy.extractDescriptionFrom(text);
}
public String requestParameters() throws UnsupportedEncodingException {
RequestParameterBuilder builder = new RequestParameterBuilder("?", "UTF-8");
builder.append("text", text);
builder.append("number", number);
builder.append("key", key);
builder.append("time", time);
builder.append("code", code);
return builder.toString();
}
@Override
public String toString() {
return "Issue { " + text + " } sent from " + number;
}
public Boolean isFor(String key) {
return key.equalsIgnoreCase(this.key);
}
}
|
package com.baizhi.cmfz_mzw.service;
import com.baizhi.cmfz_mzw.interfaceObj.UserView;
import java.util.Map;
public interface AppService {
Map getFirstPageData(Integer uid, String type, String subType);
Object getSi(Integer uid, Integer id);
Map getWen(Integer uid, Integer id);
Object getLogin(String phone, String password);
Map getRegister(String phone, String password);
Object getModify(UserView user);
Map getIdentifyCode(String phone);
Map checkIdentifyCode(String code, String phone);
Object getUserList(Integer uid);
}
|
package net.jeremiahsmith.recipeapi.controllers;
import lombok.extern.slf4j.Slf4j;
import net.jeremiahsmith.recipeapi.exceptions.RecipeNotFoundException;
import net.jeremiahsmith.recipeapi.models.Recipe;
import net.jeremiahsmith.recipeapi.services.RecipeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Optional;
@RestController
@RequestMapping("/${api.version}/${api.basePath}/recipes")
@Slf4j
public class RecipeController {
private final RecipeService recipeService;
@Autowired
public RecipeController(RecipeService recipeService) {
log.debug("Constructing Recipe Controller");
this.recipeService = recipeService;
}
@GetMapping
public ResponseEntity<?> getRecipes(@RequestParam Optional<String> name) {
log.debug("GET /recipes");
return name.map(s -> new ResponseEntity<>(recipeService.getRecipesByName(s), HttpStatus.OK)).orElseGet(() -> new ResponseEntity<>(recipeService.getRecipes(), HttpStatus.OK));
}
@PostMapping
public ResponseEntity<?> addRecipe(@RequestBody Recipe recipe) {
log.debug("POST /recipes");
if (this.recipeService.addRecipe(recipe)) {
return new ResponseEntity<>(HttpStatus.CREATED);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@GetMapping("/{recipeId}")
public ResponseEntity<?> getRecipeById(@PathVariable Long recipeId) throws RecipeNotFoundException {
log.debug("GET /recipes/{}", recipeId);
Optional<Recipe> recipeOptional = recipeService.getRecipeById(recipeId);
if (recipeOptional.isPresent()) {
log.debug("Recipe Found: {}", recipeOptional.get());
return new ResponseEntity<>(recipeOptional.get(), HttpStatus.OK);
}
else {
log.error("Recipe with id: {} not found", recipeId);
throw new RecipeNotFoundException("Recipe Not Found");
}
}
@DeleteMapping("/{recipeId}")
public ResponseEntity<?> deleteRecipeById(@PathVariable Long recipeId) throws RecipeNotFoundException, Exception {
if(recipeService.getRecipeById(recipeId).isEmpty()) {
log.error("Recipe with id: {} not found", recipeId);
throw new RecipeNotFoundException("Recipe Not Found");
}
if(this.recipeService.deleteRecipe(recipeId)) {
log.debug("Recipe with id: {} deleted", recipeId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
log.error("Unknown Error");
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
@PutMapping("/{recipeId}")
public ResponseEntity<?> putRecipeById(@PathVariable Long recipeId, @RequestBody Recipe recipe) throws RecipeNotFoundException {
if (recipeService.getRecipeById(recipeId).isEmpty()) {
log.error("Recipe with id: {} not found", recipeId);
throw new RecipeNotFoundException("Recipe Not Found");
}
if (recipeService.updateRecipe(recipe).isPresent()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
|
/* Written in 2016 by David Blackman and Sebastiano Vigna (vigna@acm.org)
To the extent possible under law, the author has dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
See <http://creativecommons.org/publicdomain/zero/1.0/>. */
package sarong;
import sarong.util.StringKit;
import java.io.Serializable;
/**
* A modification of Blackman and Vigna's xoroshiro64** generator; behaves like {@link Starfish32RNG}, but is designed
* to make it less likely that users can reduce the quality by simple arithmetic on the result. Lobster (and Starfish)
* are 2-dimensionally equidistributed, so it can return all long values except for one, while Lathe is 1-dimensionally
* equidistributed so it can return all int values but not all longs. Lobster passes all 32TB of PractRand's statistical
* tests, and does so with only one anomaly (considered "unusual") and no failures. In statistical testing,
* xoroshiro128+ always fails some binary matrix rank tests, but that uses a pair of 64-bit states, and when the states
* are reduced to 32-bits, these small-word versions fail other tests as well. Lobster uses a variant on xoroshiro64**
* that reduces some issues with that generator and tries to "harden the defenses" on the generator's quality. Lobster
* does not change xoroshiro's well-tested state transition, but it doesn't base the output on the sum of the two states
* (like xoroshiro128+), instead using the first state only for output (exactly like xoroshiro64** and similar to
* xoshiro256**). Any arithmetic it performs is safe for GWT. Lobster adds an extremely small amount of extra code to
* xoroshiro, running xoroshiro's state transition as normal, using stateA (or s[0] in the original xoroshiro code)
* multiplied by 31 as the initial result, then returning after a somewhat-unusual operation on that initial result that
* isn't common in most RNGs. This last operation is {@code (result << 11) - Integer.rotateLeft(result, 5)}, and this is
* one of a group of similar scrambling operations with varying effects on quality. It is a random reversible mapping, a
* one-to-one operation from int to int, but it seems to be a challenge to actually reverse it without creating a lookup
* table from all int inputs to their outputs. The period is identical to xoroshiro with two 32-bit states, at
* 0xFFFFFFFFFFFFFFFF or 2 to the 64 minus 1. This generator is a little slower than xoroshiro64+ or Lathe, but has
* better distribution than either; it can be contrasted with {@link Starfish32RNG} or {@link XoshiroAra32RNG}, the
* former of which is faster than this and the latter of which has a longer period, but both are fragile if users can
* add integers of their choice.
* <br>
* This avoids an issue in xoroshiro** generators where many multipliers, when applied to the output of a xoroshiro**
* generator, will cause the modified output to rapidly fail binary matrix rank tests. It also is immune to the "attack"
* possible on Starfish and XoshiroAra, where the quality can be wrecked by subtracting a specific number or some number
* similar to it. It's absolutely possible to make a table of inputs to outputs, run the scrambler through that table
* (which would only take seconds, but would use 16GB of RAM), and multiply by the multiplicative inverse of 31 modulo
* 2 to the 32, which would give you half of the state from one full output. It should be clear that this is not a
* cryptographic generator, but I am not claiming this is a rock-solid or all-purpose generator either; if a hostile
* user is trying to subvert a Lobster generator and can access full outputs, they can absolutely do so, but it's much
* less likely that a non-hostile user could accidentally find an issue with this than with Starfish.
* <br>
* The name comes from the sea creature theme I'm using for this family of generators and the hard shell on a lobster.
* <br>
* <a href="http://xoshiro.di.unimi.it/xoroshiro64starstar.c">Original version here for xoroshiro64**</a>.
* <br>
* Written in 2016 by David Blackman and Sebastiano Vigna (vigna@acm.org)
* Ported and modified in 2018 by Tommy Ettinger
* @author Sebastiano Vigna
* @author David Blackman
* @author Tommy Ettinger (if there's a flaw, use SquidLib's or Sarong's issues and don't bother Vigna or Blackman, it's probably a mistake in SquidLib's implementation)
*/
public final class Lobster32RNG implements StatefulRandomness, Serializable {
private static final long serialVersionUID = 1L;
private int stateA, stateB;
/**
* Creates a new generator seeded using two calls to Math.random().
*/
public Lobster32RNG() {
setState((int)((Math.random() * 2.0 - 1.0) * 0x80000000), (int)((Math.random() * 2.0 - 1.0) * 0x80000000));
}
/**
* Constructs this Lathe32RNG by dispersing the bits of seed using {@link #setSeed(int)} across the two parts of state
* this has.
* @param seed an int that won't be used exactly, but will affect both components of state
*/
public Lobster32RNG(final int seed) {
setSeed(seed);
}
/**
* Constructs this Lathe32RNG by splitting the given seed across the two parts of state this has with
* {@link #setState(long)}.
* @param seed a long that will be split across both components of state
*/
public Lobster32RNG(final long seed) {
setState(seed);
}
/**
* Constructs this Lathe32RNG by calling {@link #setState(int, int)} on stateA and stateB as given; see that method
* for the specific details (stateA and stateB are kept as-is unless they are both 0).
* @param stateA the number to use as the first part of the state; this will be 1 instead if both seeds are 0
* @param stateB the number to use as the second part of the state
*/
public Lobster32RNG(final int stateA, final int stateB) {
setState(stateA, stateB);
}
@Override
public final int next(int bits) {
final int s0 = stateA;
final int s1 = stateB ^ s0;
final int result = s0 * 31;
stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); // a, b
stateB = (s1 << 13 | s1 >>> 19); // c
return (result << 11) - (result << 5 | result >>> 27) >>> (32 - bits);
}
/**
* Can return any int, positive or negative, of any size permissible in a 32-bit signed integer.
* @return any int, all 32 bits are random
*/
public final int nextInt() {
final int s0 = stateA;
final int s1 = stateB ^ s0;
final int result = s0 * 31;
stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9); // a, b
stateB = (s1 << 13 | s1 >>> 19); // c
return (result << 11) - (result << 5 | result >>> 27) | 0;
}
@Override
public final long nextLong() {
int s0 = stateA;
int s1 = stateB ^ s0;
final int high = s0 * 31;
s0 = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9);
s1 = (s1 << 13 | s1 >>> 19) ^ s0;
final int low = s0 * 31;
stateA = (s0 << 26 | s0 >>> 6) ^ s1 ^ (s1 << 9);
stateB = (s1 << 13 | s1 >>> 19);
final long result = (high << 11) - (high << 5 | high >>> 27);
return result << 32 ^ ((low << 11) - (low << 5 | low >>> 27));
}
/**
* Produces a copy of this RandomnessSource that, if next() and/or nextLong() are called on this object and the
* copy, both will generate the same sequence of random numbers from the point copy() was called. This just needs to
* copy the state so it isn't shared, usually, and produce a new value with the same exact state.
*
* @return a copy of this RandomnessSource
*/
@Override
public Lobster32RNG copy() {
return new Lobster32RNG(stateA, stateB);
}
/**
* Sets the state of this generator using one int, running it through Zog32RNG's algorithm two times to get
* two ints. If the states would both be 0, state A is assigned 1 instead.
* @param seed the int to use to produce this generator's state
*/
public void setSeed(final int seed) {
int z = seed + 0xC74EAD55 | 0, a = seed ^ z;
a ^= a >>> 14;
z = (z ^ z >>> 10) * 0xA5CB3 | 0;
a ^= a >>> 15;
stateA = (z ^ z >>> 20) + (a ^= a << 13) | 0;
z = seed + 0x8E9D5AAA | 0;
a ^= a >>> 14;
z = (z ^ z >>> 10) * 0xA5CB3 | 0;
a ^= a >>> 15;
stateB = (z ^ z >>> 20) + (a ^ a << 13) | 0;
if((stateA | stateB) == 0)
stateA = 1;
}
public int getStateA()
{
return stateA;
}
/**
* Sets the first part of the state to the given int. As a special case, if the parameter is 0 and stateB is
* already 0, this will set stateA to 1 instead, since both states cannot be 0 at the same time. Usually, you
* should use {@link #setState(int, int)} to set both states at once, but the result will be the same if you call
* setStateA() and then setStateB() or if you call setStateB() and then setStateA().
* @param stateA any int
*/
public void setStateA(int stateA)
{
this.stateA = (stateA | stateB) == 0 ? 1 : stateA;
}
public int getStateB()
{
return stateB;
}
/**
* Sets the second part of the state to the given int. As a special case, if the parameter is 0 and stateA is
* already 0, this will set stateA to 1 and stateB to 0, since both cannot be 0 at the same time. Usually, you
* should use {@link #setState(int, int)} to set both states at once, but the result will be the same if you call
* setStateA() and then setStateB() or if you call setStateB() and then setStateA().
* @param stateB any int
*/
public void setStateB(int stateB)
{
this.stateB = stateB;
if((stateB | stateA) == 0) stateA = 1;
}
/**
* Sets the current internal state of this Lathe32RNG with three ints, where stateA and stateB can each be any int
* unless they are both 0 (which will be treated as if stateA is 1 and stateB is 0).
* @param stateA any int (if stateA and stateB are both 0, this will be treated as 1)
* @param stateB any int
*/
public void setState(int stateA, int stateB)
{
this.stateA = (stateA | stateB) == 0 ? 1 : stateA;
this.stateB = stateB;
}
/**
* Get the current internal state of the StatefulRandomness as a long.
*
* @return the current internal state of this object.
*/
@Override
public long getState() {
return (stateA & 0xFFFFFFFFL) | ((long)stateB) << 32;
}
/**
* Set the current internal state of this StatefulRandomness with a long.
*
* @param state a 64-bit long. You should avoid passing 0; this implementation will treat it as 1.
*/
@Override
public void setState(long state) {
stateA = state == 0 ? 1 : (int)(state & 0xFFFFFFFFL);
stateB = (int)(state >>> 32);
}
@Override
public String toString() {
return "Lobster32RNG with stateA 0x" + StringKit.hex(stateA) + " and stateB 0x" + StringKit.hex(stateB);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Lobster32RNG lobster32RNG = (Lobster32RNG) o;
if (stateA != lobster32RNG.stateA) return false;
return stateB == lobster32RNG.stateB;
}
@Override
public int hashCode() {
return 31 * stateA + stateB | 0;
}
}
|
package cn.stormbirds.expressDelivery.mapper;
import cn.stormbirds.expressDelivery.entity.SysRolePermission;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 权限列表中权限名对应权限表中详细权限关系 Mapper 接口
* </p>
*
* @author stormbirds
* @since 2019-09-09
*/
public interface SysRolePermissionMapper extends BaseMapper<SysRolePermission> {
}
|
package com.tencent.mm.plugin.appbrand.jsapi.d;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.q.f;
import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler;
import com.tencent.mm.plugin.appbrand.widget.input.AppBrandInputInvokeHandler.b;
import java.util.HashMap;
import java.util.Map;
class c$1 implements b {
final /* synthetic */ AppBrandInputInvokeHandler fQH;
final /* synthetic */ c fQI;
c$1(c cVar, AppBrandInputInvokeHandler appBrandInputInvokeHandler) {
this.fQI = cVar;
this.fQH = appBrandInputInvokeHandler;
}
public final void bM(int i, int i2) {
int inputId = this.fQH.getInputId();
p kK = c.kK(inputId);
if (kK != null && kK.isRunning()) {
c$a c_a = new c$a();
Map hashMap = new HashMap();
hashMap.put("height", Integer.valueOf(f.lO(i2)));
hashMap.put("lineCount", Integer.valueOf(i));
hashMap.put("inputId", Integer.valueOf(inputId));
c_a.aC(kK.mAppId, 0).x(hashMap).h(new int[]{kK.hashCode()});
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Vistas;
import Clases.Cl_Conectar;
import Clases.Cl_Proveedor;
import Clases.Cl_Tipo_Documento;
import Clases.Cl_Varios;
import Forms.frm_reg_compra;
import Forms.frm_reg_ingreso;
import Forms.frm_reg_emo;
import Forms.frm_reg_orden_compra;
import Forms.frm_reg_proveedor;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.table.DefaultTableModel;
/**
*
* @author luis-d
*/
public class frm_ver_proveedores extends javax.swing.JInternalFrame {
Cl_Conectar con = new Cl_Conectar();
Cl_Varios ven = new Cl_Varios();
Cl_Proveedor pro = new Cl_Proveedor();
DefaultTableModel mostrar;
public static String funcion = "proveedor";
int i;
/**
* Creates new form frm_ver_proveedores
*/
public frm_ver_proveedores() {
initComponents();
txt_bus.requestFocus();
String query = "select * from proveedor order by raz_soc_pro asc";
ver_proveedor(query);
}
private void ver_proveedor(String query) {
try {
mostrar = new DefaultTableModel() {
@Override
public boolean isCellEditable(int fila, int columna) {
return false;
}
};
Statement st = con.conexion();
ResultSet rs = con.consulta(st, query);
ResultSetMetaData rsMd = rs.getMetaData();
//La cantidad de columnas que tiene la consulta
int cantidadColumnas = rsMd.getColumnCount();
//Establecer como cabezeras el nombre de las colimnas
mostrar.addColumn("RUC");
mostrar.addColumn("Razon Social");
mostrar.addColumn("Telefono");
mostrar.addColumn("Estado");
//Creando las filas para el JTable
while (rs.next()) {
Object[] fila = new Object[4];
fila[0] = rs.getObject("ruc_pro");
fila[1] = rs.getObject("raz_soc_pro");
fila[2] = rs.getObject("tel_pro");
Cl_Tipo_Documento tido = new Cl_Tipo_Documento();
boolean validar_ruc = tido.validar_RUC(rs.getString("ruc_pro"));
// if (rs.getString("est_pro").equals("1")) {
// fila[3] = "ACTIVO";
// } else {
// fila[3] = "-";
// }
if (validar_ruc == true) {
fila[3] = "-";
} else {
fila[3] = "NO VALIDO";
}
mostrar.addRow(fila);
}
con.cerrar(st);
con.cerrar(rs);
t_proveedor.setModel(mostrar);
t_proveedor.getColumnModel().getColumn(0).setPreferredWidth(80);
t_proveedor.getColumnModel().getColumn(1).setPreferredWidth(300);
t_proveedor.getColumnModel().getColumn(2).setPreferredWidth(100);
t_proveedor.getColumnModel().getColumn(3).setPreferredWidth(100);
mostrar.fireTableDataChanged();
} catch (SQLException e) {
System.out.print(e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btn_cer = new javax.swing.JButton();
btn_mod = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
t_proveedor = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
txt_bus = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
setTitle("Ver Proveedor");
btn_cer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/cancel.png"))); // NOI18N
btn_cer.setText("Cerrar");
btn_cer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_cerActionPerformed(evt);
}
});
btn_mod.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/application_edit.png"))); // NOI18N
btn_mod.setText("Modificar");
btn_mod.setEnabled(false);
btn_mod.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_modActionPerformed(evt);
}
});
t_proveedor.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
t_proveedor.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
t_proveedorMouseClicked(evt);
}
public void mousePressed(java.awt.event.MouseEvent evt) {
t_proveedorMousePressed(evt);
}
});
t_proveedor.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
t_proveedorKeyPressed(evt);
}
});
jScrollPane1.setViewportView(t_proveedor);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Recursos/application_add.png"))); // NOI18N
jButton1.setText("Registrar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
txt_bus.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_busKeyPressed(evt);
}
});
jLabel1.setText("Buscar:");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txt_bus, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 287, Short.MAX_VALUE)
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn_mod))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btn_cer)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_bus, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_mod, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 320, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn_cer, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btn_cerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_cerActionPerformed
this.dispose();
}//GEN-LAST:event_btn_cerActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
frm_reg_proveedor proveedor = new frm_reg_proveedor();
ven.llamar_ventana(proveedor);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
private void t_proveedorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_t_proveedorKeyPressed
int i = t_proveedor.getSelectedRow();
if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
txt_bus.setText("");
txt_bus.requestFocus();
}
}//GEN-LAST:event_t_proveedorKeyPressed
private void txt_busKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_busKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
String bus = txt_bus.getText();
String query = "select * from proveedor where ruc_pro like '%" + bus + "%' or "
+ "raz_soc_pro like '%" + bus + "%' order by raz_soc_pro asc";
ver_proveedor(query);
}
}//GEN-LAST:event_txt_busKeyPressed
private void t_proveedorMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_t_proveedorMousePressed
i = t_proveedor.getSelectedRow();
pro.setRuc(t_proveedor.getValueAt(i, 0).toString());
btn_mod.setEnabled(true);
}//GEN-LAST:event_t_proveedorMousePressed
private void btn_modActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_modActionPerformed
frm_reg_proveedor prov = new frm_reg_proveedor();
String ruc = t_proveedor.getValueAt(i, 0).toString();
try {
Statement st = con.conexion();
String edit_pro = "select * from proveedor where ruc_pro = '" + ruc + "'";
ResultSet rs = con.consulta(st, edit_pro);
if (rs.next()) {
prov.txt_ruc.setText(rs.getString("ruc_pro"));
prov.txt_raz.setText(rs.getString("raz_soc_pro"));
prov.txt_dir.setText(rs.getString("dir_pro"));
prov.txt_tel.setText(rs.getString("tel_pro"));
prov.txt_ruc.setEnabled(false);
prov.txt_raz.setEditable(true);
prov.txt_dir.setEditable(true);
prov.txt_tel.setEditable(true);
prov.btn_reg.setEnabled(true);
prov.funcion = "modificar";
ven.llamar_ventana(prov);
this.dispose();
}
} catch (Exception e) {
System.out.println(e);
}
}//GEN-LAST:event_btn_modActionPerformed
private void t_proveedorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_t_proveedorMouseClicked
if (evt.getClickCount() == 2) {
if (funcion.equals("ingreso")) {
frm_reg_ingreso compra = null;
pro.setRuc(t_proveedor.getValueAt(i, 0).toString());
try {
Statement st = con.conexion();
String ver_pro = "select * from proveedor where ruc_pro = '" + pro.getRuc() + "'";
ResultSet rs = con.consulta(st, ver_pro);
if (rs.next()) {
compra.txt_ruc.setText(pro.getRuc());
compra.txt_raz.setText(rs.getString("raz_soc_pro"));
compra.cbx_tido.setEnabled(true);
compra.cbx_tido.requestFocus();
this.dispose();
}
} catch (SQLException ex) {
System.out.print(ex);
}
funcion = "proveedor";
}
if (funcion.equals("compra")) {
frm_reg_compra compra = null;
pro.setRuc(t_proveedor.getValueAt(i, 0).toString());
try {
Statement st = con.conexion();
String ver_pro = "select * from proveedor where ruc_pro = '" + pro.getRuc() + "'";
ResultSet rs = con.consulta(st, ver_pro);
if (rs.next()) {
compra.txt_ruc.setText(pro.getRuc());
compra.txt_raz.setText(rs.getString("raz_soc_pro"));
compra.cbx_tido.setEnabled(true);
compra.cbx_tido.requestFocus();
this.dispose();
}
} catch (SQLException ex) {
System.out.print(ex);
}
funcion = "proveedor";
}
if (funcion.equals("emo")) {
frm_reg_emo emo = null;
pro.setRuc(t_proveedor.getValueAt(i, 0).toString());
try {
Statement st = con.conexion();
String ver_pro = "select * from Proveedor where ruc_pro = '" + pro.getRuc() + "'";
ResultSet rs = con.consulta(st, ver_pro);
if (rs.next()) {
emo.txt_ruc.setText(pro.getRuc());
emo.txt_raz.setText(rs.getString("raz_soc_pro"));
emo.txt_fec.setEditable(true);
emo.txt_fec.requestFocus();
this.dispose();
}
} catch (SQLException ex) {
System.out.print(ex);
}
funcion = "proveedor";
}
if (funcion.equals("orden_compra")) {
frm_reg_orden_compra orden_compra = null;
pro.setRuc(t_proveedor.getValueAt(i, 0).toString());
try {
Statement st = con.conexion();
String ver_pro = "select * from proveedor where ruc_pro = '" + pro.getRuc() + "'";
ResultSet rs = con.consulta(st, ver_pro);
if (rs.next()) {
orden_compra.txt_ruc.setText(pro.getRuc());
orden_compra.txt_raz_soc.setText(rs.getString("raz_soc_pro"));
orden_compra.txt_contacto.setEnabled(true);
orden_compra.txt_contacto.requestFocus();
this.dispose();
}
} catch (SQLException ex) {
System.out.print(ex);
}
funcion = "proveedor";
}
}
}//GEN-LAST:event_t_proveedorMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_cer;
private javax.swing.JButton btn_mod;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable t_proveedor;
private javax.swing.JTextField txt_bus;
// End of variables declaration//GEN-END:variables
}
|
package com.pia.workshop.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pia.workshop.dto.UserDTO;
import com.pia.workshop.model.User;
import com.pia.workshop.service.UserService;
@RestController
@Validated
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@PostMapping("/add-user")
public User addUser(@Valid@RequestBody UserDTO userDTO) {
return userService.addUser(userDTO);
}
@GetMapping("/get-user/{name}")
public List<User> getUsers(@PathVariable("name") String name){
return userService.getUsersByName(name);
}
}
|
package com.bit.myfood.controller.api;
import com.bit.myfood.controller.CrudController;
import com.bit.myfood.model.entity.Category;
import com.bit.myfood.model.network.request.CategoryApiRequest;
import com.bit.myfood.model.network.response.CategoryApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/api/category")
public class CategoryApiController extends CrudController<CategoryApiRequest, CategoryApiResponse, Category> {
}
|
package id.ac.um.produkskripsi;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
public class MainActivity extends AppCompatActivity {
CardView materi1, materi2, materi3, fitur;
Intent temp;
Bundle materi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
materi1 = findViewById(R.id.menu1);
materi2 = findViewById(R.id.menu2);
materi3 = findViewById(R.id.menu3);
fitur = findViewById(R.id.menu4);
materi = new Bundle();
final String a="satu";
final String b="dua";
final String c="tiga";
materi1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
temp = new Intent(MainActivity.this, CitraBitmap.class);
temp.putExtra(CitraBitmap.KEYMENU1,a);
startActivity(temp);
}
});
materi2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
temp= new Intent(MainActivity.this, CitraBitmap.class);
temp.putExtra(CitraBitmap.KEYMENU1,b);
startActivity(temp);
}
});
materi3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
temp = new Intent(getApplicationContext(),CitraBitmap.class);
startActivity(temp);
}
});
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Yakin ingin keluar?")
.setCancelable(false)
.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MainActivity.this.finish();
}
})
.setNegativeButton("Tidak",null)
.show();
}
}
|
/*
* Copyright © 2018 tesshu.com (webmaster@tesshu.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tesshu.sonic.player.plugin.view;
import com.tesshu.sonic.player.view.ICustomContainer;
import com.tesshu.sonic.player.view.annotation.StarIndicator;
import java.util.Optional;
import org.checkerframework.checker.nullness.qual.NonNull;
public interface ViewSupplier {
@NonNull
String getName();
@NonNull
ICustomContainer createContainer();
Optional<StarIndicator> getStarIndicator();
}
|
package de.raidcraft.skillsandeffects.pvp.skills.healing;
import com.sk89q.minecraft.util.commands.CommandContext;
import de.raidcraft.skills.api.combat.EffectType;
import de.raidcraft.skills.api.combat.action.HealAction;
import de.raidcraft.skills.api.exceptions.CombatException;
import de.raidcraft.skills.api.hero.Hero;
import de.raidcraft.skills.api.persistance.SkillProperties;
import de.raidcraft.skills.api.profession.Profession;
import de.raidcraft.skills.api.resource.Resource;
import de.raidcraft.skills.api.skill.AbstractSkill;
import de.raidcraft.skills.api.skill.SkillInformation;
import de.raidcraft.skills.api.trigger.CommandTriggered;
import de.raidcraft.skills.tables.THeroSkill;
import de.raidcraft.skills.util.ConfigUtil;
import org.bukkit.configuration.ConfigurationSection;
/**
* @author Silthus
*/
@SkillInformation(
name = "Bloodthirst",
description = "Heilt dich basierend auf der Menge deiner Wut.",
types = {EffectType.HEALING, EffectType.HELPFUL, EffectType.MAGICAL}
)
public class BloodThirst extends AbstractSkill implements CommandTriggered {
private String resourceName = "rage";
private double healFactor = 1.0;
private double minCost = 20;
public BloodThirst(Hero hero, SkillProperties data, Profession profession, THeroSkill database) {
super(hero, data, profession, database);
}
@Override
public void load(ConfigurationSection data) {
resourceName = data.getString("resource");
healFactor = ConfigUtil.getTotalValue(this, data.getConfigurationSection("heal"));
minCost = ConfigUtil.getTotalValue(this, data.getConfigurationSection("min"));
}
@Override
public void runCommand(CommandContext args) throws CombatException {
Resource resource = getHolder().getResource(resourceName);
if (resource.getCurrent() >= minCost) {
new HealAction<>(this, getHolder(), (int) (resource.getCurrent() * healFactor)).run();
resource.setCurrent(resource.getDefault());
} else {
throw new CombatException("Nicht genug " + resource.getFriendlyName() + ".");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.