text
stringlengths 10
2.72M
|
|---|
package com.auth.extensions.userregistration;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.keycloak.Config;
import org.keycloak.events.EventListenerProvider;
import org.keycloak.models.KeycloakSession;
import java.net.URI;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class StoreEventListenerProviderFactoryTest {
@Rule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables();
private StoreEventListenerProviderFactory storeEventListenerProviderFactory = new StoreEventListenerProviderFactory();
@Before
public void init(){
environmentVariables.set("APPLICATION_URL", "http://test");
storeEventListenerProviderFactory.init(mock(Config.Scope.class));
}
@Test
public void testCreation() {
EventListenerProvider eventListenerProvider = storeEventListenerProviderFactory.create(mock(KeycloakSession.class));
assertThat(eventListenerProvider).isNotNull();
assertThat(eventListenerProvider).extracting("storeClient").isEqualTo(new StoreClient(URI.create("http://test/api/v1/users")));
}
@Test
public void testInvalidCreation() {
environmentVariables.set("APPLICATION_URL", null);
assertThatThrownBy(() -> {storeEventListenerProviderFactory.init(mock(Config.Scope.class));}).isInstanceOf(NullPointerException.class);
}
@Test
public void testId(){
assertThat(storeEventListenerProviderFactory.getId()).isEqualTo("store-user-registration-listener");
}
}
|
package com.github.vinja.util;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class UserLibConfig {
private static Map<String,List<String>> usrLibCache=new HashMap<String,List<String>>();
public static List<String> getUsrLibArchives(String name) {
return usrLibCache.get(name);
}
public static void init(String xmlPath){
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(new File(xmlPath));
Element docEle = dom.getDocumentElement();
NodeList libNodeList = docEle.getElementsByTagName("library");
if(libNodeList != null && libNodeList.getLength() > 0) {
for(int i = 0 ; i < libNodeList.getLength();i++) {
Element libNode = (Element)libNodeList.item(i);
String libName = libNode.getAttribute("name");
NodeList archiveNodeList = libNode.getElementsByTagName("archive");
if(archiveNodeList != null && archiveNodeList.getLength() > 0) {
List<String> urls =new ArrayList<String>();
for(int j = 0 ; j < archiveNodeList.getLength();j++) {
Element arvhiveNode = (Element)archiveNodeList.item(j);
urls.add(arvhiveNode.getAttribute("path"));
}
usrLibCache.put(libName, urls);
}
}
}
}catch(Exception e) {
}
}
}
|
package com.cg.project.castleglobalproject.search.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.cg.project.castleglobalproject.R;
import com.cg.project.castleglobalproject.base.fragments.BaseFragment;
import com.cg.project.castleglobalproject.search.adapters.CuisineTypeAdapter;
import com.cg.project.castleglobalproject.search.adapters.RestaurantAdapter;
import com.cg.project.castleglobalproject.search.network.pojo.Restaurant;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
public class SearchResultFragment extends BaseFragment implements View.OnClickListener, CuisineTypeAdapter.CuisineTypeListener{
private static final String ARG = "arg";
TextView mCuisineTypesSelected;
View mCuisineTypesSelector;
RecyclerView mCuisineTypesRV;
CuisineTypeAdapter mCuisineTypeAdapter;
TreeSet<String> availableCuisines;
TreeSet<String> selectedCuisines;
Map<String, List<Restaurant>> results;
FloatingActionMenu mSortButton;
FloatingActionButton mSortByPrice, mSortByRating;
RecyclerView mRestaurantRV;
RestaurantAdapter mRestaurantAdapter;
public static Fragment newInstance(HashMap<String, List<Restaurant>> results) {
Fragment fragment = new SearchResultFragment();
Bundle args = new Bundle();
args.putSerializable(ARG, results);
fragment.setArguments(args);
return fragment;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context != null) {
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
if(args.getSerializable(ARG) != null)
results = (HashMap<String,List<Restaurant>>) args.getSerializable(ARG);
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_search_result, container, false);
mCuisineTypesSelected = mRootView.findViewById(R.id.cuisine_types_selected);
mCuisineTypesSelector = mRootView.findViewById(R.id.cuisine_types_selector);
mCuisineTypesRV = mRootView.findViewById(R.id.cuisine_types_RV);
mRestaurantRV = mRootView.findViewById(R.id.restaurant_RV);
mSortButton = mRootView.findViewById(R.id.sort);
mSortByPrice = mRootView.findViewById(R.id.sort_price);
mSortByRating = mRootView.findViewById(R.id.sort_rating);
return mRootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
mCuisineTypesSelector.setOnClickListener(this);
mRootView.findViewById(R.id.change_cuisine).setOnClickListener(this);
mRootView.findViewById(R.id.ok_button).setOnClickListener(this);
mSortByPrice.setOnClickListener(this);
mSortByRating.setOnClickListener(this);
availableCuisines = new TreeSet<>();
selectedCuisines = new TreeSet<>();
RecyclerView.LayoutManager lm = new LinearLayoutManager(getContext());
mCuisineTypeAdapter = new CuisineTypeAdapter(getContext(), this,
availableCuisines, selectedCuisines);
mCuisineTypesRV.setLayoutManager(lm);
mCuisineTypesRV.setAdapter(mCuisineTypeAdapter);
RecyclerView.LayoutManager lm1 = new LinearLayoutManager(getContext());
mRestaurantAdapter = new RestaurantAdapter(getContext(), new ArrayList<Restaurant>());
mRestaurantRV.setLayoutManager(lm1);
mRestaurantRV.setAdapter(mRestaurantAdapter);
processData();
displayResults();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.change_cuisine:
if (mCuisineTypesSelector.getVisibility() == View.VISIBLE) {
mCuisineTypesSelector.setVisibility(View.GONE);
} else {
mCuisineTypesSelector.setVisibility(View.VISIBLE);
}
break;
case R.id.ok_button:
/// TODO this
mCuisineTypesSelector.setVisibility(View.GONE);
displayResults();
break;
case R.id.sort_price:
mRestaurantAdapter.sort(RestaurantAdapter.PRICE);
mSortButton.close(true);
break;
case R.id.sort_rating:
mRestaurantAdapter.sort(RestaurantAdapter.RATING);
mSortButton.close(true);
break;
default:
break;
}
}
public void displayResults () {
TreeSet<String > selectedCuisines = this.selectedCuisines != null ? this.selectedCuisines
: this.availableCuisines;
mCuisineTypeAdapter.addAll(availableCuisines, selectedCuisines);
HashSet<Restaurant> restaurants = new HashSet<>();
StringBuilder builder = new StringBuilder("");
for (String cuisine : selectedCuisines) {
builder.append(cuisine + ", ");
restaurants.addAll(results.get(cuisine));
}
if (builder.length() >= 2) {
builder.deleteCharAt(builder.length() - 1);
builder.deleteCharAt(builder.length() - 1);
}
mCuisineTypesSelected.setText(builder.toString());
mRestaurantAdapter.addAll(restaurants);
}
@Override
public void onResume() {
super.onResume();
if (mBaseListener != null) {
mBaseListener.setActionBarTitle("Results");
}
}
public void processSearchResult(HashMap<String, List<Restaurant>> results) {
// HashMap<String, List<Restaurant>> results = new HashMap<>();
// for (Restaurant result : data.restaurants) {
// String[] cuisines = result.restaurant.cuisines.split(", ");
// for (String cuisine : cuisines) {
// List<Restaurant> restaurants = results.get(cuisine);
// if (restaurants == null) {
// restaurants = new ArrayList<>();
// }
// restaurants.add(result);
// results.put(cuisine, restaurants);
// }
// }
this.results = results;
processData();
displayResults();
}
public void processData() {
availableCuisines.clear();
selectedCuisines.clear();
if (availableCuisines == null) {
availableCuisines = new TreeSet<>();
}
if (selectedCuisines == null) {
selectedCuisines = new TreeSet<>();
}
for (String cuisine : results.keySet()) {
availableCuisines.add(cuisine);
selectedCuisines.add(cuisine);
}
}
@Override
public void onCuisineSelected(String cusine) {
if (selectedCuisines != null) {
selectedCuisines.add(cusine);
}
}
@Override
public void onCuisineUnselected(String cuisine) {
if (selectedCuisines != null) {
selectedCuisines.remove(cuisine);
}
}
}
|
package monde.vivant.animal.oiseau;
public class Kiwi
{
}
|
package com.simple_dao.entity;
public class Car {
private int id;
private String mark;
private String model;
private int price;
public Car(String mark, String model, int price) {
this.mark = mark;
this.model = model;
this.price = price;
}
public Car() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Car{" +
"id=" + id +
", mark='" + mark + '\'' +
", model='" + model + '\'' +
", price=" + price +
'}';
}
}
|
package com.tencent.mm.plugin.wenote.ui.nativenote.voiceview;
import com.tencent.mm.ab.g;
import com.tencent.mm.ab.g.b;
import com.tencent.mm.ab.h;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.sdk.platformtools.SensorController;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.af;
import com.tencent.mm.sdk.platformtools.az;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.LinkedList;
import java.util.List;
public class a implements com.tencent.mm.ab.g.a, b, com.tencent.mm.sdk.platformtools.SensorController.a {
public static volatile a qwc = null;
private int bOS;
public List<a> cWy = new LinkedList();
public SensorController hlW;
private boolean hlZ = true;
public az hma;
private long hmb = -1;
private boolean hmc;
private boolean hmg = false;
private g iWF = ((h) com.tencent.mm.kernel.g.l(h.class)).vm();
String path;
private a() {
au.HU();
Boolean bool = (Boolean) c.DT().get(26, Boolean.valueOf(false));
this.hmc = bool.booleanValue();
this.hlZ = !bool.booleanValue();
if (this.iWF != null) {
this.iWF.a(this);
this.iWF.a(this);
this.iWF.aK(this.hlZ);
} else {
x.w("MicroMsg.RecordVoiceHelper", "get voice player fail, it is null");
}
if (this.hlW == null) {
this.hlW = new SensorController(ad.getContext());
}
if (this.hma == null) {
this.hma = new az(ad.getContext());
}
}
public static a cbb() {
if (qwc == null) {
synchronized (a.class) {
if (qwc == null) {
qwc = new a();
}
}
}
return qwc;
}
public final boolean startPlay(String str, int i) {
if (this.iWF == null) {
x.w("MicroMsg.RecordVoiceHelper", "start play error, path %s, voiceType %d, player is null", new Object[]{str, Integer.valueOf(i)});
return false;
}
this.iWF.stop();
if (!(this.hlW == null || this.hlW.sIY)) {
this.hlW.a(this);
if (this.hma.Q(new 1(this))) {
this.hmb = 0;
} else {
this.hmb = -1;
}
}
this.path = str;
this.bOS = i;
if (bi.oW(str) || !this.iWF.a(str, this.hlZ, true, i)) {
return false;
}
af.Wp("keep_app_silent");
for (a aVar : this.cWy) {
if (aVar != null) {
aVar.Sw(str);
}
}
return true;
}
public final void stopPlay() {
x.i("MicroMsg.RecordVoiceHelper", "stop play");
af.Wq("keep_app_silent");
if (this.iWF != null) {
this.iWF.stop();
for (a aVar : this.cWy) {
if (aVar != null) {
aVar.cba();
}
}
}
if (this.hlW != null) {
this.hlW.ciL();
}
if (this.hma != null) {
this.hma.ciM();
}
}
public final boolean aLq() {
if (this.iWF != null) {
return this.iWF.isPlaying();
}
x.w("MicroMsg.RecordVoiceHelper", "check is play, but player is null");
return false;
}
public final void onError() {
x.d("MicroMsg.RecordVoiceHelper", "on error, do stop play");
stopPlay();
}
public final void wd() {
x.d("MicroMsg.RecordVoiceHelper", "on completion, do stop play");
stopPlay();
}
public final void dK(boolean z) {
boolean z2 = true;
if (!bi.oW(this.path)) {
if (this.hmg) {
if (z) {
z2 = false;
}
this.hmg = z2;
} else if (z || this.hmb == -1 || bi.bI(this.hmb) <= 400) {
this.hmg = false;
if (this.iWF != null && this.iWF.vZ()) {
return;
}
if (this.hmc) {
if (this.iWF != null) {
this.iWF.aK(false);
}
this.hlZ = false;
} else if (this.iWF == null || this.iWF.isPlaying()) {
if (this.iWF != null) {
this.iWF.aK(z);
}
this.hlZ = z;
if (!z) {
startPlay(this.path, this.bOS);
}
} else {
this.iWF.aK(true);
this.hlZ = true;
}
} else {
this.hmg = true;
}
}
}
}
|
package io.github.flpmartins88.basico;
import org.h2.Driver;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtils {
private static SessionFactory sessionFactory;
static {
Configuration c = new Configuration();
c.addAnnotatedClass(Pessoa.class);
c.addPackage(Pessoa.class.getPackage().getName());
c.setProperty(AvailableSettings.DIALECT, "org.hibernate.dialect.H2Dialect");
c.setProperty(AvailableSettings.DRIVER, "org.h2.Driver");
c.setProperty(AvailableSettings.USER, "sa");
c.setProperty(AvailableSettings.PASS, "");
c.setProperty(AvailableSettings.URL, "jdbc:h2:mem:banco");
c.setProperty(AvailableSettings.HBM2DDL_AUTO, "create");
c.setProperty(AvailableSettings.SHOW_SQL, "true");
c.setProperty(AvailableSettings.FORMAT_SQL, "true");
c.setProperty(AvailableSettings.GENERATE_STATISTICS, "true");
ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(c.getProperties()).build();
sessionFactory = c.buildSessionFactory(registry);
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
|
/*
* 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 swingtodo;
import com.TodoPojo.Todo;
import com.dao.TodoDao;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Bhatti
*/
public class ViewTodo extends JFrame implements ActionListener {
JButton back;
JTable table;
DefaultTableModel dtm;
public ViewTodo()throws Exception{
this.setBounds(0, 0, 900, 600);
this.setDefaultCloseOperation(3);
this.setLayout(new BorderLayout());
back =new JButton("Back");
back.setFont(new Font("lato", Font.BOLD, 30));
back.setBounds(100, 480, 200, 70);
back.setBackground(new Color(252, 65, 54));
back.setForeground(Color.white);
String t_head[] = {"Id", "T_name", "T_description", "Time", "Status"};
dtm = new DefaultTableModel(t_head, 0);
List<Todo> todolist=TodoDao.select();
for(Todo o:todolist)
{
SimpleDateFormat sdf=new SimpleDateFormat("yy/mm/dd hh:mm:ss");
String date=sdf.format(o.getTime());
String data[]={""+o.getId(),o.getName(),o.getDescription(),date,o.getStatus()};
dtm.addRow(data);
}
table = new JTable(dtm);
// setting table header decoration
table.getTableHeader().setOpaque(false);
table.getTableHeader().setBackground(new Color(32, 136, 203));
table.getTableHeader().setForeground(new Color(255, 255, 255));
table.setRowHeight(30);
// table body decoration
table.setRowHeight(35);
table.getTableHeader().setFont(new Font("Segoe", Font.BOLD, 14));
table.setFont(new Font("poppins", Font.BOLD, 14));
JScrollPane jsp = new JScrollPane(table);
this.add(jsp, BorderLayout.CENTER);
this.add(back, BorderLayout.SOUTH);
this.setVisible(true);
back.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==back)
{
this.setVisible(false);
new Home();
}
}
}
|
package zx.soft.restlet_demo;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import org.json.JSONObject;
import org.restlet.Server;
import org.restlet.data.Form;
import org.restlet.data.Protocol;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
import redis.clients.jedis.Jedis;
public class GetPostedDataAndWriteIntoRedis extends ServerResource {
private static Jedis jedis;
private static String lt; //redis queue名称
public static void main(final String[] args) throws Exception {
jedis = new Jedis("localhost", 6379);
jedis.flushAll();
lt = "queue";
// Create the HTTP server and listen on port 8182
new Server(Protocol.HTTP, 8182, GetPostedDataAndWriteIntoRedis.class).start();
}
@Override
@Get
public Representation get() {
Form form = getRequest().getResourceRef().getQueryAsForm(); //获取查询参数
String sentence = form.getFirstValue("sentence"); //获取key=movie的参数值
getResponse().setStatus(Status.SUCCESS_OK);
return new StringRepresentation("*** Get Method in ServerResource\n" + "Parameter sentence: " + sentence);
}
@Post
public Representation post(String parameters) {
getResponse().setStatus(Status.SUCCESS_OK);
try {
//解析curl提交过来的json数据
JSONObject obj = new JSONObject(parameters);
Iterator it = obj.keys();
parameters = "";
String key = "";
String value = "";
while (it.hasNext()) {
key = (String) it.next();
value = obj.getString(key);
parameters += key + ":" + value + "\n";
// 将Post过来的text写进redis
if (key.equals("text")) {
// System.out.println("text:" + value);
jedis.lpush(lt, value);
}
}
return new StringRepresentation("*** Post Method in ServerResource-json\n" + parameters);
} catch (Exception e) {
//处理程序中模拟post提交form表单数据
getResponse().setStatus(Status.SUCCESS_OK);
//解析json数据
try {
parameters = URLDecoder.decode(parameters, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
String parapairs[] = parameters.split("&");
String key = "";
for (String parapair : parapairs) {
key = parapair.split("=")[0];
if (key.equals("text")) {
jedis.lpush(lt, parapair.split("=")[1]);
// System.out.println("text:" + jedis.rpop(lt));
}
}
return new StringRepresentation("*** Post Method in ServerResource-form\n" + parameters);
}
}
}
|
package kr.co.sist.user.faq.vo;
/**
* 사용자 - 문의사항 등록시 사용되는 클래스
* @author sist37
*/
public class ReqAddVO {
private String reqType;
private String reqTitle;
private String reqContent;
private String userId;
public ReqAddVO() {
}
public ReqAddVO(String userId, String reqType, String reqTitle, String reqContent) {
this.reqType = reqType;
this.reqTitle = reqTitle;
this.reqContent = reqContent;
this.userId = userId;
}
public String getReqType() {
return reqType;
}
public void setReqType(String reqType) {
this.reqType = reqType;
}
public String getReqTitle() {
return reqTitle;
}
public void setReqTitle(String reqTitle) {
this.reqTitle = reqTitle;
}
public String getReqContent() {
return reqContent;
}
public void setReqContent(String reqContent) {
this.reqContent = reqContent;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
|
package lp2.lerDados;
/**
* Classe que define um estabelecimento.
*
* @author Flavia Gangorra<br>
* Irvile Rodrigues Lavor<br>
* Jordao Ezequiel Serafim de Araujo<br>
*/
public class Estabelecimento implements Comparable<Estabelecimento> {
private String nome;
private String localizacao;
private String tipoDeComida;
private int nota;
/**
* Metodo que instancia um objeto da classe Estabelecimento que eh responsavel
* por guardar informacoes sobre um determinado restaurante como seu nome, localizacao e tipo de refeicao servida.
*
* @param nome
* nome do estabelecimento.
* @param localizacao
* localizacao do estabelecimento.
* @param tipoDeComida
* tipo de comida servida.
* @throws Exception
* caso algun dos parametros passados seja null.
*/
public Estabelecimento(String nome, String localizacao, String tipoDeComida) throws Exception {
if(nome == null || nome.equals(""))
throw new Exception("Nome nulo/vazio.");
if(localizacao == null || localizacao.equals(""))
throw new Exception("Localizacao nula/vazia.");
if(tipoDeComida == null || tipoDeComida.equals(""))
throw new Exception("Tipo de comida nulo/vazio.");
this.nome = nome;
this.localizacao = localizacao;
this.tipoDeComida = tipoDeComida;
}
/**
* Retorna o nome do estabelecimento.
* @return
* o nome do estabelecimento.
*/
public String getNome() {
return nome;
}
/**
* Modifica o nome atual do estabelecimento.
* @param nome
* novo nome do estabelecimento.
* @throws Exception
* caso o novo nome passado seja igual a null.
*/
public void setNome(String nome) throws Exception {
if(nome == null || nome.equals(""))
throw new Exception("Nome nulo/vazio.");
this.nome = nome;
}
/**
* Retorna a localizacao do estabelecimento.
* @return
* a localizacao do estabelecimento.
*/
public String getLocalizacao() {
return localizacao;
}
/**
* Modifica a localizacao atual do estabelecimento.
* @param localizacao
* a nova localizacao do estabelecimento.
* @throws Exception
* caso a nova localizao seja igual a null.
*/
public void setLocalizacao(String localizacao) throws Exception {
if(localizacao == null || localizacao.equals(""))
throw new Exception("Localizacao nula/vazia.");
this.localizacao = localizacao;
}
/**
* Retorna o tipo de refeicao servido no estabelecimento.
* @return
* o tipo de refeicao servido no estabelecimento.
*/
public String getTipoDeComida() {
return tipoDeComida;
}
/**
* Modifica o tipo de refeicao servido no estabelecimento.
* @param tipoDeComida
* novo tipo de refeicao servido no estabelecimeto.
* @throws Exception
* caso o novo tipo de refeicao passado seja igual a null.
*/
public void setTipoDeComida(String tipoDeComida) throws Exception {
if(tipoDeComida == null || tipoDeComida.equals(""))
throw new Exception("Tipo de comida nulo/vazio.");
this.tipoDeComida = tipoDeComida;
}
/**
* Retorna a nota do estabelecimento.
* @return
* a nota do estabelecimento.
*/
public int getNota() {
return nota;
}
/**
* Modifica a nota atual do estabelecimeto.
* @param nota
* a nota atual do estabelecimeto.
*/
public void setNota(int nota) {
this.nota = nota;
}
/**
* Compara se dois estabelecimentos sao iguais mediante a comparacao de suas notas.
*/
@Override
public int compareTo(Estabelecimento o) {
return this.getNota() - o.getNota();
}
/**
* Compara dois estabelecimentos pelos nomes. Utilizado para ordenacao dos
* estabelecimentos em ordem alfabetica.
*
* @param outro
* O outro estabelecimentos.
* @return Um inteiro representando o nome que vem antes ou depois.
*/
public int comparePorNome(Estabelecimento outro){
return this.getNome().compareTo(outro.getNome());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((localizacao == null) ? 0 : localizacao.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
result = prime * result + nota;
result = prime * result
+ ((tipoDeComida == null) ? 0 : tipoDeComida.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Estabelecimento))
return false;
Estabelecimento estabelecimento = (Estabelecimento) obj;
if (this.getNome().equals(estabelecimento.getNome())
&& this.getLocalizacao().equals(
estabelecimento.getLocalizacao())
&& this.getTipoDeComida().equals(
estabelecimento.getTipoDeComida())
&& this.getNota() == estabelecimento.getNota())
return true;
return false;
}
@Override
public String toString(){
return getNome() + ", " + getLocalizacao() + "," + getTipoDeComida();
}
}
|
//package com.example.demo.error;
//
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.http.HttpStatus;
//
///**
// * 描述:自定义错误页面
// * @author Ay
// * @date 2017/12/02
// */
//@Configuration
//public class ErrorPageConfig {
//
// @Bean
// public EmbeddedServletContainerCustomizer containerCustomizer() {
//
// return new EmbeddedServletContainerCustomizer() {
// @Override
// public void customize(ConfigurableEmbeddedServletContainer container) {
// ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
// container.addErrorPages(error404Page);
// }
// };
// }
//
//}
|
package uz.kassa.test.exception;
public class CurrencyInfoNotFoundException extends RuntimeException {
public CurrencyInfoNotFoundException(String message) {
super(message);
}
public CurrencyInfoNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
|
package com.icehousecorp.jsonapi;
import com.icehousecorp.jsonapi.constant.JSONAPIMemberKey;
import com.icehousecorp.jsonapi.constant.JSONAPIResourceKey;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.util.Iterator;
/**
* Created by imrenagi on 2/13/15.
*/
public class JSONAPILinks {
private final static String EMPTY_STRING = "";
private JSONObject links;
/**
* @param key
* @return true if key is "links"
*/
public static boolean isLinks(String key) {
return key.equals(JSONAPIMemberKey.LINKS_MEMBER);
}
/**
* Default Constructor
*
* @param jsonObject raw JSON API Object
* @throws JSONException
*/
public JSONAPILinks(JSONObject jsonObject) throws JSONException {
try {
links = jsonObject.getJSONObject(JSONAPIMemberKey.LINKS_MEMBER);
} catch (JSONException e) {
JSONException exception = new JSONException(
"Can not find links key or Links should be type of JSONObject");
exception.setStackTrace(e.getStackTrace());
throw exception;
}
}
/**
* @param resourceObject
* @param linksKey
* @return the type of a resource object.
*/
public String getType(Object resourceObject, String linksKey) {
String type;
if (resourceObject instanceof JSONObject) {
type = getResourceTypeForJSONObject((JSONObject) resourceObject, linksKey);
} else {
type = getResourceTypeFromLinksMember(linksKey);
}
if (type.equals(EMPTY_STRING)) {
return linksKey;
} else {
return type;
}
}
/**
* @param keyword
* @return linked type of a resource object
*/
private String getResourceTypeFromLinksMember(String keyword) {
Iterator<String> iterator = links.keys();
while (iterator.hasNext()) {
String key = iterator.next();
if (key.contains(keyword)) {
try {
return ((JSONObject) links.get(key)).getString(JSONAPIResourceKey.TYPE_KEY);
} catch (JSONException e) {
return EMPTY_STRING;
}
}
}
return EMPTY_STRING;
}
private String getResourceTypeForJSONObject(JSONObject resourceObject, String key) {
String typeFromLinksMember = getResourceTypeFromLinksMember(key);
String typeFromResourceObject = getResourceTypeFromResourceObject(resourceObject);
if (typeFromLinksMember.equals(EMPTY_STRING)) {
return typeFromResourceObject.equals(EMPTY_STRING) ? key : typeFromResourceObject;
} else {
return typeFromLinksMember;
}
}
/**
* @param resourceObject
* @return type of a resource object in String if the type is specified in the resource object
*/
private String getResourceTypeFromResourceObject(JSONObject resourceObject) {
try {
return resourceObject.getString(JSONAPIResourceKey.TYPE_KEY);
} catch (JSONException e) {
return EMPTY_STRING;
}
}
/**
* @param resourceObject resource resourceObject class
* @param linksKey
* @return
*/
public String getURLTemplate(Object resourceObject, String linksKey) {
String type;
if (resourceObject instanceof JSONObject) {
type = getURLTemplateForJSONObject((JSONObject) resourceObject, linksKey);
} else {
type = getURLTemplateFromLinksMember(linksKey);
}
return type;
}
private String getURLTemplateForJSONObject(JSONObject resourceObject, String key) {
String hrefFromLinksMember = getURLTemplateFromLinksMember(key);
String hrefFromResourceObject = getURLTemplateFromResourceObject(resourceObject);
if (hrefFromLinksMember == null) {
return hrefFromResourceObject;
} else {
return hrefFromLinksMember;
}
}
/**
* Get URL Template/href link for a resource object specified in href field within itself.
*
* @param resourceObject
* @return URL Template / href links
*/
private String getURLTemplateFromResourceObject(JSONObject resourceObject) {
try {
return resourceObject.getString(JSONAPIResourceKey.HREF_KEY);
} catch (JSONException e) {
return null;
}
}
/**
* If a JSON API formatted Object give information about "links",
* this function will return URL Template in String format inside term field.
*
* @param term
* @return URI Template in String
*/
public String getURLTemplateFromLinksMember(String term) {
Iterator<String> iterator = links.keys();
while (iterator.hasNext()) {
String key = iterator.next();
if (key.contains(term)) {
try {
Object linksObject = links.get(key);
if (linksObject instanceof JSONObject && ((JSONObject) linksObject).has(
JSONAPIResourceKey.HREF_KEY)) {
return ((JSONObject) linksObject).getString(JSONAPIResourceKey.HREF_KEY);
} else if (linksObject instanceof String) {
return (String) linksObject;
}
} catch (JSONException e) {
return null;
}
}
}
return null;
}
public Object findResourceId(Object linkedResource) {
if (linkedResource instanceof JSONArray) {
return linkedResource;
} else if (linkedResource instanceof JSONObject) {
try {
if (((JSONObject) linkedResource).has(JSONAPIResourceKey.IDS_KEY)) {
if (((JSONObject) linkedResource).get(JSONAPIResourceKey.IDS_KEY) instanceof JSONArray) {
return ((JSONObject) linkedResource).getJSONArray(JSONAPIResourceKey.IDS_KEY);
}
} else if (((JSONObject) linkedResource).has(JSONAPIResourceKey.ID_KEY)) {
return ((JSONObject) linkedResource).get(JSONAPIResourceKey.ID_KEY);
}else{
throw new JSONException("Can not find resource id. This object will be handled not as linked resource");
}
} catch (JSONException e) {
Log.e("JSONAPI",e.getMessage());
}
} else if (linkedResource instanceof String) {
return linkedResource;
}
return null;
}
/**
* @param term
* @return the json field containing term
*/
public String getLinksKeyContainingTerm(String term) {
Iterator<String> iterator = links.keys();
while (iterator.hasNext()) {
String key = iterator.next();
if (key.contains(term)) {
return key;
}
}
return EMPTY_STRING;
}
}
|
package com.elsevier.ews.jacksontest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
/**
* Simple JSON streaming parser adapted from
* http://www.journaldev.com/2324/jackson
* -json-processing-api-in-java-example-tutorial
*
* @author Eugenio Durand
*
*/
public class JacksonStreamingRead {
public static void main(String[] args) throws IOException {
// create JsonParser object
JsonParser jsonParser = new JsonFactory().createParser(new File(
"/tmp/stream_test.json"));
// loop through the JsonTokens
try {
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
String key = "";
List<String> appIds = new ArrayList<String>();
// System.out.print(jsonParser.getCurrentName());
// System.out.print(" - ");
// System.out.println(jsonParser.getText());
while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
String name = jsonParser.getCurrentName();
// System.out.print("\t");
// System.out.print(name);
// System.out.print(" - ");
// System.out.println(jsonParser.getText());
if ("pii".equals(name)) {
jsonParser.nextToken();
key = "pii:" + jsonParser.getText();
} else if ("appIds".equals(name)
&& jsonParser.nextToken() == JsonToken.START_ARRAY) {
while (jsonParser.nextToken() != JsonToken.END_ARRAY) {
// System.out.print("\t\t");
// System.out.print(jsonParser.getCurrentName());
// System.out.print(" - ");
// System.out.println(jsonParser.getText());
appIds.add(jsonParser.getText());
}
} // end of appIds array
} // end of index item
System.out.print("sadd ");
System.out.print(key);
for (String appId : appIds) {
System.out.print(" " + appId);
}
System.out.println();
} // end of JSON stream
} catch (JsonParseException e) {
System.err.print(e);
}
}
}
|
import javax.swing.JPanel;
public class MainSoundPannel extends JPanel {
/**
* Create the panel.
*/
public MainSoundPannel() {
}
}
|
package com.insat.gl5.crm_pfa.web.converter.account;
import com.insat.gl5.crm_pfa.model.Account;
import java.io.Serializable;
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
/**
*
* @author Mu7ammed 3li -- mohamed.ali.affes@gmail.com --
*/
@FacesConverter(forClass = Account.class)
@RequestScoped
public class AccountConverter implements Serializable, Converter {
private static final long serialVersionUID = 1L;
@Inject
private List<Account> lstAccounts;
@Override
public Object getAsObject(final FacesContext arg0, final UIComponent arg1, final String id) {
if (id == null) {
return null;
}
for (Account account : lstAccounts) {
if (account.getName().equals(id)) {
return account;
}
}
return null;
}
@Override
public String getAsString(final FacesContext context, final UIComponent comp, final Object object) {
if (object == null) {
return null;
}
return ((Account) object).getName();
}
}
|
package com.techelevator;
public class SecondClass extends PostalService {
public double rate;
@Override
public double calculateRate(int distance, double weight) {
this.rate = 0;
if (weight <= 7) {
this.rate += 0.0035;
} else if (weight >= 8 && weight < 15) {
this.rate += 0.0040;
} else if (weight == 15) {
this.rate += 0.0047;
} else if (weight >= 16 && weight <= 127) {
// 16 ounces in a pound
this.rate += 0.0195;
} else if (weight == 128) {
this.rate += 0.0450;
} else if (weight > 128) {
this.rate += 0.0500;
}
return this.rate * distance;
}
}
|
package com.example.spring04.service;
import java.util.List;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.example.spring04.modelVO.BoardVO;
import com.example.spring04.modelVO.Criteria;
import com.example.spring04.modelVO.SearchCriteria;
public interface BoardService {
public void boardWrite(BoardVO wrtVO, MultipartHttpServletRequest mpRequest) throws Exception;
public List<BoardVO> boardList() throws Exception;
public List<BoardVO> boardListPage(int startRow, int endRow) throws Exception;
public int listCount() throws Exception;
public BoardVO boardView(int seq) throws Exception;
public int passChk(BoardVO passChk) throws Exception;
public void boardUpdate(BoardVO updVO) throws Exception;
public void boardDelete(int seq) throws Exception;
public List<BoardVO> boardListSchPage(String option, String keyword, int startRow, int endRow) throws Exception;
public int boardSelCount(String option, String keyword) throws Exception;
public List<BoardVO> ListPage(Criteria cri) throws Exception;
public List<BoardVO> ListSchPage(SearchCriteria scri) throws Exception;
}
|
/**
*
*/
package com.assignment.conference.factory;
import com.assignment.conference.constants.Constants;
import com.assignment.conference.enums.TimeMeasureEnum;
import com.assignment.conference.time.Time;
/**
* @author vipul
*
*/
public class TimeFactory {
/**
*
*/
public TimeFactory() {
}
public static Time getTimeInstance(String time) {
if (time == null || time.equals(Constants.EMPTY_STRING)) {
return null;
}
final int indexOfColumn = time.indexOf(Constants.COLON);
final Integer hour = Integer.valueOf(time.substring(0, indexOfColumn));
final String remaining = time.substring(indexOfColumn + 1);
final Integer minute = Integer.valueOf(remaining.substring(0, 2));
return new Time(hour, minute, TimeMeasureEnum.getTimeMeasureEnum(remaining.substring(2, 4)));
}
}
|
package com.rc.portal.dao.impl;
import java.sql.SQLException;
import java.util.List;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.rc.app.framework.webapp.model.page.PageManager;
import com.rc.app.framework.webapp.model.page.PageWraper;
import com.rc.portal.dao.TMemberCertificatesDAO;
import com.rc.portal.vo.TMemberCertificates;
import com.rc.portal.vo.TMemberCertificatesExample;
public class TMemberCertificatesDAOImpl implements TMemberCertificatesDAO {
private SqlMapClient sqlMapClient;
public void setSqlMapClient(SqlMapClient sqlMapClient) {
this.sqlMapClient = sqlMapClient;
}
public SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
public TMemberCertificatesDAOImpl() {
super();
}
public TMemberCertificatesDAOImpl(SqlMapClient sqlMapClient) {
super();
this.sqlMapClient = sqlMapClient;
}
public int countByExample(TMemberCertificatesExample example) throws SQLException {
Integer count = (Integer) sqlMapClient.queryForObject("t_member_certificates.ibatorgenerated_countByExample", example);
return count.intValue();
}
public int deleteByExample(TMemberCertificatesExample example) throws SQLException {
int rows = sqlMapClient.delete("t_member_certificates.ibatorgenerated_deleteByExample", example);
return rows;
}
public int deleteByPrimaryKey(Long id) throws SQLException {
TMemberCertificates key = new TMemberCertificates();
key.setId(id);
int rows = sqlMapClient.delete("t_member_certificates.ibatorgenerated_deleteByPrimaryKey", key);
return rows;
}
public Long insert(TMemberCertificates record) throws SQLException {
return (Long) sqlMapClient.insert("t_member_certificates.ibatorgenerated_insert", record);
}
public Long insertSelective(TMemberCertificates record) throws SQLException {
return (Long) sqlMapClient.insert("t_member_certificates.ibatorgenerated_insertSelective", record);
}
public List selectByExample(TMemberCertificatesExample example) throws SQLException {
List list = sqlMapClient.queryForList("t_member_certificates.ibatorgenerated_selectByExample", example);
return list;
}
public TMemberCertificates selectByPrimaryKey(Long id) throws SQLException {
TMemberCertificates key = new TMemberCertificates();
key.setId(id);
TMemberCertificates record = (TMemberCertificates) sqlMapClient.queryForObject("t_member_certificates.ibatorgenerated_selectByPrimaryKey", key);
return record;
}
public int updateByExampleSelective(TMemberCertificates record, TMemberCertificatesExample example) throws SQLException {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = sqlMapClient.update("t_member_certificates.ibatorgenerated_updateByExampleSelective", parms);
return rows;
}
public int updateByExample(TMemberCertificates record, TMemberCertificatesExample example) throws SQLException {
UpdateByExampleParms parms = new UpdateByExampleParms(record, example);
int rows = sqlMapClient.update("t_member_certificates.ibatorgenerated_updateByExample", parms);
return rows;
}
public int updateByPrimaryKeySelective(TMemberCertificates record) throws SQLException {
int rows = sqlMapClient.update("t_member_certificates.ibatorgenerated_updateByPrimaryKeySelective", record);
return rows;
}
public int updateByPrimaryKey(TMemberCertificates record) throws SQLException {
int rows = sqlMapClient.update("t_member_certificates.ibatorgenerated_updateByPrimaryKey", record);
return rows;
}
private static class UpdateByExampleParms extends TMemberCertificatesExample {
private Object record;
public UpdateByExampleParms(Object record, TMemberCertificatesExample example) {
super(example);
this.record = record;
}
public Object getRecord() {
return record;
}
}
public PageWraper selectByRepositoryByPage(TMemberCertificatesExample example) throws SQLException {
PageWraper pw=null;
int count=this.countByExample(example);
List list = sqlMapClient.queryForList("t_member_certificates.selectByExampleByPage", example);
System.out.println("��Դ��ҳ��ѯlist.size="+list.size());
pw=PageManager.getPageWraper(example.getPageInfo(), list, count);
return pw;
}
}
|
package com.zero.qa.testcases;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.zero.qa.base.TestBase;
import com.zero.qa.pages.Home;
import com.zero.qa.pages.LoginPage;
import com.zero.qa.pages.PurForCurPage;
import com.zero.qa.util.TestUtil;
public class PurForCurTest extends TestBase{
PurForCurPage purForCur;
TestUtil testUtil;
LoginPage loginPage;
Home home;
public PurForCurTest() {
super();
}
@BeforeMethod
public void setUp() {
initialization();
purForCur = new PurForCurPage();
testUtil = new TestUtil();
loginPage = new LoginPage();
home = new Home();
home.clickOnSignin();
loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
purForCur.clickOnPayBillTab();
purForCur.clickOnpurFurCurTab();
}
@Test(priority=1)
public void verifyPurForCurTitleTest(){
String purForCurTitle = purForCur.verifyPurForCurPageTitle();
Assert.assertEquals(purForCurTitle, "Zero - Pay Bills", "Purchase Foreign Currency title not matched");
}
@Test(priority=2)
public void verifyPurForCurHeaderTest(){
Assert.assertTrue(purForCur.verifyPurForCurHeaderTest());
}
@Test(priority=3)
public void validTest_1() {
purForCur.selectCurrency("Eurozone (euro)");
purForCur.amountPFC("2");
purForCur.radioUS();
//purForCur.radioCountry();
purForCur.purchaseBtn();
Assert.assertTrue(purForCur.purchaseConfirmation());
}
// @Test(priority=4)
// public void validTest_2() {
// purForCur.selectCurrency("Eurozone (euro)");
// purForCur.amountPFC("3");
// //purForCur.radioUS();
// purForCur.radioCountry();
// purForCur.purchaseBtn();
// Assert.assertTrue(purForCur.purchaseConfirmation());
// }
@AfterMethod
public void tearDown(){
driver.quit();
}
}
|
package hackerrank;
public class InOrderBinaryTreeTraversalWithoutRecursion {
// https://www.java67.com/2016/08/binary-tree-inorder-traversal-in-java.html
public static void main(String[] args) {
}
}
|
package com.pine.template.demo.old.dagger2;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.pine.template.demo.R;
import com.pine.template.demo.util.ConsoleUtils;
/**
* Created by tanghongfeng on 2017/8/10.
*/
public class Dagger2Activity extends AppCompatActivity {
private final static String TAG = "Dagger2Activity";
private ScrollView mConsoleSv;
private TextView mConsoleTv;
private Button mNormalBtn;
private Button mDependencyBtn;
private Button mSubBtn;
private Button mQualifierBtn;
private Button mScopeBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo_activity_dagger2);
mConsoleSv = (ScrollView) findViewById(R.id.console_sv);
mConsoleTv = (TextView) findViewById(R.id.console_tv);
mNormalBtn = (Button) findViewById(R.id.normal_btn_ad);
mDependencyBtn = (Button) findViewById(R.id.dependency_btn_ad);
mSubBtn = (Button) findViewById(R.id.sub_btn_ad);
mQualifierBtn = (Button) findViewById(R.id.qualifier_btn_ad);
mScopeBtn = (Button) findViewById(R.id.scope_btn_ad);
final NormalComponent normalComponent = DaggerNormalComponent.builder().normalModule(new NormalModule()).build();
final ParentComponent parentComponent = DaggerParentComponent.builder().parentModule(new ParentModule()).build();
final DependencyComponent dependencyComponent = DaggerDependencyComponent.builder().parentComponent(parentComponent).dependencyModule(new DependencyModule()).build();
final SubComponent subComponent = parentComponent.createSubComponent(new SubModule());
final QualifierComponent qualifierComponent = DaggerQualifierComponent.builder().qualifierModule(new QualifierModule()).build();
final ScopeComponent scopeComponent = DaggerScopeComponent.builder().scopeModule(new ScopeModule()).build();
mNormalBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NormalInjectee normalInjectee = new NormalInjectee(normalComponent);
String injectTrace = normalInjectee.getInjectTrace();
ConsoleUtils.out(mConsoleSv, mConsoleTv, injectTrace);
}
});
mDependencyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DependencyInjectee dependencyInjectee = new DependencyInjectee(dependencyComponent);
String injectTrace = dependencyInjectee.getInjectTrace();
ConsoleUtils.out(mConsoleSv, mConsoleTv, injectTrace);
}
});
mSubBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SubInjectee subInjectee = new SubInjectee(subComponent);
String injectTrace = subInjectee.getInjectTrace();
ConsoleUtils.out(mConsoleSv, mConsoleTv, injectTrace);
}
});
mQualifierBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
QualifierInjectee qualifierInjectee = new QualifierInjectee(qualifierComponent);
String injectTrace = qualifierInjectee.getInjectTrace();
ConsoleUtils.out(mConsoleSv, mConsoleTv, injectTrace);
}
});
mScopeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ScopeInjectee scopeInjectee = new ScopeInjectee(scopeComponent);
String injectTrace = scopeInjectee.getInjectTrace();
ConsoleUtils.out(mConsoleSv, mConsoleTv, injectTrace);
}
});
}
}
|
package com.harrymt.productivitymapping.coredata;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.android.gms.maps.model.LatLng;
import com.harrymt.productivitymapping.PROJECT_GLOBALS;
import com.harrymt.productivitymapping.utility.Util;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Describes a zone object.
*/
public class Zone implements Parcelable {
// Zone properties
public int zoneID;
public int hasSynced; // if zone has been synced with server
public double lat;
public double lng;
public float radiusInMeters;
public String name;
public String[] blockingApps = new String[] {};
public String[] keywords = new String[] {};
/**
* Constructor.
*
* @param latLng Center point of zone.
*/
public Zone(LatLng latLng) {
this(latLng.latitude, latLng.longitude);
}
/**
* Constructor.
*
* @param lt Longitude of center.
* @param lg Latitude of center.
*/
public Zone(double lt, double lg) {
this(lt, lg, 5.0f);
}
/**
* Constructor.
*
* @param lt Longitude of center.
* @param lg Latitude of center.
* @param r Radius.
*/
public Zone(double lt, double lg, float r) {
this(-1, lt, lg, r, "", 0, new String[] {}, new String[] {});
}
/**
* Constructor.
*
* @param id Zone id.
* @param lt Longitude of center.
* @param lg Latitude of center.
* @param r Radius of zone.
* @param nm Name of zone.
* @param synced Has Synched.
* @param appsToBlock List of apps to block.
* @param words List of keywords to let through.
*/
public Zone(int id, double lt, double lg, float r, String nm, int synced, String[] appsToBlock, String[] words) {
zoneID = id;
lat = lt;
lng = lg;
radiusInMeters = r;
name = nm;
hasSynced = synced;
blockingApps = appsToBlock;
keywords = words;
}
/**
* Constructor.
*
* @param in Parcel.
*/
public Zone(Parcel in) {
zoneID = in.readInt();
lat = in.readDouble();
lng = in.readDouble();
radiusInMeters = in.readFloat();
name = in.readString();
hasSynced = in.readInt();
blockingApps = in.createStringArray();
keywords = in.createStringArray();
}
/**
* Unused.
* @return contents.
*/
@Override
public int describeContents() {
return 0;
}
/**
* Write zone data to parcel.
*
* @param out Parcel to write to.
* @param flags Flags.
*/
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(zoneID);
out.writeDouble(lat);
out.writeDouble(lng);
out.writeFloat(radiusInMeters);
out.writeString(name);
out.writeInt(hasSynced);
out.writeStringArray(blockingApps);
out.writeStringArray(keywords);
}
/**
* Convert keywords to string.
*
* @return String without delimiters.
*/
public String keywordsAsStr() {
return Util.arrayToString(keywords);
}
/**
* Convert blocking apps to string.
*
* @return String without delimiters.
*/
public String blockingAppsAsStr() {
return Util.arrayToString(blockingApps);
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
/**
* Regenerate the zone parcel object.
*/
public static final Parcelable.Creator<Zone> CREATOR = new Parcelable.Creator<Zone>() {
/**
* Make the zone from the parcel.
*
* @param in Parcel.
* @return Zone object.
*/
@Override
public Zone createFromParcel(Parcel in) {
return new Zone(in);
}
/**
* Make a new zone array from a parcel.
*
* @param size Size of array.
* @return Zone array of give size.
*/
@Override
public Zone[] newArray(int size) {
return new Zone[size];
}
};
/**
* Convert the zone object to a JSON representation.
*
* @param c Context of zone.
* @return Zone object in JSON format.
* @throws JSONException If we cannot serialize the zone to JSON.
*/
public JSONObject getJSONObject(Context c) throws JSONException {
JSONObject zoneInJSON = new JSONObject();
zoneInJSON.put("user_id", PROJECT_GLOBALS.getUniqueDeviceId(c));
zoneInJSON.put("id", this.zoneID);
zoneInJSON.put("name", this.name);
zoneInJSON.put("lat", this.lat);
zoneInJSON.put("lng", this.lng);
zoneInJSON.put("radius", this.radiusInMeters);
zoneInJSON.put("blockingApps", new JSONArray(new ArrayList<>(Arrays.asList(this.blockingApps))));
zoneInJSON.put("keywords", new JSONArray(new ArrayList<>(Arrays.asList(this.keywords))));
return zoneInJSON;
}
}
|
package com.countout.dao;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.countout.entity.CarInfoManagerEntity;
import com.tang.plug.hibernate.HibernateSimpleEntityDao;
import com.tang.util.page.Page;
/**
* 车辆信息管理模块--数据底层
* @author Mr.tang
*/
@Repository
public class CarInfoManagerDao extends HibernateSimpleEntityDao<CarInfoManagerEntity> {
/**
* 车辆信息管理分页查询
* @param requestMap
* @return
*/
public Page<CarInfoManagerEntity> pageQuery(Map<String, Object> requestMap) {
Criteria dc = createCriteria(CarInfoManagerEntity.class);
int start = (Integer) requestMap.get("pageNum");
int pageSize = (Integer) requestMap.get("pageSize");
int pageNum = (start-1) * pageSize;
String name = (String) requestMap.get("name");
if (StringUtils.isNotEmpty(name)) {
dc.add(Restrictions.like("this.name", name, MatchMode.ANYWHERE));
}
dc.add(Restrictions.eq("this.state", 1));
dc.addOrder(Order.asc("this.createTime"));
return super.pagedQuery(dc, pageNum, pageSize);
}
}
|
package com.github.adambots.steamworks2017.autonModes;
import org.usfirst.frc.team245.robot.Actuators;
import org.usfirst.frc.team245.robot.Constants;
import com.github.adambots.steamworks2017.drive.Drive;
import edu.wpi.first.wpilibj.command.Command;
public class BaselineCenter extends Command {
static double distance = 95; // distance to baseline
static boolean hasFinished = false;
static double rampSpeed = .2;
static boolean driveDoneLeft = false;
static boolean driveDoneRight = false;
public BaselineCenter() {
System.out.println("I got here BaselineCenter");
}
public BaselineCenter(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public BaselineCenter(double timeout) {
super(timeout);
// TODO Auto-generated constructor stub
}
public BaselineCenter(String name, double timeout) {
super(name, timeout);
// TODO Auto-generated constructor stub
}
@Override
protected void initialize() {
// TODO Auto-generated method stub
Actuators.getLeftDriveMotor().setPosition(0);
Actuators.getRightDriveMotor().setPosition(0);
Drive.drive(0, 0);
}
@Override
protected void execute() {
// System.out.println("I got here execution (Baseline Center)");
try {
//Left Side
if (Math.abs(Actuators.getLeftDriveMotor().getEncPosition()) < 750) {
System.out.println("Ramp up");
Actuators.getLeftDriveMotor().set(-rampSpeed);
hasFinished = false;
driveDoneLeft = false;
} else if (Math.abs(Actuators.getLeftDriveMotor().getEncPosition()) < 7500
&& Math.abs(Actuators.getLeftDriveMotor().getEncPosition()) >= 750) {
System.out.println("Half speed");
Actuators.getLeftDriveMotor().set(Constants.HALF_MOTOR_SPEED - .1);
driveDoneLeft = false;
hasFinished = false;
} else if (Math.abs(Actuators.getLeftDriveMotor().getEncPosition()) >= 7500
&& Math.abs(Actuators.getLeftDriveMotor().getEncPosition()) < 8300) {
System.out.println("Ramp down");
Actuators.getLeftDriveMotor().set(rampSpeed);
driveDoneLeft = false;
hasFinished = false;
} else if (Math.abs(Actuators.getLeftDriveMotor().getEncPosition()) >= 8300) {
System.out.println("Stop");
Actuators.getLeftDriveMotor().set(Constants.MOTOR_STOP);
hasFinished = false;
driveDoneLeft = true;
}
//Right side
if (Math.abs(Actuators.getRightDriveMotor().getEncPosition()) < 750) {
System.out.println("Ramp up");
Actuators.getRightDriveMotor().set(rampSpeed);
hasFinished = false;
driveDoneRight = false;
} else if (Math.abs(Actuators.getRightDriveMotor().getEncPosition()) < 7500
&& Math.abs(Actuators.getRightDriveMotor().getEncPosition()) >= 750) {
System.out.println("Half speed");
Actuators.getRightDriveMotor().set(Constants.HALF_MOTOR_SPEED - .1);
driveDoneLeft = false;
hasFinished = false;
} else if (Math.abs(Actuators.getRightDriveMotor().getEncPosition()) >= 7500
&& Math.abs(Actuators.getRightDriveMotor().getEncPosition()) < 8300) {
System.out.println("Ramp down");
Actuators.getRightDriveMotor().set(rampSpeed);
driveDoneLeft = false;
hasFinished = false;
} else if (Math.abs(Actuators.getRightDriveMotor().getEncPosition()) >= 8300) {
System.out.println("Stop");
Actuators.getRightDriveMotor().set(Constants.MOTOR_STOP);
hasFinished = false;
driveDoneRight = true;
}
if (driveDoneLeft && driveDoneRight) {
// Actuators.getDispenseGearPneumatic().set(true);
hasFinished = true;
}
// Drive.driveWithPID(distance, distance);
} catch (Exception e) {
System.out.println(e);
}
}
@Override
protected boolean isFinished() {
// TODO Auto-generated method stub
return hasFinished;
}
@Override
protected void end() {
// TODO Auto-generated method stub
}
@Override
protected void interrupted() {
// TODO Auto-generated method stub
}
}
|
package com.zking.ssm.service.imp;
import com.zking.ssm.mapper.NewsMapper;
import com.zking.ssm.model.News;
import com.zking.ssm.service.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
@Service
public class INewsServiceImp implements INewsService {
@Autowired
private NewsMapper newsMapper;
@Override
public List<News> queryNewsLst() {
return newsMapper.queryNewsLst();
}
}
|
package chess.pkg2;
import java.util.ArrayList;
public class King extends Piece{
int[] kingOffset = {-9,-8,-7,-1,1,7,8,9};
public final static int[] whiteKingEvaluator = {
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-20,-30,-30,-40,-40,-30,-30,-20,
-10,-20,-20,-20,-20,-20,-20,-10,
20, 20, 0, 0, 0, 0, 20, 20,
20, 30, 10, 0, 0, 10, 30, 20
};
public final static int[] blackKingEvaluator = {
20, 30, 10, 0, 0, 10, 30, 20,
20, 20, 0, 0, 0, 0, 20, 20,
-10,-20,-20,-20,-20,-20,-20,-10,
-20,-30,-30,-40,-40,-30,-30,-20,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30,
-30,-40,-40,-50,-50,-40,-40,-30
};
public King(int piecePosition, int alliance) {
super(piecePosition, alliance);
}
@Override
public int getPointStatic() {
return 10000;
}
@Override
public String toString(){
// if(alliance == 0){
return "K";
// }else{
// return "k";
// }
}
@Override
public int[] getPossibleNextPosition(ChessPosition positionChess) {
int[] possibleKingNextPosition = new int[10];
int j;
j=0;
int testNextPosition;
for(int i=0; i<10; ++i){
possibleKingNextPosition[i] = 100;
}
testNextPosition = piecePosition;
if((testNextPosition % 8 != 7)){
testNextPosition += kingOffset[2];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if((testNextPosition % 8 != 7)){
testNextPosition += kingOffset[4];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if((testNextPosition % 8 != 7)){
testNextPosition += kingOffset[7];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if((testNextPosition % 8 != 0)){
testNextPosition += kingOffset[5];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if(testNextPosition % 8 != 0){
testNextPosition += kingOffset[3];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if(testNextPosition % 8 != 0){
testNextPosition += kingOffset[0];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if(true ){
testNextPosition += kingOffset[1];
if((testNextPosition >= 0) && (testNextPosition <64)){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
testNextPosition = piecePosition;
if(true){
testNextPosition += kingOffset[6];
if(testNextPosition >=0 && testNextPosition < 64){
if(positionChess.chessBoard.get(testNextPosition) == null){
possibleKingNextPosition[j] = testNextPosition;
++j;
}else{
Piece pieceAtPosition = positionChess.chessBoard.get(testNextPosition);
if(pieceAtPosition.getAlliance() != this.getAlliance()){
possibleKingNextPosition[j] = testNextPosition;
++j;
}
}
}
}
//White King Castle
if(this.getAlliance() == 0){
ArrayList<Integer> tileAttackedByBlack = positionChess.getAllTileNotIncludeKing(1);
if(positionChess.getWhiteQueenSideCastleCondition() == 0 ){
if((positionChess.chessBoard.get(59) == null) && (positionChess.chessBoard.get(58) == null) && (positionChess.chessBoard.get(57) == null) && (piecePosition == 60) &&
((positionChess.chessBoard.get(49) == null) || (!(positionChess.chessBoard.get(49).toString().equals("K")))) ){
for(int i : tileAttackedByBlack){
if(!((i == 59) || (i==58) || (i==60))){
possibleKingNextPosition[j] = 58;
}else{
possibleKingNextPosition[j] = 100;
break;
}
}
}
++j;
}
if(positionChess.getWhiteKingSideCastleCondition() == 0 ){
if((positionChess.chessBoard.get(61) == null) && (positionChess.chessBoard.get(62) == null) && (piecePosition == 60) &&
((positionChess.chessBoard.get(54) == null) || (!(positionChess.chessBoard.get(54).toString().equals("K"))))){
for(int i : tileAttackedByBlack){
if(!((i == 61) || (i==62) || (i==60))){
possibleKingNextPosition[j] = 62;
}else{
possibleKingNextPosition[j] = 100;
break;
}
}
}
}
}
//Black King Castle
if(this.getAlliance() == 1){
ArrayList<Integer> tileAttackedByWhite = positionChess.getAllTileNotIncludeKing(0);
if(positionChess.getBlackQueenSideCastleCondition() == 0 ){
if((positionChess.chessBoard.get(1) == null) && (positionChess.chessBoard.get(2) == null) && (positionChess.chessBoard.get(3) == null) && (piecePosition == 4) &&
((positionChess.chessBoard.get(9) == null) || (!(positionChess.chessBoard.get(9).toString().equals("K"))))){
for(int i : tileAttackedByWhite){
if(!((i == 3) || (i==2) || (i==4))){
possibleKingNextPosition[j] = 2;
}else{
possibleKingNextPosition[j] = 100;
break;
}
}
}
++j;
}
if(positionChess.getBlackKingSideCastleCondition() == 0 ){
if((positionChess.chessBoard.get(6) == null) && (positionChess.chessBoard.get(5) == null) && (piecePosition == 4) &&
((positionChess.chessBoard.get(14) == null) || (!(positionChess.chessBoard.get(14).toString().equals("K"))))){
for(int i : tileAttackedByWhite){
if(!((i == 6) || (i==5) || (i==4))){
possibleKingNextPosition[j] = 6;
}else{
possibleKingNextPosition[j] = 100;
break;
}
}
}
}
}
return possibleKingNextPosition;
}
@Override
public int getLocationPoint(int location) {
if(alliance == 0){
return whiteKingEvaluator[location];
}else{
return blackKingEvaluator[location];
}
}
}
|
package com.github.vinja.server;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.github.vinja.compiler.CompilerContext;
import com.github.vinja.omni.MemberReferenceFinder;
import com.github.vinja.omni.ReferenceLocation;
public class SzjdeSearchReferenceCommand extends SzjdeCommand {
private static final String SEPERATOR = "::";
public SzjdeSearchReferenceCommand() {
}
public String execute() {
String classPathXml = params.get(SzjdeConstants.PARAM_CLASSPATHXML);
String srcPath = params.get(SzjdeConstants.PARAM_SOURCEFILE);
String memberDesc = params.get(SzjdeConstants.PARAM_MEMBER_DESC);
File file = new File(classPathXml);
if (file.isDirectory()) return "";
CompilerContext ctx=getCompilerContext(classPathXml);
String targetClass= ctx.buildClassName(srcPath);
targetClass = targetClass.replace(".", "/");
String result = search(ctx,targetClass,memberDesc);
return result;
}
public String search(CompilerContext ctx , String targetClass, String memberDesc) {
MemberReferenceFinder app = new MemberReferenceFinder();
try {
app.findCallingMethodInDir(ctx.getOutputDir(), targetClass,memberDesc);
} catch (Exception e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
for (ReferenceLocation loc : app.getReferenceLocations() ) {
sb.append(getSourcePath(ctx,loc.className,loc.source)).append(SEPERATOR);
sb.append(loc.line).append(SEPERATOR);
sb.append(getSourceLine(ctx,loc.className,loc.source,loc.line)).append("\n");
}
return sb.toString();
}
public String getSourcePath(CompilerContext ctx ,String className,String sourceName) {
String rtlPathName = sourceName;
if (className.indexOf("/") > 0 ) {
rtlPathName = className.substring(0,className.lastIndexOf("/")+1) + sourceName;
}
String sourcePath = ctx.findSourceFile(rtlPathName);
return sourcePath;
}
public String getSourceLine(CompilerContext ctx, String className, String sourceName, int line) {
String sourcePath = getSourcePath(ctx,className,sourceName);
FileReader fr = null;
try {
fr = new FileReader(sourcePath);
BufferedReader br = new BufferedReader(fr);
String result = "";
int i = 0;
while (true) {
i++;
result = br.readLine();
if (result == null || i==line ) break;
}
return result;
} catch (IOException e) {
} finally {
if (fr !=null) try { fr.close(); } catch (Exception e) {}
}
return "";
}
}
|
package com.campus.mapper;
import com.campus.entity.MenuBean;
import java.util.List;
public interface SysMapper {
//根据角色id查询菜单
public List<MenuBean> getMenuList(Long rid);
}
|
package net.d4rk.inventorychef.inventory.expandablelistview.storageplaceingredientlist.model;
import net.d4rk.inventorychef.database.dao.Ingredient;
import net.d4rk.inventorychef.database.dao.StoragePlace;
import java.util.List;
public class Inventory {//implements Parent<Ingredient> {
private StoragePlace mStoragePlace;
private List<Ingredient> mIngredients;
private boolean mIsVisible = true;
public Inventory(
StoragePlace storagePlace,
List<Ingredient> ingredients
) {
mStoragePlace = storagePlace;
mIngredients = ingredients;
}
public StoragePlace getStoragePlace() {
return mStoragePlace;
}
public Ingredient getIngredient(int position) {
return mIngredients.get(position);
}
public int getVisibleCount() {
if (mIsVisible) {
// all ingredients and group title are visible
return mIngredients.size() + 1;
} else {
// only group title visible
return 1;
}
}
}
|
package calculator.backend;
public class Operator implements MathematicalObject {
private MathOp mathOp;
public Operator(MathOp mathOp) {
this.mathOp = mathOp;
}
public MathOp getMathOp() {
return mathOp;
}
}
|
package com.yunkuent.sdk;
import com.gokuai.base.ReturnResult;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
/**
* Created by qp on 2017/3/16.
*/
public class YunkuThirdPartyTest {
public static final String CLIENT_ID = "";
public static final String CLIENT_SECRET = "";
public static final String OUT_ID = "";
@Test
public void createEnt() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.createEnt("yunku2","yunku2","","","");
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void createEntByMap() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
HashMap<String, String> map = new HashMap<>();
map.put("__setting_site_url","aaa");
String s = thirdParty.createEnt(map,"yunku","yunku","","","");
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void getEntInfo() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.getEntInfo();
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void orderSubscribe() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.orderSubscribe(-1,1,12);
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void orderUpgrade() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.orderUpgrade(-1,1);
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void orderRenew() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.orderRenew(12);
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void orderUnsubscribe() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.orderUnsubscribe();
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void getEntToken() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.getEntToken();
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
@Test
public void getSsoUrl() throws Exception {
ThirdPartyManager thirdParty = new ThirdPartyManager(CLIENT_ID, CLIENT_SECRET, OUT_ID);
String s = thirdParty.getSsoUrl("");
ReturnResult r = ReturnResult.create(s);
Assert.assertEquals(200,r.getStatusCode());
}
}
|
package com.goldgov.dygl.dynamicfield.valueresource.impl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import com.goldgov.dygl.dynamicfield.valueresource.ValueResource;
import com.goldgov.dygl.freemarker.FormFieldUtils;
import com.goldgov.gtiles.core.web.GTilesContext;
import com.goldgov.gtiles.module.businessfield.service.BusinessField;
public class FileValueResource implements ValueResource{
public final String PREFIX = "file:";
private static final Map<String,String[]> valueResourceMap = new HashMap<String,String[]>();
@Override
public boolean supportsValue(String expressionStr) {
if(expressionStr != null){
return expressionStr.startsWith(PREFIX);
}
return false;
}
@Override
public String[] resolveFiled(BusinessField field) {
String expressionStr = field.getDefaultValue();
String filePath = expressionStr.substring(PREFIX.length());
if(valueResourceMap.containsKey(filePath)){
return valueResourceMap.get(filePath);
}
String webRoot = GTilesContext.getWebRoot();
String valueFilePath = FilenameUtils.concat(webRoot, filePath);
File valueFile = new File(valueFilePath);
BufferedReader fileReader = null;
try {
fileReader = new BufferedReader(new FileReader(valueFile));
} catch (FileNotFoundException e) {
throw new RuntimeException("字段值文件不存在:"+valueFilePath,e);
}
List<String> fieldList = new ArrayList<String>();
String str = null;
try {
while ((str = fileReader.readLine()) != null) {
if(str.split(FormFieldUtils.VALUE_SEPARATOR).length != 2){
throw new RuntimeException("字段值不满足格式要求:" + str + "(" + filePath + ")");
}
fieldList.add(str);
}
valueResourceMap.put(filePath, fieldList.toArray(new String[0]));
} catch (IOException e) {
throw new RuntimeException("读取字段值文件时发生IO错误:"+valueFilePath,e);
}finally{
try {
fileReader.close();
} catch (IOException e) {}
}
return valueResourceMap.get(filePath);
}
}
|
package com.isystk.sample.web.front.service;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.isystk.sample.common.dto.mail.EntryRegistTemporary;
import com.isystk.sample.common.exception.NoDataFoundException;
import com.isystk.sample.common.helper.SendMailHelper;
import com.isystk.sample.common.service.BaseTransactionalService;
import com.isystk.sample.common.util.DateUtils;
import com.isystk.sample.common.values.MailTemplate;
import com.isystk.sample.common.values.UserStatus;
import com.isystk.sample.domain.dao.MMailTemplateDao;
import com.isystk.sample.domain.dao.TUserDao;
import com.isystk.sample.domain.dao.TUserOnetimeValidDao;
import com.isystk.sample.domain.dto.MMailTemplateCriteria;
import com.isystk.sample.domain.dto.TUserOnetimeValidCriteria;
import com.isystk.sample.domain.entity.MMailTemplate;
import com.isystk.sample.domain.entity.TUser;
import com.isystk.sample.domain.entity.TUserOnetimeValid;
import com.isystk.sample.domain.repository.TUserRepository;
import lombok.val;
@Service
public class EntryService extends BaseTransactionalService {
@Value("${spring.mail.properties.mail.from}")
String fromAddress;
@Value("${server.address}")
String domain;
@Autowired
TUserDao tUserDao;
@Autowired
TUserRepository tUserRepository;
@Autowired
TUserOnetimeValidDao tUserOnetimeValidDao;
@Autowired
MMailTemplateDao mMailTemplateDao;
@Autowired
SendMailHelper sendMailHelper;
/**
* 仮会員登録
*
* @param user
*/
public void registTemporary(TUser tUser) {
// DB登録する
tUser.setStatus(UserStatus.TEMPORARY.getCode());
tUserRepository.create(tUser);
// 会員-初期承認を登録する
TUserOnetimeValid tUserOnetimeValid = new TUserOnetimeValid();
tUserOnetimeValid.setUserId(tUser.getUserId());
String onetimeKey = generateOnetimeKey();
tUserOnetimeValid.setOnetimeKey(onetimeKey);
// 7時間の制限時間を設ける
tUserOnetimeValid.setOnetimeValidTime(DateUtils.getNow().plusHours(7));
tUserOnetimeValidDao.insert(tUserOnetimeValid);
// 仮会員登録メールを送信する
val mailTemplate = getMailTemplate(MailTemplate.ENTRY_REGIST_TEMPORARY.getCode());
val subject = mailTemplate.getTitle();
val templateBody = mailTemplate.getText();
EntryRegistTemporary dto = new EntryRegistTemporary();
dto.setFamilyName(tUser.getFamilyName());
dto.setDomain(domain);
dto.setOnetimeKey(onetimeKey);
Map<String, Object> objects = new HashMap<>();
objects.put("dto", dto);
val body = sendMailHelper.getMailBody(templateBody, objects);
sendMailHelper.sendMail(fromAddress, tUser.getEmail(), subject, body);
}
/**
* 本会員登録
*
* @param onetimeKey
*/
public void registComplete(String onetimeKey) {
// ワンタイムキーからユーザーIDを取得する
var tUserOnetimeValid = getTUserOnetimeValid(onetimeKey);
if (tUserOnetimeValid == null) {
throw new NoDataFoundException("指定されたワンタイムキーが見つかりません。[onetimeKey=" + onetimeKey + "]");
}
// 承認期限オーバー
if (DateUtils.beforeNow(tUserOnetimeValid.getOnetimeValidTime())) {
throw new NoDataFoundException("指定されたワンタイムキーは承認期限を過ぎています。[onetimeKey=" + onetimeKey + "]");
}
// ユーザー情報を取得する
TUser tUser = tUserDao.selectById(tUserOnetimeValid.getUserId())
.orElseThrow(() -> new NoDataFoundException(
"user_id=" + tUserOnetimeValid.getUserId() + " のデータが見つかりません。"));
// DB登録する
tUser.setStatus(UserStatus.VALID.getCode());
tUserRepository.update(tUser);
// 本会員登録完了メールを送信する
val mailTemplate = getMailTemplate(MailTemplate.ENTRY_REGIST_VALID.getCode());
val subject = mailTemplate.getTitle();
val templateBody = mailTemplate.getText();
EntryRegistTemporary dto = new EntryRegistTemporary();
dto.setFamilyName(tUser.getFamilyName());
dto.setDomain(domain);
Map<String, Object> objects = new HashMap<>();
objects.put("dto", dto);
val body = sendMailHelper.getMailBody(templateBody, objects);
sendMailHelper.sendMail(fromAddress, tUser.getEmail(), subject, body);
// ワンタイムキーを削除
tUserOnetimeValidDao.delete(tUserOnetimeValid);
}
/**
* ワンタイムキー生成
*
* @return 生成されたワンタイムキー
*/
private String generateOnetimeKey() {
String onetimeKey = "";
boolean loopFlg = true;
do {
// ランダムな文字列を生成する。
onetimeKey = RandomStringUtils.randomAlphanumeric(32);
// 生成したキーが存在しないか確認する
if (null == getTUserOnetimeValid(onetimeKey)) {
loopFlg = false;
}
} while (loopFlg);
return onetimeKey;
}
/**
* 会員-初期承認Entityを取得する
*
* @param onetimeKey ワンタイムキー
* @return 会員Entity
*/
public TUserOnetimeValid getTUserOnetimeValid(String onetimeKey) {
TUserOnetimeValidCriteria criteria = new TUserOnetimeValidCriteria();
criteria.setOnetimeKeyEq(onetimeKey);
return tUserOnetimeValidDao.findOne(criteria).orElse(null);
}
/**
* メールテンプレートを取得する。
*
* @return
*/
protected MMailTemplate getMailTemplate(Integer templateId) {
val criteria = new MMailTemplateCriteria();
criteria.setMailTemplateIdEq(templateId);
val mailTemplate = mMailTemplateDao.findOne(criteria).orElseThrow(
() -> new NoDataFoundException("templateKey=" + templateId + " のデータが見つかりません。"));
return mailTemplate;
}
}
|
package com.main.activity;
import android.app.TabActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.widget.TabHost;
import com.main.chart.DisplayActivity;
@SuppressWarnings("deprecation")
public class TabMainActivity extends TabActivity {
private static final String TAG = "TabMainActivity";
private TabHost tabHost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置屏幕旋转
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.tab);
this.tabHost = super.getTabHost();
// tabHost.addTab(tabHost.newTabSpec("tab1")
// .setIndicator("地图",getResources().getDrawable(R.drawable.baidu_map_icon))
// .setContent(new Intent(this, RoutePlanDemo.class)));
tabHost.addTab(tabHost.newTabSpec("tab4")
.setIndicator("",getResources().getDrawable(R.drawable.location_fill))
.setContent(new Intent(this, OverlayDemo.class)));
tabHost.setCurrentTab(0);
tabHost.addTab(tabHost.newTabSpec("tab2")
.setIndicator("",getResources().getDrawable(R.drawable.community_fill))
.setContent(new Intent(this, DisplayActivity.class)));
tabHost.addTab(tabHost.newTabSpec("tab3")
.setIndicator("",getResources().getDrawable(R.drawable.new_fill))
.setContent(new Intent(this, Dis_Info_Activity.class)));
}
}
|
package flight_booking;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class Passenger {
public int pid;
public String name, flightNumber, date, cardNumber;
public String bookTime, address, expDate;
public Passenger (int pid, String cardNumber, String flightNumber, String name, String date) {
this.pid = pid;
this.flightNumber = flightNumber;
this.cardNumber = cardNumber;
this.name = name;
this.date = date;
}
public int getPID(){
return this.pid;
}
public String getCardNumber(){
return this.cardNumber;
}
public String getName(){
return this.name;
}
public String getFlightNumber(){
return this.flightNumber;
}
public String getbookTime(){
return this.bookTime;
}
public String getAddress(){
return this.address;
}
public String getExpDate(){
return this.expDate;
}
public void setPID(int pid) {
this.pid = pid;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public void setName(String name) {
this.name = name;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public void setbookTime(String bookTime){
this.bookTime = bookTime;
}
public void setAddress(String address){
this.address = address;
}
public void setExpDate(String expDate){
this.expDate = expDate;
}
}
|
package ua.lviv.iot.labaratornafirst;
import java.lang.String;
public class ElectricLamp {
private static String companyProducer;
protected float widthInMm;
protected float lengthInMm;
private float powerOfLightningInWatts;
private int warrantyPeriodOfWorkInDays;
private String producingCountry;
private String materials;
private String typeOfLamp;
private String typeOfLight;
public ElectricLamp() {
}
public ElectricLamp(float powerOfLightningInWatts, int warrantyPeriodOfWorkInDays, String producingCountry,
String materials, String typeOfLamp, String typeOfLight) {
this(0, 0, powerOfLightningInWatts, warrantyPeriodOfWorkInDays, producingCountry, materials, typeOfLamp,
typeOfLight);
}
public ElectricLamp(float widthInMm, float lengthInMm, float powerOfLightningInWatts,
int warrantyPeriodOfWorkInDays, String producingCountry, String materials, String typeOfLamp,
String typeOfLight) {
resetValues(widthInMm, lengthInMm, powerOfLightningInWatts, warrantyPeriodOfWorkInDays, producingCountry,
materials, typeOfLamp, typeOfLight);
}
public void resetValues(float widthInMm, float lengthInMm, float powerOfLightningInWatts,
int warrantyPeriodOfWorkInDays, String producingCountry, String materials, String typeOfLamp,
String typeOfLight) {
this.widthInMm = widthInMm;
this.lengthInMm = lengthInMm;
this.powerOfLightningInWatts = powerOfLightningInWatts;
this.warrantyPeriodOfWorkInDays = warrantyPeriodOfWorkInDays;
this.producingCountry = producingCountry;
this.materials = materials;
this.typeOfLamp = typeOfLamp;
this.typeOfLight = typeOfLight;
}
public static String getCompanyProducer() {
return companyProducer;
}
public static void setCompanyProducer(String companyProducer) {
ElectricLamp.companyProducer = companyProducer;
}
public float getWidthInMm() {
return widthInMm;
}
public void setWidthInMm(float widthInMm) {
this.widthInMm = widthInMm;
}
public float getLengthInMm() {
return lengthInMm;
}
public void setLengthInMm(float lengthInMm) {
this.lengthInMm = lengthInMm;
}
public float getPowerOfLightningInWatts() {
return powerOfLightningInWatts;
}
public void setPowerOfLightningInWatts(float powerOfLightningInWatts) {
this.powerOfLightningInWatts = powerOfLightningInWatts;
}
public int getWarrantyPeriodOfWorkInDays() {
return warrantyPeriodOfWorkInDays;
}
public void setWarrantyPeriodOfWorkInDays(int warrantyPeriodOfWorkInDays) {
this.warrantyPeriodOfWorkInDays = warrantyPeriodOfWorkInDays;
}
public String getProducingCountry() {
return producingCountry;
}
public void setProducingCountry(String producingCountry) {
this.producingCountry = producingCountry;
}
public String getMaterials() {
return materials;
}
public void setMaterials(String materials) {
this.materials = materials;
}
public String getTypeOfLamp() {
return typeOfLamp;
}
public void setTypeOfLamp(String typeOfLamp) {
this.typeOfLamp = typeOfLamp;
}
public String getTypeOfLight() {
return typeOfLight;
}
public void setTypeOfLight(String typeOfLight) {
this.typeOfLight = typeOfLight;
}
@Override
public String toString() {
return "ElectricLamp{" + "widthInMm=" + widthInMm + ", lengthInMm=" + lengthInMm + ", powerOfLightningInWatts="
+ powerOfLightningInWatts + ", warrantyPeriodOfWorkInDays=" + warrantyPeriodOfWorkInDays
+ ", producingCountry='" + producingCountry + '\'' + ", material='" + materials + '\''
+ ", typeOfLamp='" + typeOfLamp + '\'' + ", typeOfLight='" + typeOfLight + '\'' + '}';
}
}
|
package com.av.acciones.usuario;
import org.apache.log4j.Logger;
import com.av.acciones.BaseAccion;
import com.av.db.layer.interfaces.UsuarioLayer;
import com.av.exceptions.AvException;
import com.av.rmi.Parametro;
import com.av.rmi.Parametro.Tipo;
/**
* Accion que obtiene todos los usuarios activos registrados en la base de datos
* configurada
*
* @author Victor J Morales R
*
*/
public class ObtenerActivosAccion extends BaseAccion {
private static Logger log = Logger.getLogger(ObtenerTodosAccion.class);
@Override
public Parametro ejecutar(Parametro parametro) throws AvException {
log.info("Inicio - ejecutar(Parametro parametro)");
UsuarioLayer ul = (UsuarioLayer) getBean(UsuarioLayer.BEAN_NAME);
parametro.setValor(Tipo.OUTPUT, ul.obtenerActivos());
log.info("Fin - ejecutar(Parametro parametro)");
return parametro;
}// ejecutar
}// ObtenerActivosAccion
|
package com.commercetools.pspadapter.payone.mapping;
import com.commercetools.pspadapter.BaseTenantPropertyTest;
import com.commercetools.pspadapter.payone.config.PayoneConfig;
import com.commercetools.pspadapter.payone.domain.ctp.PaymentWithCartLike;
import com.commercetools.pspadapter.payone.domain.payone.model.common.PayoneRequest;
import com.commercetools.pspadapter.payone.domain.payone.model.creditcard.CreditCardPayoneRequest;
import com.neovisionaries.i18n.CountryCode;
import io.sphere.sdk.carts.CartLike;
import io.sphere.sdk.customers.Customer;
import io.sphere.sdk.models.Address;
import io.sphere.sdk.models.Reference;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.types.CustomFields;
import org.assertj.core.api.SoftAssertions;
import org.javamoney.moneta.Money;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import util.PaymentTestHelper;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Optional;
import static com.commercetools.pspadapter.payone.domain.ctp.paymentmethods.MethodKeys.CREDIT_CARD;
import static com.commercetools.pspadapter.payone.domain.ctp.paymentmethods.MethodKeys.WALLET_PAYPAL;
import static com.commercetools.pspadapter.payone.mapping.CustomFieldKeys.GENDER_FIELD;
import static com.commercetools.pspadapter.payone.mapping.CustomFieldKeys.LANGUAGE_CODE_FIELD;
import static com.commercetools.pspadapter.payone.mapping.MappingUtil.getPaymentLanguage;
import static com.neovisionaries.i18n.CountryCode.*;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author fhaertig
* @since 18.01.16
*/
@RunWith(MockitoJUnitRunner.class)
public class MappingUtilTest extends BaseTenantPropertyTest {
private SoftAssertions softly;
@Mock(lenient = true)
private Customer customer;
@Mock
private PaymentWithCartLike paymentWithCartLike;
@Mock
private Payment payment;
@Mock
private CustomFields customFields;
@Mock
private CartLike cartLike;
@Before
public void setUp() throws Exception {
super.setUp();
final PaymentTestHelper payments = new PaymentTestHelper();
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(payments.dummyOrderMapToPayoneRequest());
softly = new SoftAssertions();
}
@Test
public void testCountryStateMapping() {
Address addressDE = Address.of(DE)
.withState("AK");
Address addressUS = Address.of(CountryCode.US)
.withState("AK");
CreditCardPayoneRequest authorizationRequestDE =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
CreditCardPayoneRequest authorizationRequestUS =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapBillingAddressToRequest(authorizationRequestDE, addressDE);
MappingUtil.mapShippingAddressToRequest(authorizationRequestDE, addressDE, CREDIT_CARD);
MappingUtil.mapBillingAddressToRequest(authorizationRequestUS, addressUS);
MappingUtil.mapShippingAddressToRequest(authorizationRequestUS, addressUS, CREDIT_CARD);
softly.assertThat(authorizationRequestDE.getState()).as("DE billing address state").isNullOrEmpty();
softly.assertThat(authorizationRequestDE.getShipping_state()).as("DE shipping address state").isNullOrEmpty();
softly.assertThat(authorizationRequestUS.getState()).as("US billing address state").isEqualTo("AK");
softly.assertThat(authorizationRequestUS.getShipping_state()).as("US shipping address state").isEqualTo("AK");
softly.assertAll();
}
@Test
public void streetJoiningFull() {
Address addressWithNameNumber = Address.of(DE)
.withStreetName("Test Street")
.withStreetNumber("2");
CreditCardPayoneRequest authorizationRequestWithNameNumber =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapBillingAddressToRequest(authorizationRequestWithNameNumber, addressWithNameNumber);
MappingUtil.mapShippingAddressToRequest(authorizationRequestWithNameNumber, addressWithNameNumber, CREDIT_CARD);
softly.assertThat(authorizationRequestWithNameNumber.getStreet()).as("billing address state").isEqualTo(addressWithNameNumber.getStreetName() + " " + addressWithNameNumber.getStreetNumber());
softly.assertThat(authorizationRequestWithNameNumber.getShipping_street()).as("shipping address state").isEqualTo(addressWithNameNumber.getStreetName() + " " + addressWithNameNumber.getStreetNumber());
softly.assertAll();
}
@Test
public void streetJoiningNoNumber() {
Address addressNoNumber = Address.of(DE)
.withStreetName("Test Street");
CreditCardPayoneRequest authorizationRequestNoNumber =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapBillingAddressToRequest(authorizationRequestNoNumber, addressNoNumber);
MappingUtil.mapShippingAddressToRequest(authorizationRequestNoNumber, addressNoNumber, CREDIT_CARD);
softly.assertThat(authorizationRequestNoNumber.getStreet()).as("billing address state").isEqualTo(addressNoNumber.getStreetName());
softly.assertThat(authorizationRequestNoNumber.getShipping_street()).as("shipping address state").isEqualTo(addressNoNumber.getStreetName());
softly.assertAll();
}
@Test
public void streetJoiningNoName() {
Address addressNoName = Address.of(DE)
.withStreetNumber("5");
CreditCardPayoneRequest authorizationRequestNoName =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapBillingAddressToRequest(authorizationRequestNoName, addressNoName);
MappingUtil.mapShippingAddressToRequest(authorizationRequestNoName, addressNoName, CREDIT_CARD);
softly.assertThat(authorizationRequestNoName.getStreet()).as("DE billing address state").isEqualTo("5");
softly.assertThat(authorizationRequestNoName.getShipping_street()).as("DE shipping address state").isEqualTo(
"5");
softly.assertAll();
}
@Test(expected = IllegalArgumentException.class)
public void WhenNoShippingAddressThrowException() {
CreditCardPayoneRequest authorizationRequestNoName =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapShippingAddressToRequest(authorizationRequestNoName, null, CREDIT_CARD);
}
@Test
public void WhenShippingAddressIsNullReturnOneToSetValueForNoShipping() {
assertThat(MappingUtil.checkForMissingShippingAddress(null)).isEqualTo(1);
}
@Test
public void WhenMissingShippingAddressReturnOneToSetValueForNoShipping() {
Address missingAddressFields = Address.of(DE)
.withStreetName("Test Street");
assertThat(MappingUtil.checkForMissingShippingAddress(missingAddressFields)).isEqualTo(1);
}
@Test
public void WhenShippingAddressIsPresentReturnZeroToSetValueForNoShipping() {
Address missingAddressFields = Address.of(DE)
.withPostalCode("123")
.withStreetNumber("5")
.withStreetName("Test Street")
.withCity("Test city");
assertThat(MappingUtil.checkForMissingShippingAddress(missingAddressFields)).isEqualTo(0);
}
@Test
public void WhenWalletPaymentAndNoShippingAddressShouldNotThrowException() {
CreditCardPayoneRequest authorizationRequest =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapShippingAddressToRequest(authorizationRequest, null, WALLET_PAYPAL);
assertThat(authorizationRequest.getShipping_country()).isEqualTo(null);
}
@Test
public void customerNumberDefault() {
when(customer.getCustomerNumber()).thenReturn("01234567890123456789");
Reference<Customer> customerReference = Reference.of(Customer.referenceTypeId(), customer);
CreditCardPayoneRequest authorizationRequest =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapCustomerToRequest(authorizationRequest, customerReference);
assertThat(authorizationRequest.getCustomerid()).isEqualTo("01234567890123456789");
}
@Test
public void customerNumberExceedsLength() {
when(customer.getCustomerNumber()).thenReturn("01234567890123456789123456789");
when(customer.getId()).thenReturn("276829bd-6fa3-450f-9e2a-9a8715a9a104");
Reference<Customer> customerReference = Reference.of(Customer.referenceTypeId(), customer);
CreditCardPayoneRequest authorizationRequest =
new CreditCardPayoneRequest(new PayoneConfig(tenantPropertyProvider), "000123",
paymentWithCartLike);
MappingUtil.mapCustomerToRequest(authorizationRequest, customerReference);
assertThat(authorizationRequest.getCustomerid()).isEqualTo("276829bd6fa3450f9e2a");
}
@Test
public void getPaymentLanguageTest() {
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(mock(CartLike.class));
// base cases: null arguments
softly.assertThat(getPaymentLanguage(null).isPresent()).isFalse();
softly.assertThat(getPaymentLanguage(paymentWithCartLike).isPresent()).isFalse();
// add properties to payment object one-by-one till valid customFields.getFieldAsString(LANGUAGE_CODE_FIELD)
when(paymentWithCartLike.getPayment()).thenReturn(payment);
softly.assertThat(getPaymentLanguage(paymentWithCartLike)).isEmpty();
when(payment.getCustom()).thenReturn(customFields);
softly.assertThat(getPaymentLanguage(paymentWithCartLike)).isEmpty();
when(customFields.getFieldAsString(LANGUAGE_CODE_FIELD)).thenReturn("nl");
softly.assertThat(getPaymentLanguage(paymentWithCartLike)).hasValue("nl");
// now set flush payment object to null - fetch language from cartLike
// set properties one-by-one till locale.getLanguage()
when(paymentWithCartLike.getPayment()).thenReturn(null);
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(cartLike);
softly.assertThat(getPaymentLanguage(paymentWithCartLike)).isEmpty();
Locale locale = new Locale("xx");
when(cartLike.getLocale()).thenReturn(locale);
softly.assertThat(getPaymentLanguage(paymentWithCartLike)).hasValue("xx");
// if both payment and cartLike set - payment value should privilege
when(paymentWithCartLike.getPayment()).thenReturn(payment);
softly.assertThat(getPaymentLanguage(paymentWithCartLike)).hasValue("nl");
// but as soon as payment reference doesn't have proper language at the end -
// cartLike language should be fetched
when(customFields.getFieldAsString(LANGUAGE_CODE_FIELD)).thenReturn(null);
Optional<String> paymentLanguage = getPaymentLanguage(paymentWithCartLike);
softly.assertThat(paymentLanguage).hasValue("xx");
softly.assertAll();
}
@Test
public void getPaymentLanguageTagOrFallback() throws Exception {
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(mock(CartLike.class));
// base cases: null arguments
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(null)).isEqualTo("en");
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("en");
// add properties to payment object one-by-one till valid customFields.getFieldAsString(LANGUAGE_CODE_FIELD)
when(paymentWithCartLike.getPayment()).thenReturn(payment);
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("en");
when(payment.getCustom()).thenReturn(customFields);
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("en");
when(customFields.getFieldAsString(LANGUAGE_CODE_FIELD)).thenReturn("nl");
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("nl");
// now set flush payment object to null - fetch language from cartLike
// set properties one-by-one till locale.getLanguage()
when(paymentWithCartLike.getPayment()).thenReturn(null);
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(cartLike);
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("en");
Locale locale = new Locale("xx");
when(cartLike.getLocale()).thenReturn(locale);
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("xx");
// if both payment and cartLike set - payment value should privilege
when(paymentWithCartLike.getPayment()).thenReturn(payment);
softly.assertThat(MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike)).isEqualTo("nl");
// but as soon as payment reference doesn't have proper language at the end -
// cartLike language should be fetched
when(customFields.getFieldAsString(LANGUAGE_CODE_FIELD)).thenReturn(null);
String paymentLanguage = MappingUtil.getPaymentLanguageTagOrFallback(paymentWithCartLike);
softly.assertThat(paymentLanguage).isEqualTo("xx");
softly.assertAll();
}
@Test
public void mapAmountPlannedFromPayment_withoutPrice() throws Exception {
PayoneRequest request = new PayoneRequestImplTest(new PayoneConfig(tenantPropertyProvider),
"testReqType", "testClearType");
when(payment.getAmountPlanned()).thenReturn(null);
MappingUtil.mapAmountPlannedFromPayment(request, payment);
assertThat(request.getAmount()).isEqualTo(0);
assertThat(request.getCurrency()).isNull();
}
@Test
public void mapAmountPlannedFromPayment_withPrice() throws Exception {
PayoneRequest request = new PayoneRequestImplTest(new PayoneConfig(tenantPropertyProvider),
"testReqType", "testClearType");
when(payment.getAmountPlanned()).thenReturn(Money.of(18, "EUR"));
MappingUtil.mapAmountPlannedFromPayment(request, payment);
assertThat(request.getAmount()).isEqualTo(1800);
assertThat(request.getCurrency()).isEqualTo("EUR");
}
@Test
public void getGenderFromPaymentCart() throws Exception {
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(cartLike);
when(paymentWithCartLike.getPayment()).thenReturn(payment);
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).isEmpty();
CustomFields cartCustomFields = mock(CustomFields.class);
when(cartCustomFields.getFieldAsString(GENDER_FIELD)).thenReturn("cartGender");
CustomFields paymentCustomFields = mock(CustomFields.class);
when(paymentCustomFields.getFieldAsString(GENDER_FIELD)).thenReturn("paymentGender");
CustomFields customerCustomFields = mock(CustomFields.class);
when(customerCustomFields.getFieldAsString(GENDER_FIELD)).thenReturn("USER_GENDER");
cartLike = Mockito.mock(CartLike.class);
when(cartLike.getCustom()).thenReturn(cartCustomFields);
when(payment.getCustom()).thenReturn(paymentCustomFields);
Reference<Customer> of = Reference.of("test-id", customer);
when(payment.getCustomer()).thenReturn(of);
when(customer.getCustom()).thenReturn(customerCustomFields);
when((CartLike) paymentWithCartLike.getCartLike()).thenReturn(cartLike);
// payment custom field in the result
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).hasValue("p");
// cart custom field in the result
when(payment.getCustom()).thenReturn(null);
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).hasValue("c");
// customer custom field in the result
when(cartCustomFields.getFieldAsString(GENDER_FIELD)).thenReturn(null);
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).hasValue("u");
// don't fail is cartLike.getCustom() is not set
when(cartLike.getCustom()).thenReturn(null);
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).hasValue("u");
// empty if everything is empty
when(customerCustomFields.getFieldAsString(GENDER_FIELD)).thenReturn(null);
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).isEmpty();
// custom field is set, but customer#getCustom() is null
Mockito.lenient().when(customerCustomFields.getFieldAsString(GENDER_FIELD)).thenReturn("XXX");
Mockito.lenient().when(customer.getCustom()).thenReturn(null);
softly.assertThat(MappingUtil.getGenderFromPaymentCart(paymentWithCartLike)).isEmpty();
softly.assertAll();
}
@Test
public void dateToBirthdayString_converting() throws Exception {
assertThat(MappingUtil.dateToBirthdayString(null)).isNull();
assertThat(MappingUtil.dateToBirthdayString(LocalDate.of(1986, 12, 15))).isEqualTo("19861215");
assertThat(MappingUtil.dateToBirthdayString(LocalDate.of(1915, 1, 2))).isEqualTo("19150102");
}
@Test
public void getFirstValueFromAddresses() throws Exception {
assertThat(MappingUtil.getFirstValueFromAddresses(emptyList(), Address::getEmail))
.isEmpty();
assertThat(MappingUtil.getFirstValueFromAddresses(singletonList(Address.of(CH)), Address::getCountry))
.contains(CH);
assertThat(MappingUtil.getFirstValueFromAddresses(asList(Address.of(DE), Address.of(NL)), Address::getCountry))
.contains(DE);
assertThat(MappingUtil.getFirstValueFromAddresses(asList(Address.of(AL).withCompany("xxx"),
Address.of(NL).withCompany("ggg")), Address::getCompany))
.contains("xxx");
assertThat(MappingUtil.getFirstValueFromAddresses(asList(Address.of(AL).withCompany("xxx").withEmail("TTT"),
Address.of(NL).withCompany("ggg").withEmail("KKK")), Address::getPhone))
.isEmpty();
assertThat(MappingUtil.getFirstValueFromAddresses(asList(Address.of(AL).withCompany("xxx").withEmail("TTT"),
Address.of(NL).withCompany("ggg").withEmail("KKK")), Address::getEmail))
.contains("TTT");
assertThat(MappingUtil.getFirstValueFromAddresses(asList(null,
Address.of(NL).withCompany("ggg").withEmail("KKK")), Address::getEmail))
.contains("KKK");
}
/**
* Simple implementation for tests.
*/
private class PayoneRequestImplTest extends PayoneRequest {
protected PayoneRequestImplTest(PayoneConfig config, String requestType, String clearingtype) {
super(config, requestType, clearingtype);
}
}
}
|
package br.com.helpdev.quaklog.parser.impl;
import br.com.helpdev.quaklog.processor.parser.GameParserException;
import br.com.helpdev.quaklog.processor.parser.impl.ShutdownGameParser;
import br.com.helpdev.quaklog.processor.parser.objects.ShutdownGameObParser;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ShutdownGameParserTest {
private final ShutdownGameParser parser = new ShutdownGameParser();
private enum ShutdownGame {
FIRST(" 0:25 ShutdownGame: ", "0:25"),
SECOND(" 10:25 ShutdownGame: ", "10:25"),
THIRD("100:25 ShutdownGame: ", "100:25"),
FOURTH(" 5:25 ShutdownGame: ", "5:25");
String line;
String expectedTime;
ShutdownGame(String line, String expectedTime) {
this.line = line;
this.expectedTime = expectedTime;
}
}
@Test
void shouldThrowGameParseExceptionWhenParseInvalidFormat() {
assertThrows(GameParserException.class, () -> parser.parse("abc abc abc"));
}
@Test
void parseClientBeginWithSuccess() {
assertTrue(Arrays.stream(ShutdownGame.values()).allMatch(this::assertParse));
}
private boolean assertParse(ShutdownGame valueToParse) {
ShutdownGameObParser parse = parse(valueToParse.line);
return parse.getGameTime().equals(valueToParse.expectedTime);
}
private ShutdownGameObParser parse(String value) {
try {
return parser.parse(value);
} catch (GameParserException e) {
throw new RuntimeException(e);
}
}
}
|
package net.minecraftforge.common.property;
public interface IUnlistedProperty<V> {
String getName();
boolean isValid(V paramV);
Class<V> getType();
String valueToString(V paramV);
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraftforge\common\property\IUnlistedProperty.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package br.usp.ffclrp.dcm.lssb.transformation_software.rulesprocessing;
public class FlagFixedContent extends Flag{
private String content;
public FlagFixedContent(String content){
this.content = content;
}
public String getContent(){
return content;
}
}
|
package com.company;
import java.util.Map;
public interface Pieces {
void createNewPieces(GameBoard myBoard);
boolean moveSyntaxOK(String move);
boolean makeMove(String move, String color);
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package rmichatserver;
/**
*
* @author mohammad
*/
public class UserAccount
{
private String userName;
private String Password;
private String FirstName;
private String LastName;
public UserAccount()
{
}
public UserAccount(String userName, String Password, String FirstName, String LastName)
{
this.userName = userName;
this.Password = Password;
this.FirstName = FirstName;
this.LastName = LastName;
}
public UserAccount(String userName, String Password)
{
this.userName = userName;
this.Password = Password;
}
/**
* @return the Email
*/
public String getuserName() {
return userName;
}
/**
* @param Email the Email to set
*/
public void setuserName(String Email) {
this.userName = Email;
}
/**
* @return the Password
*/
public String getPassword() {
return Password;
}
/**
* @param Password the Password to set
*/
public void setPassword(String Password) {
this.Password = Password;
}
/**
* @return the FirstName
*/
public String getFirstName() {
return FirstName;
}
/**
* @param FirstName the FirstName to set
*/
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
/**
* @return the LastName
*/
public String getLastName() {
return LastName;
}
/**
* @param LastName the LastName to set
*/
public void setLastName(String LastName) {
this.LastName = LastName;
}
@Override
public String toString()
{
return userName;
}
@Override
public boolean equals(Object obj)
{
if((this.userName.equals(((UserAccount)obj).getuserName())))
return true;
return false;
}
}
|
package algorithms.mdp;
import java.util.HashMap;
import learning.*;
import problems.maze.MazeProblemMDP;
public class PolicyIteration extends LearningAlgorithm {
/**
* Max delta. Controls convergence.
*/
private double maxDelta = 0.01;
/**
* Learns the policy (notice that this method is protected, and called from the public method learnPolicy(LearningProblem problem, double gamma) in LearningAlgorithm.
*/
@Override
protected void learnPolicy() {
if (!(problem instanceof MDPLearningProblem)) {
System.out.println("The algorithm PolicyIteration can not be applied to this problem (model is not visible).");
System.exit(0);
}
// Initializes the policy randomly
solution = new Policy();
Policy policyAux = new Policy();
MazeProblemMDP problemMDP = (MazeProblemMDP) this.problem;
HashMap<State, Double> utilities;
/* Sets a random policy for each non-final state */
for (State state : problemMDP.getAllStates()) {
if (!problemMDP.isFinal(state)) {
policyAux.setAction(state, problemMDP.randomAction(state));
}
}
// Main loop of the policy iteration.
/* While the new policy is not the same as the previous policy, iterate */
do {
solution = policyAux;
utilities = this.policyEvaluation(solution);
policyAux = this.policyImprovement(utilities);
} while (!solution.equals(policyAux));
}
/**
* Policy evaluation. Calculates the utility given the policy
*/
private HashMap<State, Double> policyEvaluation(Policy policy) {
// Initializes utilities. In case of terminal states, the utility corresponds to
// the reward. In the remaining (most) states, utilities are zero.
HashMap<State, Double> utilities = new HashMap<State, Double>();
HashMap<State, Double> currentUtilities;
MDPLearningProblem problemMDP = (MDPLearningProblem) this.problem;
double delta = 0;
/* Iterates through all the posible states,.. */
for (State state : problemMDP.getAllStates()) {
if (!problemMDP.isFinal(state)) {
utilities.put(state, (double) 0); // assigning 0 to all the non final states
} else {
utilities.put(state, problemMDP.getReward(state)); // or the corresponding reward -100/100 in case of a final state
}
}
do {
delta = 0;
currentUtilities = new HashMap<State, Double>();
for (State state : problemMDP.getAllStates()) {
if (problemMDP.isFinal(state)) {
currentUtilities.put(state, problemMDP.getReward(state));
} else{
/* Calculates the expected utilty for that action */
double expectedUtility = problemMDP.getExpectedUtility(state, policy.getAction(state), utilities, problemMDP.gamma);
/* Obtains the new utility and updates it*/
double newUtility = problemMDP.getReward(state) + problemMDP.gamma * expectedUtility;
currentUtilities.put(state, newUtility); // Introduces it into the set of new utilities
/* Updates delta */
if (Math.abs(currentUtilities.get(state) - utilities.get(state)) > delta) {
delta = Math.abs(currentUtilities.get(state) - utilities.get(state));
}
}
}
utilities = currentUtilities;
} while (delta >= maxDelta);
return utilities;
}
/**
* Improves the policy given the utility
*/
private Policy policyImprovement(HashMap<State, Double> utilities) {
// Creates the new policy
Policy newPolicy = new Policy();
MDPLearningProblem problemMDP = (MDPLearningProblem) this.problem;
/* Iterates through each state to find their optimal policies */
for (State state : problemMDP.getAllStates()) {
if (!problemMDP.isFinal(state)) {
Action optimalAction = null;
double expectedUtility = Double.NEGATIVE_INFINITY;
for (Action action : problemMDP.getPossibleActions(state)) {
if (problemMDP.getExpectedUtility(state, action, utilities, problemMDP.gamma) > expectedUtility) {
expectedUtility = problemMDP.getExpectedUtility(state, action, utilities, problemMDP.gamma);
optimalAction = action;
}
}
newPolicy.setAction(state, optimalAction);
}
}
return newPolicy;
}
/**
* Sets the parameters of the algorithm.
*/
@Override
public void setParams(String[] args) {
// In this case, there is only one parameter (maxDelta).
if (args.length > 0) {
try {
maxDelta = Double.parseDouble(args[0]);
} catch (Exception e) {
System.out.println("The value for maxDelta is not correct. Using 0.01.");
}
}
}
/**
* Prints the results
*/
public void printResults() {
System.out.println("Policy Iteration");
// Prints the policy
System.out.println("\nOptimal policy");
System.out.println(solution);
}
/**
* Main function. Allows testing the algorithm with MDPExProblem
*/
public static void main(String[] args) {
LearningProblem mdp = new problems.mdpexample2.MDPExProblem();
mdp.setParams(null);
PolicyIteration pi = new PolicyIteration();
pi.setProblem(mdp);
pi.learnPolicy(mdp);
pi.printResults();
}
}
|
execute(des, src, registers, memory) {
Calculator calculator = new Calculator(registers, memory);
int desSize = 0;
int srcSize = 0;
if( des.isRegister() ) {
desSize = registers.getBitSize(des);
}
if( src.isRegister() ) {
srcSize = registers.getBitSize(src);
}
if( des.isRegister() && checkSizeOfRegister(registers, desSize) ) {
if( src.isRegister() ) {
if( desSize == srcSize ) {
String source = calculator.hexToBinaryString(registers.get(src), src);
String destination = calculator.hexToBinaryString(registers.get(des), des);
storeResultToRegister(registers, calculator, des, source, destination);
} else {
//throw exception
}
}
else if( src.isMemory() ) {
String source = calculator.hexToBinaryString(memory.read(src, desSize), src);
String destination = calculator.hexToBinaryString(registers.get(des), des);
storeResultToRegister(registers, calculator, des, source, destination);
}
}
else {
//throw exception
}
}
storeResultToRegister(registers, calculator, des, source, destination) {
BigInteger biSrc = new BigInteger(source, 2);
BigInteger biDes = new BigInteger(destination, 2);
BigInteger biResult = biDes.and(biSrc);
registers.set(des, calculator.binaryToHexString(biResult.toString(2), des));
}
boolean checkSizeOfRegister(registers, desSize) {
boolean checkSize = false;
if( 128 == desSize ) {
checkSize = true;
}
return checkSize;
}
|
package org.springframework.boot.logging.log4j2;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith;
/**
* Tests for {@link WhitespaceThrowablePatternConverter}.
*
* @author Vladimir Tsanev
*/
public class WhitespaceThrowablePatternConverterTests {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
private final WhitespaceThrowablePatternConverter converter = WhitespaceThrowablePatternConverter
.newInstance(new String[] {});
@Test
public void noStackTrace() throws Exception {
LogEvent event = Log4jLogEvent.newBuilder().build();
StringBuilder builder = new StringBuilder();
this.converter.format(event, builder);
assertThat(builder.toString(), equalTo(""));
}
@Test
public void withStackTrace() throws Exception {
LogEvent event = Log4jLogEvent.newBuilder().setThrown(new Exception()).build();
StringBuilder builder = new StringBuilder();
this.converter.format(event, builder);
assertThat(builder.toString(), startsWith(LINE_SEPARATOR));
assertThat(builder.toString(), endsWith(LINE_SEPARATOR));
}
}
|
package com.thoughtworks.shoppingwizard.product_detail;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.thoughtworks.presentation.PresentationError;
import com.thoughtworks.presentation.product_detail.ProductDetailModel;
import com.thoughtworks.presentation.product_detail.ProductDetailPresenter;
import com.thoughtworks.presentation.product_detail.ProductDetailUI;
import com.thoughtworks.shoppingwizard.BaseFragment;
import com.thoughtworks.shoppingwizard.ImageLoader;
import com.thoughtworks.shoppingwizard.Navigator;
import com.thoughtworks.shoppingwizard.R;
import java.lang.ref.WeakReference;
/**
* Created on 14-06-2018.
*/
public class ProductDetailFragment
extends BaseFragment implements ProductDetailUI {
private static final String KEY_PROD_ID = "KEY_PROD_ID";
private static final int INVALID_ID = -1;
private ProductDetailPresenter mProductDetailPresenter;
private TextView mTextViewProductName;
private TextView mTextViewProductPrice;
private ImageView mImageViewProduct;
@Nullable
@Override
public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.layout_product_detail, container, false);
mProductDetailPresenter = ProductDetailPresenter.newInstance();
setupView(view);
return view;
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.cart_menu, menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (item.getItemId() == R.id.show_cart) {
mProductDetailPresenter.onShowCartClicked();
}
return super.onOptionsItemSelected(item);
}
private void setupView(final View view) {
setHasOptionsMenu(true);
mTextViewProductName = view.findViewById(R.id.product_item_name);
mTextViewProductPrice = view.findViewById(R.id.product_item_price);
mImageViewProduct = view.findViewById(R.id.product_img_url);
view.findViewById(R.id.product_detail_action_add_to_cart)
.setOnClickListener(new AddToCartListener());
}
@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mProductDetailPresenter.onUiCreated(this);
mProductDetailPresenter.loadDataForProductId(getProdIdFromArg());
}
private int getProdIdFromArg() {
return getArguments() == null
? INVALID_ID
: getArguments().getInt(KEY_PROD_ID, INVALID_ID);
}
@Override
public void renderProductDetail(final ProductDetailModel data) {
mTextViewProductName.setText(data.getName());
mTextViewProductPrice.setText(data.getPrice());
ImageLoader.loadImage(mImageViewProduct,
data.getProdImgUrl());
}
@Override
public void renderError(final PresentationError error) {
}
@Override
public void showCartDetailUi() {
Navigator.navigateToCartDetail(mContext);
}
static Fragment newInstance(final int productId) {
final Fragment fragment = new ProductDetailFragment();
final Bundle args = new Bundle();
args.putInt(KEY_PROD_ID, productId);
fragment.setArguments(args);
return fragment;
}
@Override
public WeakReference<Context> getContextRef() {
return new WeakReference<>(getContext());
}
private class AddToCartListener implements View.OnClickListener {
@Override
public void onClick(final View v) {
if (mProductDetailPresenter != null) {
mProductDetailPresenter.onAddToCartClicked(getProdIdFromArg());
}
}
}
}
|
package org.star.uml.designer.ui.action;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.workspace.util.WorkspaceSynchronizer;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramEditPart;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDiagramDocument;
import org.eclipse.gmf.runtime.diagram.ui.resources.editor.parts.DiagramDocumentEditor;
import org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand;
import org.eclipse.gmf.runtime.emf.core.util.EObjectAdapter;
import org.eclipse.gmf.runtime.emf.type.core.MetamodelType;
import org.eclipse.gmf.runtime.emf.type.core.requests.CreateElementRequest;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.runtime.notation.impl.DiagramImpl;
import org.eclipse.gmf.runtime.notation.impl.ShapeImpl;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.uml2.diagram.usecase.edit.helpers.UMLBaseEditHelper;
import org.eclipse.uml2.diagram.usecase.navigator.UMLNavigatorItem;
import org.eclipse.uml2.uml.UMLFactory;
import org.eclipse.uml2.uml.VisibilityKind;
import org.eclipse.uml2.uml.internal.impl.ActorImpl;
import org.eclipse.uml2.uml.internal.impl.PackageImpl;
import org.eclipse.uml2.uml.internal.impl.UMLFactoryImpl;
import org.osgi.framework.Bundle;
import org.star.uml.designer.Activator;
import org.star.uml.designer.base.constance.GlobalConstants;
import org.star.uml.designer.base.utils.CommonUtil;
import org.star.uml.designer.base.utils.EclipseUtile;
import org.star.uml.designer.ui.diagram.action.interfaces.IStarUMLModelAction;
import org.star.uml.designer.ui.factory.StarUMLCommandFactory;
import org.star.uml.designer.ui.factory.StarUMLEditHelperFactory;
import org.star.uml.designer.ui.views.StarPMSModelView;
import org.star.uml.designer.ui.views.StarPMSModelViewUtil;
import org.star.uml.designer.ui.views.StarPMSModelView.TreeObject;
import org.star.uml.designer.ui.views.StarPMSModelView.TreeParent;
public class RefactorRenameAction extends Action{
public static final String ACTION_ID = "REFACTOR_RENAME";
public static final String ACTION_URI = "org.star.uml.designer.ui.action.RefactorRenameAction";
public static final String ACTION_TITLE ="Rename";
public static final String ICON_PATH = "/icons/login.gif";
public RefactorRenameAction() {
super();
this.setText(ACTION_TITLE);
this.setImageDescriptor(getImageDescriptor());
}
@Override
public void run() {
System.out.println("Rename");
}
public URL getImageURL(){
Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
return bundle.getEntry(ICON_PATH);
}
public ImageDescriptor getImageDescriptor(){
return Activator.getImageDescriptor(ICON_PATH);
}
}
|
public class TestSeries {
//test method
public static void main(String[] args) {
AbstractSeries sn;
double[] tuple;
sn = new Arithmetic();
System.out.println("The first five terms of the arithmetic series are:");
for (int n=0; n<5; n++) {
System.out.println(sn.next());
}
sn = new Geometric();
System.out.println();
System.out.println("The first five terms of the geometric series are:");
tuple = sn.take(5);
for (int n=0; n<5; n++) {
System.out.println(tuple[n]);
}
}
}
|
package com.tencent.mm.plugin.exdevice.ui;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
class a$2 implements OnClickListener {
final /* synthetic */ String dMs;
final /* synthetic */ a iDD;
a$2(a aVar, String str) {
this.iDD = aVar;
this.dMs = str;
}
public final void onClick(View view) {
Context b = a.b(this.iDD);
Intent intent = new Intent(b, ExdeviceProfileUI.class);
intent.putExtra("username", this.dMs);
b.startActivity(intent);
}
}
|
package com.philippe.app.domain;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
@Getter @Setter
public class LoadFullSupply {
public static final String EVENT_TYPE = "FULL_SUPPLY";
private String fileLocationGB;
private String fileLocationISL;
private String source;
private LocalDate extractionDate;
private Boolean initiateNextJob;
}
|
package com.ab.yuri.aifuwu.gson;
import java.util.List;
/**
* Created by Yuri on 2017/1/26.
*/
public class WeatherNow {
/**
* basic : {"city":"南京","cnty":"中国","id":"CN101190101","lat":"32.048000","lon":"118.769000","update":{"loc":"2017-01-26 18:57","utc":"2017-01-26 10:57"}}
* now : {"cond":{"code":"101","txt":"多云"},"fl":"8","hum":"52","pcpn":"0","pres":"1024","tmp":"12","vis":"5","wind":{"deg":"160","dir":"南风","sc":"3-4","spd":"10"}}
* status : ok
*/
public BasicBean basic;
public NowBean now;
public String status;
public static class BasicBean {
/**
* city : 南京
* cnty : 中国
* id : CN101190101
* lat : 32.048000
* lon : 118.769000
* update : {"loc":"2017-01-26 18:57","utc":"2017-01-26 10:57"}
*/
public String id;
public UpdateBean update;
public static class UpdateBean {
/**
* loc : 2017-01-26 18:57
* utc : 2017-01-26 10:57
*/
public String loc;
}
}
public static class NowBean {
/**
* cond : {"code":"101","txt":"多云"}
* fl : 8
* hum : 52
* pcpn : 0
* pres : 1024
* tmp : 12
* vis : 5
* wind : {"deg":"160","dir":"南风","sc":"3-4","spd":"10"}
*/
public CondBean cond;
public String tmp;
public static class CondBean {
/**
* code : 101
* txt : 多云
*/
public String txt;
}
}
}
|
package com.example.userportal.service;
import com.example.userportal.service.dto.ShoppingCartPositionDTO;
import java.util.List;
public interface ShoppingCartService {
ShoppingCartPositionDTO addPosition(int productId);
ShoppingCartPositionDTO getPosition(int id);
List<ShoppingCartPositionDTO> getAllCurrentCustomerPositions();
ShoppingCartPositionDTO getPosition(int customerId, int productId);
ShoppingCartPositionDTO updatePositionQuantity(int productId, int quantity);
ShoppingCartPositionDTO deletePosition(int productId);
}
|
package collector.event.listener.kafka;
import collector.configuration.EthConfiguration;
import collector.configuration.EthKafkaConfiguration;
import collector.event.EthPendingTxEvent;
import collector.event.EthTxEvent;
import collector.event.publisher.EthPendingTxPublisher;
import collector.event.publisher.EthTransactionPublisher;
import collector.message.kafka.EthKafkaProducer;
import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
/**
* Produce kafka tx messages
*
* @author zacconding
*/
@Slf4j(topic = "listener")
@Component
@ConditionalOnBean(value = {EthConfiguration.class, EthKafkaConfiguration.class})
public class EthTxKafkaProduceListener {
private EthKafkaProducer ethKafkaProducer;
@Autowired
public EthTxKafkaProduceListener(EthKafkaProducer ethKafkaProducer,
EthPendingTxPublisher ethPendingTxPublisher,
EthTransactionPublisher ethTxPublisher) {
this.ethKafkaProducer = ethKafkaProducer;
// register
ethPendingTxPublisher.register(this);
ethTxPublisher.register(this);
}
@Subscribe
@AllowConcurrentEvents
public void onPendingTx(EthPendingTxEvent pendingTxEvent) {
logger.info("## subscribe pending tx event. network : {} / node : {} / hash : {}"
, pendingTxEvent.getNetworkName(), pendingTxEvent.getNodeName(), pendingTxEvent.getPendingTx().getHash());
ethKafkaProducer.produceEthereumPendingTxMessage(pendingTxEvent);
}
@Subscribe
@AllowConcurrentEvents
public void onTransaction(EthTxEvent txEvent) {
logger.info("## subscribe tx event. network : {} / node : {} / hash : {} / status : {}"
, txEvent.getNetworkName(), txEvent.getEthereumNode().getNodeName()
, txEvent.getTransaction().getHash(), txEvent.getTransactionReceipt().getStatus());
ethKafkaProducer.produceEthereumTransactionMessage(txEvent);
}
}
|
package com.survey.search;
import com.survey.model.Survey;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class InformationOnSurveys {
private List<Survey> surveys;
public InformationOnSurveys() {
surveys = new LinkedList<>();
}
@XmlElementWrapper
@XmlAnyElement(lax=true)
public List<Survey> getSurveys() {
return surveys;
}
public void setSurveys(List<Survey> surveys) {
this.surveys = surveys;
}
}
|
package parser.parsertables;
import parser.Token;
import parser.syntax.Rule;
import parser.syntax.Syntax;
import util.UniqueAggregatingHashtable;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
class FirstSets extends UniqueAggregatingHashtable {
public FirstSets(Syntax syntax, Nullable nullAble, List nonterminals)
throws ParserBuildException {
Map done = new Hashtable(nonterminals.size()); // avoid recursion
for (int i = 0; i < nonterminals.size(); i++) {
String nonterm = (String) nonterminals.get(i);
generateFirstSet(syntax, nullAble, nonterm, done);
}
}
private void generateFirstSet(Syntax syntax, Nullable nullAble, String nonterminal, Map done)
throws ParserBuildException {
if (get(nonterminal) != null)
return; // alreay done
if (done.get(nonterminal) != null)
return;
done.put(nonterminal, nonterminal); // avoid endless loops
//System.err.println("generateFirstSet("+nonterminal+")");
for (int k = 0; k < syntax.size(); k++) {
Rule rule = syntax.getRule(k);
String nonterm = rule.getNonterminal(); // left side of derivation
if (nonterminal.equals(nonterm)) { // this rule derives the nonterminal
// if left side is empty, add NULL to FIRST of nonterminal
if (rule.rightSize() <= 0) {
put(nonterm, Nullable.NULL);
} else { // there are symbols on left side
boolean nullable = true; // enable loop until nullable
// While nullable, add the symbol, shift to the next and
// check if it is nullable again.
for (int i = 0; nullable && i < rule.rightSize(); i++) {
String symbol = rule.getRightSymbol(i);
nullable = false; // assume it is a terminal
if (Token.isTerminal(symbol)) {
put(nonterm, symbol);
} else {
// If there is a nonterminal on first position, add its FIRST set
// FIRST set of this nonterminal, but without null-word.
try {
generateFirstSet(syntax, nullAble, symbol, done); // enter recursion
List list = (List) get(symbol); // get the results
for (int j = 0; list != null && j < list.size(); j++) {
String s = (String) list.get(j);
put(nonterm, s);
}
nullable = nullAble.isNullable(symbol);
} catch (Exception ex) {
throw new ParserBuildException(ex.getMessage() + " <- " + nonterm);
}
} // end if terminal
} // end for all symbols of rule
} // end if rule size > 1
} // end for al rules of syntax
}
}
public Object put(Object key, Object value) {
if (key.equals(value))
throw new IllegalArgumentException("Can not be FIRST of its own: key=" + key + ", value=" + value);
return super.put(key, value);
}
public static void main(String[] args) {
// nonterminals
List nonterm = new ArrayList();
nonterm.add("S");
nonterm.add("T");
nonterm.add("F");
nonterm.add("L");
// rules
List sx = new ArrayList();
List r = new ArrayList();
r.add("S");
r.add("T");
r.add("'*'");
r.add("F");
sx.add(r);
r = new ArrayList();
r.add("S");
r.add("T");
sx.add(r);
r = new ArrayList();
r.add("T");
r.add("F");
sx.add(r);
r = new ArrayList();
r.add("F");
sx.add(r);
r = new ArrayList();
r.add("F");
r.add("'1'");
sx.add(r);
Syntax syntax = new Syntax(sx);
try {
FirstSets f = new FirstSets(syntax, new Nullable(syntax, nonterm), nonterm);
String s = "S";
System.err.println("FIRST(" + s + ") = " + f.get(s));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.progoth.synchrochat.shared;
public class InvalidIdentifierException extends Exception
{
private static final long serialVersionUID = 4072771293139310251L;
public InvalidIdentifierException()
{
}
public InvalidIdentifierException(final String aMsg)
{
super(aMsg);
}
}
|
public enum WingAngle {
Wild, Dichaete
}
|
package nl.restaurant.wt.controller;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import nl.restaurant.wt.domein.Klant;
@Component
public interface KlantRepository extends CrudRepository<Klant, Long>{
}
|
package marier.UI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import marier.DB.CustomerDB;
import marier.business.Customer;
import marier.business.CustomerDAO;
import marier.business.*;
import static marier.business.CustomerConstants.emailSize;
import static marier.business.CustomerConstants.firstNameSize;
import static marier.business.CustomerConstants.lastNameSize;
/*
* 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.
*/
/**
*
* @author linma
*/
//Main application page.
public class CustomerMaintApp extends JFrame{
//necessary variables
static CustomerDAO customers;
static JFrame frame = new JFrame();
static JPanel panel = new JPanel();
static JPanel butPanel = new JPanel();
static JButton add = new JButton("Add");
static JButton edit = new JButton("Edit");
static JButton delete = new JButton("Delete");
static JButton help = new JButton("Help");
static JTable table = new JTable();
static JScrollPane scroll = new JScrollPane(table);
/**
*
* @param args
*/
public static void main(String[] args) {
// TODO code application logic here
GUI();
tab();
}
public static void GUI()
{
Dimension d = new Dimension(600,400);
frame.setSize(600, 600);
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(butPanel,BorderLayout.SOUTH);
// frame.setPreferredSize(d);
frame.setMinimumSize(d);
butPanel.add(add);
butPanel.add(edit);
butPanel.add(delete);
butPanel.add(help);
table.setModel(new DefaultTableModel(
new Object[][] {},
new String[] {"Email","First Name","Last Name"}
));
table.setFillsViewportHeight(true);
table.setRowHeight(20);
panel.add(table.getTableHeader());
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll);
frame.add(panel);
add.addActionListener((ActionEvent e) -> {
addButton();
});
edit.addActionListener((ActionEvent e)->{
editButton();
});
delete.addActionListener((ActionEvent e) ->{
deleteButton();
});
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
tableMouseClicked(e);
}
});
help.addActionListener((ActionEvent e) -> {
helpButton();
});
frame.setVisible(true);
}
public static void tableMouseClicked(MouseEvent e)
{
int i = table.getSelectedRow();
TableModel m = table.getModel();
}
public static void deleteButton()
{
int i = table.getSelectedRow();
if(i == -1)
{
JOptionPane.showMessageDialog(frame, "Did not select a row","Error", JOptionPane.WARNING_MESSAGE);
}else
{
String email = table.getValueAt(i, 0).toString();
Customer c = customers.getCustomer(email);
if(c!=null)
{
customers.deleteCustomer(c);
tab();
}else
System.out.println("No match.");
}
}
public static void editButton()
{
int i = table.getSelectedRow();
if(i == -1)
{
JOptionPane.showMessageDialog(frame, "Did not select a row","Error",JOptionPane.INFORMATION_MESSAGE);
}else
{
String email = table.getValueAt(i,0).toString();
Customer c = addeditButton();
if(c.getEmail()!=null)
{
customers.updateCustomer(email, c);
tab();
}else{
JOptionPane.showMessageDialog(frame, "No Email selected","Error",JOptionPane.INFORMATION_MESSAGE);
}
tab();
}
}
//pulls up the pop up for the user to enter the required information.
public static void addButton()
{
Customer c = addeditButton();
Customer t = customers.getCustomer(c.getEmail());
//makes sure that the information was not already added.
if(t != null)
{
JOptionPane.showMessageDialog(frame, "There is already a customer with that email.","Error", JOptionPane.WARNING_MESSAGE);
}else if(c.getEmail() != null)
{
customers.addCustomer(c);
tab();
}
}
//pulls and verifies the informaiton from the pop up tomake sure the information that the user enters is valid
public static Customer addeditButton()
{
//text field for email
JTextField tEmail = new JTextField();
StringsUtils su = new StringsUtils();
tEmail.setColumns(20);
//text field for first name
JTextField tFName = new JTextField();
tFName.setColumns(20);
//text field for last name
JTextField tLName = new JTextField();
tLName.setColumns(20);
//Labels for each text field
JLabel lEmail = new JLabel("Email: ");
JLabel lFName = new JLabel("First Name: ");
JLabel lLName = new JLabel("Last Name: ");
//Panel creation
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints g = new GridBagConstraints();
g.insets = new Insets(5,5,0,5);
g.gridx = 0; g.gridy = 0; g.anchor = GridBagConstraints.LINE_START;
panel.add(lEmail, g);
g.gridx=1; g.gridy =0; g.anchor = GridBagConstraints.LINE_START;
panel.add(tEmail,g);
g.gridx=0; g.gridy=1; g.anchor = GridBagConstraints.LINE_START;
panel.add(lFName,g);
g.gridx = 1; g.gridy = 1; g.anchor = GridBagConstraints.LINE_START;
panel.add(tFName,g);
g.gridx = 0; g.gridy = 2; g.anchor = GridBagConstraints.LINE_START;
panel.add(lLName,g);
g.gridx = 1; g.gridy = 2; g.anchor = GridBagConstraints.LINE_START;
panel.add(tLName,g);
int result = JOptionPane.showConfirmDialog(null, panel, "add", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
//Variables that store user inputted data
String email;
String firstName;
String lastName;
if(result != JOptionPane.OK_CANCEL_OPTION)
{
//gets the inputted data from the user and stores it on the correct variables
email = tEmail.getText();
firstName = tFName.getText();
lastName = tLName.getText();
//makes sure that there are no empty areas in the program, then continues to store the data in customers
boolean noEmp = Validator.notEmpty(email, firstName, lastName);
if(noEmp ==true)
{
boolean forvali = Validator.formatEmail(email);
if(forvali == true)
{
if(email.length()> emailSize )
{
su.shorter(email,emailSize);
}else if(email.length()< emailSize)
{
su.padSpaces(email, emailSize);
}if(firstName.length()> firstNameSize)
{
su.shorter(firstName,firstNameSize);
}else if(firstName.length()< firstNameSize)
{
su.padSpaces(firstName, firstNameSize);
}if(lastName.length()> lastNameSize )
{
su.shorter(lastName,lastNameSize);
}else if(lastName.length()< lastNameSize)
{
su.padSpaces(lastName, lastNameSize);
}
}
Customer c = new Customer(email, firstName, lastName);
return c;
}
}
//correct error pop up for the user
JOptionPane.showMessageDialog(frame, "No Email, First name, or Last name entered, please try again. ","Error",JOptionPane.INFORMATION_MESSAGE);
return null;
}
//Help button gives a pop up that helps the user understand what each button does in the program.
public static void helpButton()
{
String message = "Add - Allows you to add a customer to the table \n"
+ "Update - Allows you to change customer data\n"
+ "Delete - Allows you to delete a customer\n";
JOptionPane.showMessageDialog(frame, message, "Help", JOptionPane.INFORMATION_MESSAGE);
}
//sets up the different rows and columns of the list on the main page.
public static void tab()
{
customers = DAOFactory.getCustomerDAO();
ArrayList<Customer> ca = customers.getCustomers();
DefaultTableModel dtm =(DefaultTableModel)table.getModel();
dtm.setRowCount(0);
Object[] row = new Object[3];
for(int i = 0; i<ca.size();i++)
{
row[0]=ca.get(i).getEmail();
row[1]=ca.get(i).getFirstName();
row[2]=ca.get(i).getLastName();
dtm.addRow(row);
}
}
}
|
/*
* JMEP - Java Mathematical Expression Parser.
* Copyright (C) 1999 Jo Desmet
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* You can contact the Original submitter of this library by
* email at: Jo_Desmet@yahoo.com.
*
*/
package io.desmet.jmep;
/**
* This is an exception that occurs on access of an Undefined Function.
* @author Jo Desmet
*/
public class UndefinedFunctionException extends ExpressionException {
private static final long serialVersionUID = 1L;
private final String functionName;
/*
* NOTE: The constructor should not defined public as it should only
* be used within the package.
*/
public UndefinedFunctionException(int position,String name) {
super(position,"Undefined Function: " + name);
this.functionName = name;
}
/**
* Gets the name of the Undefined Function.
* @return the name of the Undefined Function.
*/
public String getFunctionName() {
return functionName;
}
}
|
package modle;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import pojo.AplicationPayment;
import pojo.Application;
import pojo.Apprualstatues;
import pojo.Otheritiscat;
import pojo.Payment;
import pojo.TradeLicense;
/**
*
* @author RM.LasanthaRanga@gmail.com
*/
public class LoadAppList implements Runnable {
HashSet<AppHolder> appHList = new HashSet<AppHolder>();
public HashSet<AppHolder> loadAllAppList() {
Session session = conn.NewHibernateUtil.getSessionFactory().openSession();
session.beginTransaction().commit();
try {
int x = 0;
List<pojo.Application> list = session.createCriteria(pojo.Application.class).list();
try {
for (Application a : list) {
x++;
AppHolder ah = new AppHolder();
ah.setIdApplication(a.getIdApplication());
ah.setApplicationNo(a.getApplicationNo());
ah.setApplicationDate(a.getApplicationDate());
ah.setYear(a.getYear());
ah.setMonth(a.getMonth());
ah.setAllocation(a.getAllocation());
ah.setTradeName(a.getTradeName());
ah.setTradeAddress1(a.getTradeAddress1());
ah.setTradeAddress2(a.getTradeAddress2());
ah.setTradeAddress3(a.getTradeAddress3());
ah.setTaxAmount(a.getTaxAmount());
ah.setDiscription(a.getDiscription());
ah.setStatues(a.getStatues());
ah.setApproveToPaymant(a.getApproveToPaymant());
ah.setUserLog_app(a.getUserLog().getIdUserLog());
if (a.getUser() != null) {
ah.setIdRo(a.getUser().getIdUser());
ah.setRoName(a.getUser().getFullName());
} else {
ah.setIdRo(0);
ah.setRoName("");
}
ah.setIdAssessmant(a.getAssessment().getIdAssessment());
ah.setAssessmantNO(a.getAssessment().getAssessmentNo());
ah.setIdStreet(a.getAssessment().getStreet().getIdStreet());
ah.setStreetName(a.getAssessment().getStreet().getStreetName());
ah.setIdWard(a.getAssessment().getStreet().getWard().getIdWard());
ah.setWardName(a.getAssessment().getStreet().getWard().getWardName());
ah.setNature(a.getTradeNature().getNature());
ah.setIdNature(a.getTradeNature().getIdTradeNature());
if (a.getSubNature() != null) {
ah.setSubNature(a.getSubNature().getSubNature());
ah.setIdSubNatrue(a.getSubNature().getIdSubNature());
} else {
ah.setSubNature("");
ah.setIdSubNatrue(0);
}
ah.setIdTradeType(a.getTradeType().getIdTradeType());
ah.setTradeTypeName(a.getTradeType().getTypeName());
ah.setIdVort(a.getTradeType().getVort().getIdVort());
ah.setVortNo(a.getTradeType().getVort().getVoteNo());
Set<AplicationPayment> aplicationPayments = a.getAplicationPayments();
if (aplicationPayments.size() > 0) {
for (AplicationPayment aplicationPayment : aplicationPayments) {
Payment payment = aplicationPayment.getPayment();
if (payment.getStatus() != 0) {
ah.setIdPaymant(payment.getIdPayment());
ah.setUserLog_pay(payment.getUserLog().getIdUserLog());
ah.setPaymentDate(payment.getPaymentDate());
ah.setReceiptNo(payment.getReceiptNo());
ah.setTaxAmount_inPaymant(payment.getTaxAmount());
ah.setVat(payment.getVat());
ah.setNbt(payment.getNbt());
ah.setSpamp(payment.getSpamp());
ah.setTotaleAmount(payment.getTotaleAmount());
ah.setCashCheack(payment.getCashCheack());
ah.setStatus_pay(payment.getStatus());
}
}
}
Set<TradeLicense> tradeLicenses = a.getTradeLicenses();
if (tradeLicenses.size() > 0) {
for (TradeLicense tradeLicense : tradeLicenses) {
if (tradeLicense.getPayment().getIdPayment() == ah.getIdPaymant()) {
ah.setIdTradeLicense(tradeLicense.getIdTradeLicense());
ah.setLicenNo(tradeLicense.getLicenNo());
ah.setTradeLicenseDate(tradeLicense.getTradeLicenseDate());
ah.setStatus_License(tradeLicense.getStatus());
}
}
}
Set<Apprualstatues> apprualstatueses = a.getApprualstatueses();
if (apprualstatueses.size() > 0) {
HashSet<ApprvalHolder> aphList = new HashSet<ApprvalHolder>();
for (Apprualstatues apr : apprualstatueses) {
ApprvalHolder aprh = new ApprvalHolder();
aprh.setIdApprualStatues(apr.getIdApprualStatues());
aprh.setIdApplication(a.getIdApplication());
aprh.setDescription(apr.getDescription());
aprh.setSendDate(apr.getSendDate());
aprh.setApproveDate(apr.getApproveDate());
aprh.setStatues_approve(apr.getStatues());
aprh.setIdOtheritisCat(apr.getIdOtheritisCat());
Integer idOtheritisCat = apr.getIdOtheritisCat();
Otheritiscat name = (pojo.Otheritiscat) session.createCriteria(pojo.Otheritiscat.class).add(Restrictions.eq("idOtheritisCat", idOtheritisCat)).uniqueResult();
aprh.setOtheritisCat(name.getCatname());
aprh.setIdUser(apr.getUser().getIdUser());
aprh.setFullName(apr.getUser().getFullName());
aprh.setNic(apr.getUser().getNic());
aprh.setMobile(apr.getUser().getMobile());
aprh.setRegDate(apr.getUser().getRegDate());
aprh.setStatus(apr.getStatues());
aphList.add(aprh);
}
ah.setApproveList(aphList);
}
appHList.add(ah);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(x);
return appHList;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.close();
}
}
@Override
public void run() {
loadAllAppList();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package legaltime;
/**
*
* @author bmartin
*/
public class ResourceAnchor {
public ResourceAnchor() {
}
}
|
package com.ab.yuri.aifuwu;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.ab.yuri.aifuwu.RecyclerView.Uses;
import com.ab.yuri.aifuwu.RecyclerView.UsesAdapter;
import com.ab.yuri.aifuwu.gson.WeatherNow;
import com.ab.yuri.aifuwu.service.AutoUpdateService;
import com.ab.yuri.aifuwu.util.HttpUtil;
import com.ab.yuri.aifuwu.util.Utility;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
public static final String STUDENT_NAME="student_name";
public static final String STUDENT_DEPARTMENT="student_department";
public static final String STUDENT_MAJOR="student_major";
private List<Uses> usesList=new ArrayList<>();
private UsesAdapter adapter;
private DrawerLayout mDrawerLayout;
private NavigationView navView;
private Toolbar mainToolbar;
private ImageView bg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=getIntent();
final String studentName=intent.getStringExtra(STUDENT_NAME);
final String studentDepartment=intent.getStringExtra(STUDENT_DEPARTMENT);
final String studentMajor=intent.getStringExtra(STUDENT_MAJOR);
mainToolbar= (Toolbar) findViewById(R.id.main_toolbar);
mDrawerLayout= (DrawerLayout) findViewById(R.id.main_drawer_layout);
navView= (NavigationView) findViewById(R.id.nav_view);
bg= (ImageView) findViewById(R.id.bg);
final RecyclerView recyclerView= (RecyclerView) findViewById(R.id.main_recycler_view);
if (Build.VERSION.SDK_INT>=21){
View decorView=getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
setSupportActionBar(mainToolbar);
ActionBar actionBar=getSupportActionBar();
if (actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_main_menu_left);
}
/*
添加侧边栏head数据和图片
*/
final View headerLayout = navView.inflateHeaderView(R.layout.nav_header);
TextView stuName= (TextView) headerLayout.findViewById(R.id.stu_name);
TextView stuDepartment= (TextView) headerLayout.findViewById(R.id.stu_department);
TextView stuMajor= (TextView) headerLayout.findViewById(R.id.stu_major);
stuName.setText(studentName);
stuDepartment.setText(studentDepartment);
stuMajor.setText(studentMajor);
Glide.with(this).load(R.drawable.bg_head).into(new SimpleTarget<GlideDrawable>() {
@Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
headerLayout.setBackground(resource);
}
}
});
/*
加载背景
*/
Glide.with(this).load(R.drawable.bg).into(bg);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.run:
Intent run=new Intent(MainActivity.this,RunActivity.class);
startActivity(run);
mDrawerLayout.closeDrawers();
break;
case R.id.score:
Intent score=new Intent(MainActivity.this,ScoreActivity.class);
startActivity(score);
mDrawerLayout.closeDrawers();
break;
case R.id.schooldays:
Intent schooldays=new Intent(MainActivity.this,SchooldaysActivity.class);
startActivity(schooldays);
mDrawerLayout.closeDrawers();
break;
case R.id.oneday:
Intent oneday=new Intent(MainActivity.this, OnedayActivity.class);
startActivity(oneday);
mDrawerLayout.closeDrawers();
break;
case R.id.about_us:
Intent aboutUs=new Intent(MainActivity.this,AboutUsActivity.class);
startActivity(aboutUs);
mDrawerLayout.closeDrawers();
break;
case R.id.quit:
Intent quit=new Intent(MainActivity.this,LoginActivity.class);
startActivity(quit);
mDrawerLayout.closeDrawers();
break;
}
return true;
}
});
initUses();
GridLayoutManager layoutManager=new GridLayoutManager(this,2);
recyclerView.setLayoutManager(layoutManager);
adapter=new UsesAdapter(usesList);
recyclerView.setAdapter(adapter);
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(this);
String weatherString=prefs.getString("weather",null);
if (weatherString!=null){
//有缓存时直接解析天气数据
WeatherNow weatherNow=Utility.handleWeatherResponse(weatherString);
showWeatherInfo(weatherNow);
}else {
//没有缓存时直接解析天气数据
requestWeather();
}
}
private void initUses() {
Uses run=new Uses("跑操查询",R.drawable.img_run_big);
usesList.add(run);
Uses score=new Uses("成绩查询",R.drawable.img_score_big);
usesList.add(score);
Uses schooldays=new Uses("校历",R.drawable.img_schooldays_big);
usesList.add(schooldays);
Uses library=new Uses("一言",R.drawable.img_oneday_big);
usesList.add(library);
}
/*
加载天气数据
*/
public void requestWeather(){
final String weatherUrl="http://guolin.tech/api/weather?cityid=CN101190101&key=56ad57d30e4e43888f020ed6a592dd40";
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String responseText=response.body().string();
final WeatherNow weatherNow= Utility.handleWeatherResponse(responseText);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (weatherNow!=null&&"ok".equals(weatherNow.status)){
SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("weather",responseText);
editor.apply();
showWeatherInfo(weatherNow);
}
}
});
}
});
}
/*
展示天气数据
*/
private void showWeatherInfo(WeatherNow weatherNow){
String updateTime =weatherNow.basic.update.loc.split(" ")[0];
String weatherInfo = weatherNow.now.cond.txt;
String degree = weatherNow.now.tmp + "℃";
TextView update= (TextView) findViewById(R.id.title_update_time);
TextView weatherInfoText= (TextView) findViewById(R.id.weather_info_text);
TextView degreeText= (TextView) findViewById(R.id.degree_text);
update.setText(updateTime);
weatherInfoText.setText(weatherInfo);
degreeText.setText(degree);
//激活自动更新服务
Intent intent=new Intent(this, AutoUpdateService.class);
startService(intent);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
break;
default:
break;
}
return true;
}
}
|
package kr.or.ddit.basic;
public class Service {
@PrintAnnotation()
public boolean method1() {
System.out.println("메서드1에서 출력되었습니다.");
return true;
}
@PrintAnnotation("%")
public boolean method2() {
System.out.println("메서드2에서 출력되었습니다.");
return true;
}
@PrintAnnotation(value = "#", count= 25)
public boolean method3() {
System.out.println("메서드3에서 출력되었습니다.");
return true;
}
}
|
package fr.solutec.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.PathVariable;
import fr.solutec.entities.Bar;
public interface BarRepository extends JpaRepository<Bar, Long> {
public Bar findByNom (String nom);
public Bar deleteById (@PathVariable Long id);
public Bar findByMail(String mail);
public Bar findById(Long id);
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.CompressionType;
import org.apache.hadoop.mapred.lib.NullOutputFormat;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* A Controlled Map/Reduce Job. The tasks are controlled by the presence of
* particularly named files in the directory signalFileDir on the file-system
* that the job is configured to work with. Tasks get scheduled by the
* scheduler, occupy the slots on the TaskTrackers and keep running till the
* user gives a signal via files whose names are of the form MAPS_[0-9]* and
* REDUCES_[0-9]*. For e.g., whenever the map tasks see that a file name MAPS_5
* is created in the singalFileDir, all the maps whose TaskAttemptIDs are below
* 4 get finished. At any time, there should be only one MAPS_[0-9]* file and
* only one REDUCES_[0-9]* file in the singnalFileDir. In the beginning MAPS_0
* and REDUCE_0 files are present, and further signals are given by renaming
* these files.
*
*/
class ControlledMapReduceJob extends Configured implements Tool,
Mapper<NullWritable, NullWritable, IntWritable, NullWritable>,
Reducer<IntWritable, NullWritable, NullWritable, NullWritable>,
Partitioner<IntWritable, NullWritable>,
InputFormat<NullWritable, NullWritable> {
static final Log LOG = LogFactory.getLog(ControlledMapReduceJob.class);
private FileSystem fs = null;
private int taskNumber;
private static ArrayList<Path> signalFileDirCache = new ArrayList<Path>();
private Path signalFileDir;
{
Random random = new Random();
signalFileDir = new Path("signalFileDir-" + random.nextLong());
while (signalFileDirCache.contains(signalFileDir)) {
signalFileDir = new Path("signalFileDir-" + random.nextLong());
}
signalFileDirCache.add(signalFileDir);
}
private long mapsFinished = 0;
private long reducesFinished = 0;
private RunningJob rJob = null;
private int numMappers;
private int numReducers;
private final String MAP_SIGFILE_PREFIX = "MAPS_";
private final String REDUCE_SIGFILE_PREFIX = "REDUCES_";
private void initialize()
throws IOException {
fs = FileSystem.get(getConf());
fs.mkdirs(signalFileDir);
writeFile(new Path(signalFileDir, MAP_SIGFILE_PREFIX + mapsFinished));
writeFile(new Path(signalFileDir, REDUCE_SIGFILE_PREFIX + reducesFinished));
}
/**
* Finish N number of maps/reduces.
*
* @param isMap
* @param noOfTasksToFinish
* @throws IOException
*/
public void finishNTasks(boolean isMap, int noOfTasksToFinish)
throws IOException {
if (noOfTasksToFinish < 0) {
throw new IOException(
"Negative values for noOfTasksToFinish not acceptable");
}
if (noOfTasksToFinish == 0) {
return;
}
LOG.info("Going to finish off " + noOfTasksToFinish);
String PREFIX = isMap ? MAP_SIGFILE_PREFIX : REDUCE_SIGFILE_PREFIX;
long tasksFinished = isMap ? mapsFinished : reducesFinished;
Path oldSignalFile =
new Path(signalFileDir, PREFIX + String.valueOf(tasksFinished));
Path newSignalFile =
new Path(signalFileDir, PREFIX
+ String.valueOf(tasksFinished + noOfTasksToFinish));
fs.rename(oldSignalFile, newSignalFile);
if (isMap) {
mapsFinished += noOfTasksToFinish;
} else {
reducesFinished += noOfTasksToFinish;
}
LOG.info("Successfully sent signal to finish off " + noOfTasksToFinish);
}
/**
* Finished all tasks of type determined by isMap
*
* @param isMap
* @throws IOException
*/
public void finishAllTasks(boolean isMap)
throws IOException {
finishNTasks(isMap, (isMap ? numMappers : numReducers));
}
/**
* Finish the job
*
* @throws IOException
*/
public void finishJob()
throws IOException {
finishAllTasks(true);
finishAllTasks(false);
}
/**
* Wait till noOfTasksToBeRunning number of tasks of type specified by isMap
* started running. This currently uses a jip object and directly uses its api
* to determine the number of tasks running.
*
* <p>
*
* TODO: It should eventually use a JobID and then get the information from
* the JT to check the number of running tasks.
*
* @param jip
* @param isMap
* @param noOfTasksToBeRunning
*/
static void waitTillNTasksStartRunning(JobInProgress jip, boolean isMap,
int noOfTasksToBeRunning)
throws InterruptedException {
int numTasks = 0;
while (numTasks != noOfTasksToBeRunning) {
Thread.sleep(1000);
numTasks = isMap ? jip.runningMaps() : jip.runningReduces();
LOG.info("Waiting till " + noOfTasksToBeRunning
+ (isMap ? " map" : " reduce") + " tasks of the job "
+ jip.getJobID() + " start running. " + numTasks
+ " tasks already started running.");
}
}
/**
* Make sure that the number of tasks of type specified by isMap running in
* the given job is the same as noOfTasksToBeRunning
*
* <p>
*
* TODO: It should eventually use a JobID and then get the information from
* the JT to check the number of running tasks.
*
* @param jip
* @param isMap
* @param noOfTasksToBeRunning
*/
static void assertNumTasksRunning(JobInProgress jip, boolean isMap,
int noOfTasksToBeRunning)
throws Exception {
if ((isMap ? jip.runningMaps() : jip.runningReduces()) != noOfTasksToBeRunning) {
throw new Exception("Number of tasks running is not "
+ noOfTasksToBeRunning);
}
}
/**
* Wait till noOfTasksToFinish number of tasks of type specified by isMap
* are finished. This currently uses a jip object and directly uses its api to
* determine the number of tasks finished.
*
* <p>
*
* TODO: It should eventually use a JobID and then get the information from
* the JT to check the number of finished tasks.
*
* @param jip
* @param isMap
* @param noOfTasksToFinish
* @throws InterruptedException
*/
static void waitTillNTotalTasksFinish(JobInProgress jip, boolean isMap,
int noOfTasksToFinish)
throws InterruptedException {
int noOfTasksAlreadyFinished = 0;
while (noOfTasksAlreadyFinished < noOfTasksToFinish) {
Thread.sleep(1000);
noOfTasksAlreadyFinished =
(isMap ? jip.finishedMaps() : jip.finishedReduces());
LOG.info("Waiting till " + noOfTasksToFinish
+ (isMap ? " map" : " reduce") + " tasks of the job "
+ jip.getJobID() + " finish. " + noOfTasksAlreadyFinished
+ " tasks already got finished.");
}
}
/**
* Have all the tasks of type specified by isMap finished in this job?
*
* @param jip
* @param isMap
* @return true if finished, false otherwise
*/
static boolean haveAllTasksFinished(JobInProgress jip, boolean isMap) {
return ((isMap ? jip.runningMaps() : jip.runningReduces()) == 0);
}
private void writeFile(Path name)
throws IOException {
Configuration conf = new Configuration(false);
SequenceFile.Writer writer =
SequenceFile.createWriter(fs, conf, name, BytesWritable.class,
BytesWritable.class, CompressionType.NONE);
writer.append(new BytesWritable(), new BytesWritable());
writer.close();
}
@Override
public void configure(JobConf conf) {
try {
signalFileDir = new Path(conf.get("signal.dir.path"));
numReducers = conf.getNumReduceTasks();
fs = FileSystem.get(conf);
String taskAttemptId = conf.get(JobContext.TASK_ATTEMPT_ID);
if (taskAttemptId != null) {
TaskAttemptID taskAttemptID = TaskAttemptID.forName(taskAttemptId);
taskNumber = taskAttemptID.getTaskID().getId();
}
} catch (IOException ioe) {
LOG.warn("Caught exception " + ioe);
}
}
private FileStatus[] listSignalFiles(FileSystem fileSys, final boolean isMap)
throws IOException {
return fileSys.globStatus(new Path(signalFileDir.toString() + "/*"),
new PathFilter() {
@Override
public boolean accept(Path path) {
if (isMap && path.getName().startsWith(MAP_SIGFILE_PREFIX)) {
LOG.debug("Found signal file : " + path.getName());
return true;
} else if (!isMap
&& path.getName().startsWith(REDUCE_SIGFILE_PREFIX)) {
LOG.debug("Found signal file : " + path.getName());
return true;
}
LOG.info("Didn't find any relevant signal files.");
return false;
}
});
}
@Override
public void map(NullWritable key, NullWritable value,
OutputCollector<IntWritable, NullWritable> output, Reporter reporter)
throws IOException {
LOG.info(taskNumber + " has started.");
FileStatus[] files = listSignalFiles(fs, true);
String[] sigFileComps = files[0].getPath().getName().split("_");
String signalType = sigFileComps[0];
int noOfTasks = Integer.parseInt(sigFileComps[1]);
while (!signalType.equals("MAPS") || taskNumber + 1 > noOfTasks) {
LOG.info("Signal type found : " + signalType
+ " .Number of tasks to be finished by this signal : " + noOfTasks
+ " . My id : " + taskNumber);
LOG.info(taskNumber + " is still alive.");
try {
reporter.progress();
Thread.sleep(1000);
} catch (InterruptedException ie) {
LOG.info(taskNumber + " is still alive.");
break;
}
files = listSignalFiles(fs, true);
sigFileComps = files[0].getPath().getName().split("_");
signalType = sigFileComps[0];
noOfTasks = Integer.parseInt(sigFileComps[1]);
}
LOG.info("Signal type found : " + signalType
+ " .Number of tasks to be finished by this signal : " + noOfTasks
+ " . My id : " + taskNumber);
// output numReduce number of random values, so that
// each reducer will get one key each.
for (int i = 0; i < numReducers; i++) {
output.collect(new IntWritable(i), NullWritable.get());
}
LOG.info(taskNumber + " is finished.");
}
@Override
public void reduce(IntWritable key, Iterator<NullWritable> values,
OutputCollector<NullWritable, NullWritable> output, Reporter reporter)
throws IOException {
LOG.info(taskNumber + " has started.");
FileStatus[] files = listSignalFiles(fs, false);
String[] sigFileComps = files[0].getPath().getName().split("_");
String signalType = sigFileComps[0];
int noOfTasks = Integer.parseInt(sigFileComps[1]);
while (!signalType.equals("REDUCES") || taskNumber + 1 > noOfTasks) {
LOG.info("Signal type found : " + signalType
+ " .Number of tasks to be finished by this signal : " + noOfTasks
+ " . My id : " + taskNumber);
LOG.info(taskNumber + " is still alive.");
try {
reporter.progress();
Thread.sleep(1000);
} catch (InterruptedException ie) {
LOG.info(taskNumber + " is still alive.");
break;
}
files = listSignalFiles(fs, false);
sigFileComps = files[0].getPath().getName().split("_");
signalType = sigFileComps[0];
noOfTasks = Integer.parseInt(sigFileComps[1]);
}
LOG.info("Signal type found : " + signalType
+ " .Number of tasks to be finished by this signal : " + noOfTasks
+ " . My id : " + taskNumber);
LOG.info(taskNumber + " is finished.");
}
@Override
public void close()
throws IOException {
// nothing
}
public JobID getJobId() {
if (rJob == null) {
return null;
}
return rJob.getID();
}
public int run(int numMapper, int numReducer)
throws IOException {
JobConf conf =
getControlledMapReduceJobConf(getConf(), numMapper, numReducer);
JobClient client = new JobClient(conf);
rJob = client.submitJob(conf);
while (!rJob.isComplete()) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
break;
}
}
if (rJob.isSuccessful()) {
return 0;
}
return 1;
}
private JobConf getControlledMapReduceJobConf(Configuration clusterConf,
int numMapper, int numReducer)
throws IOException {
setConf(clusterConf);
initialize();
JobConf conf = new JobConf(getConf(), ControlledMapReduceJob.class);
conf.setJobName("ControlledJob");
conf.set("signal.dir.path", signalFileDir.toString());
conf.setNumMapTasks(numMapper);
conf.setNumReduceTasks(numReducer);
conf.setMapperClass(ControlledMapReduceJob.class);
conf.setMapOutputKeyClass(IntWritable.class);
conf.setMapOutputValueClass(NullWritable.class);
conf.setReducerClass(ControlledMapReduceJob.class);
conf.setOutputKeyClass(NullWritable.class);
conf.setOutputValueClass(NullWritable.class);
conf.setInputFormat(ControlledMapReduceJob.class);
FileInputFormat.addInputPath(conf, new Path("ignored"));
conf.setOutputFormat(NullOutputFormat.class);
conf.setMapSpeculativeExecution(false);
conf.setReduceSpeculativeExecution(false);
// Set the following for reduce tasks to be able to be started running
// immediately along with maps.
conf.set(JobContext.COMPLETED_MAPS_FOR_REDUCE_SLOWSTART, String.valueOf(0));
return conf;
}
@Override
public int run(String[] args)
throws Exception {
numMappers = Integer.parseInt(args[0]);
numReducers = Integer.parseInt(args[1]);
return run(numMappers, numReducers);
}
@Override
public int getPartition(IntWritable k, NullWritable v, int numPartitions) {
return k.get() % numPartitions;
}
@Override
public RecordReader<NullWritable, NullWritable> getRecordReader(
InputSplit split, JobConf job, Reporter reporter) {
LOG.debug("Inside RecordReader.getRecordReader");
return new RecordReader<NullWritable, NullWritable>() {
private int pos = 0;
public void close() {
// nothing
}
public NullWritable createKey() {
return NullWritable.get();
}
public NullWritable createValue() {
return NullWritable.get();
}
public long getPos() {
return pos;
}
public float getProgress() {
return pos * 100;
}
public boolean next(NullWritable key, NullWritable value) {
if (pos++ == 0) {
LOG.debug("Returning the next record");
return true;
}
LOG.debug("No more records. Returning none.");
return false;
}
};
}
@Override
public InputSplit[] getSplits(JobConf job, int numSplits) {
LOG.debug("Inside InputSplit.getSplits");
InputSplit[] ret = new InputSplit[numSplits];
for (int i = 0; i < numSplits; ++i) {
ret[i] = new EmptySplit();
}
return ret;
}
public static class EmptySplit implements InputSplit {
public void write(DataOutput out)
throws IOException {
}
public void readFields(DataInput in)
throws IOException {
}
public long getLength() {
return 0L;
}
public String[] getLocations() {
return new String[0];
}
}
static class ControlledMapReduceJobRunner extends Thread {
private JobConf conf;
private ControlledMapReduceJob job;
private JobID jobID;
private int numMappers;
private int numReducers;
public ControlledMapReduceJobRunner() {
this(new JobConf(), 5, 5);
}
public ControlledMapReduceJobRunner(JobConf cnf, int numMap, int numRed) {
this.conf = cnf;
this.numMappers = numMap;
this.numReducers = numRed;
}
public ControlledMapReduceJob getJob() {
while (job == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
LOG.info(ControlledMapReduceJobRunner.class.getName()
+ " is interrupted.");
break;
}
}
return job;
}
public JobID getJobID()
throws IOException {
ControlledMapReduceJob job = getJob();
JobID id = job.getJobId();
while (id == null) {
id = job.getJobId();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
LOG.info(ControlledMapReduceJobRunner.class.getName()
+ " is interrupted.");
break;
}
}
return id;
}
@Override
public void run() {
if (job != null) {
LOG.warn("Job is already running.");
return;
}
try {
job = new ControlledMapReduceJob();
int ret =
ToolRunner.run(this.conf, job, new String[] {
String.valueOf(numMappers), String.valueOf(numReducers) });
LOG.info("Return value for the job : " + ret);
} catch (Exception e) {
LOG.warn("Caught exception : " + StringUtils.stringifyException(e));
}
}
static ControlledMapReduceJobRunner getControlledMapReduceJobRunner(
JobConf conf, int numMappers, int numReducers) {
return new ControlledMapReduceJobRunner(conf, numMappers, numReducers);
}
}
}
|
package com.rs.game.player.content.citadel;
import com.rs.game.player.dialogues.Dialogue;
public class LeavingCitadel extends Dialogue {
@Override
public void start() {
sendDialogue(
"This portal will bring you back to land. Do you",
"want to leave your citadel?");
}
@Override
public void run(int interfaceId, int componentId) {
switch(stage) {
case -1:
stage = 0;
sendOptionsDialogue(SEND_DEFAULT_OPTIONS_TITLE, "Leave my Citadel", "Nevermind");
break;
case 0:
if(componentId == OPTION_2) {
end();
stage = 1;
} else {
stage = 2;
}
break;
case 1:
stage = -2;
new Citadel(player);
break;
case 2:
Citadel.LeaveCitadel(player);
break;
default:
end();
break;
}
}
@Override
public void finish() {
}
}
|
/* Generated by AN DISI Unibo */
/*
This code is generated only ONCE
*/
package it.unibo.logic_controller;
import it.unibo.is.interfaces.IOutputEnvView;
import it.unibo.qactors.QActorContext;
public class Logic_controller extends AbstractLogic_controller {
public Logic_controller(String actorId, QActorContext myCtx, IOutputEnvView outEnvView ) throws Exception{
super(actorId, myCtx, outEnvView);
}
private static int DETECTED = 40;
private static int DMIN = 70;
private static int MULT = 30;
private int[] sonars;
private int robotPosition = 0;
public void setSonar(int distance, int sid) {
sonars[sid-1] = distance;
for (int i = 0; i < sonars.length; i++) {
//println("--"+sonars[i]);
}
}
public void setRobotPosition(int pos) {
robotPosition = pos;
}
public int getRobotPosition() {
return robotPosition;
}
public void incRobotPosition() {
robotPosition++;
println("Robot position:"+ robotPosition);
}
public void setNumOfSonars(int num) {
sonars = new int[num];
for (int i = 0; i < sonars.length; i++) {
sonars[i] = -1;
}
}
// detect robot and emit event for the radar
public boolean isRobotDetected() {
if ((sonars[robotPosition] < DETECTED) && (sonars[robotPosition] >= 0) ){
this.incRobotPosition();
this.emit("sonarToGui", "p(" + sonars[robotPosition-1] + "," + (robotPosition*MULT) + ")");
return true;
}else{
return false;
}
}
public void setRadarPointToZero() {
this.emit("sonarToGui", "p(0,0)");
}
public void reset() {
this.setNumOfSonars(sonars.length);
robotPosition = 0;
}
public boolean isExpressionTrue() {
for (int i = 0; i < sonars.length; i++) {
if (sonars[i] == -1) return false;
}
int total = 0;
for (int i = robotPosition; i < sonars.length; i++) {
total = sonars[i] + total;
}
//println("total: " + total + "\nsonars.length: " + sonars.length + "\nrobotPosition: " + robotPosition);
if ((total/(sonars.length-(robotPosition + 1)+1))<DMIN) {
return true;
}else{
return false;
}
}
}
|
package dao;
import com.zhao.RunBoot;
import com.zhao.entity.City;
import com.zhao.repository.CityRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RunBoot.class)
public class TestMasterSlave {
@Resource
CityRepository cityRepository;
@Test
public void testMasterSlave() {
City city = new City();
city.setName("shanghai");
city.setProvince("shanghai");
cityRepository.save(city);
}
@Test
public void findAll() {
List<City> list = cityRepository.findAll();
list.forEach(c -> {
System.out.println(c.getId() + " " + c.getName() + " " + c.getProvince());
});
}
}
|
package cz.alza.uitest.pages;
import com.codeborne.selenide.SelenideElement;
import org.openqa.selenium.By;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.WebDriverRunner.url;
public class AlzaCartPage extends AlzaPage<AlzaCartPage> implements AlzaInterface {
private static final String REMOVE_BUTTON = "//div[contains(@class,'del alzaico-f-cross')]";
private static final String PAGE_URL = ALZA_URL + "/Order1.htm";
private static final String CART_ITEM = "//div[@class='nameContainer']/a[@class='mainItem']";
@Override
public AlzaCartPage openPage() {
open(PAGE_URL);
return this;
}
@Override
public Boolean isCurrentPage() {
return url().contains(PAGE_URL);
}
public AlzaCartPage cleanCart() {
$$(By.xpath(REMOVE_BUTTON)).forEach(SelenideElement::click);
return this;
}
public SelenideElement getFirstCartItem() {
return $x(CART_ITEM);
}
}
|
public class NumberOfStepsToReduceANumberToZero {
public static int numberOfSteps (int num) {
int result = 0;
while (num > 0) {
if (num%2 == 0){
num = num/2;
result = result +1;
}
else {
num = num - 1;
result = result +1;
}
}
return result;
}
public static void main(String[] args) {
int result = numberOfSteps(123);
System.out.println(result);
}
}
|
package com.tencent.mm.plugin.exdevice.service;
import com.tencent.mm.sdk.platformtools.x;
class b$2 implements Runnable {
final /* synthetic */ int itv;
final /* synthetic */ b iyw;
final /* synthetic */ r iyx;
final /* synthetic */ int[] iyy;
b$2(b bVar, int i, r rVar, int[] iArr) {
this.iyw = bVar;
this.itv = i;
this.iyx = rVar;
this.iyy = iArr;
}
public final void run() {
if (!b.a(this.iyw, this.itv, this.iyx, this.iyy)) {
x.e("MicroMsg.exdevice.BluetoothSDKAdapter", "instance.scanImp failed!!!");
}
}
}
|
package com.ssm.wechatpro.controller;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
import com.ssm.wechatpro.service.WechatProductPackageDiscountService;
@Controller
public class WechatProductPackageDiscountController {
@Resource
private WechatProductPackageDiscountService wechatProductPackageDiscountService;
/**
* 显示所有套餐
*
* @return
* @throws Exception
*/
@RequestMapping("/post/wechatProductPackageDiscountController/selsctAllPackageDiscount")
@ResponseBody
public void selectAllPackageDiscount(InputObject inputObject,OutputObject outputObject) throws Exception {
wechatProductPackageDiscountService.selectAllPackageDiscount(inputObject, outputObject);
}
/**
* 添加新的打折表
* @param inputObject
* @param outputObject
* @throws Exception
*/
@RequestMapping("/post/wechatProductPackageDiscountController/insertPackageDiscount")
@ResponseBody
public void insertPackageDiscount(InputObject inputObject,OutputObject outputObject) throws Exception {
wechatProductPackageDiscountService.insertPackageDiscount(inputObject, outputObject);
}
/**
* 修改打折表
* @param inputObject
* @param outputObject
* @throws Exception
*/
@RequestMapping("/post/wechatProductPackageDiscountController/modifyPackageDiscount")
@ResponseBody
public void modifyPackageDiscount(InputObject inputObject,OutputObject outputObject) throws Exception {
wechatProductPackageDiscountService.modifyPackageDiscount(inputObject, outputObject);
}
/**
* 删除打折表
* @param inputObject
* @param outputObject
* @throws Exception
*/
@RequestMapping("/post/wechatProductPackageDiscountController/deletePackageDiscount")
@ResponseBody
public void deletePackageDiscount(InputObject inputObject,OutputObject outputObject) throws Exception {
wechatProductPackageDiscountService.deletePackageDiscount(inputObject, outputObject);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package begining.gf4.ejb.jms.mdb;
import begining.gf4.ejb.common.ConstantValueEJB;
import java.security.Principal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
/**
*
* @author Eiichi Tanaka
*/
@MessageDriven(
name = "RecieveMDB435"
,mappedName = "jms/Queue435"
,activationConfig = {
@ActivationConfigProperty(
propertyName = "acknowledgeMode"
,propertyValue = "Auto-acknowledge")
,@ActivationConfigProperty(
propertyName = "destinationType"
,propertyValue = "javax.jms.Queue")
,@ActivationConfigProperty(
propertyName = "destinationLookup"
,propertyValue = "jms/Queue435")
})
//@RunAs("admin_role")
public class RecieveMDB435 implements MessageListener {
private static final java.util.logging.Logger logger =
Logger.getLogger(RecieveMDB435.class.getName());
@Resource
private MessageDrivenContext context;
public RecieveMDB435() {
}
@Override
public void onMessage(Message message) {
final Principal princial = context.getCallerPrincipal();
logger.log(Level.INFO
, "Principal#getName() = {0}"
, princial.getName());
try {
TextMessage msg = (TextMessage) message;
logger.logp(
Level.INFO
, Thread.currentThread().getStackTrace()[0].getClassName()
, Thread.currentThread().getStackTrace()[0].getMethodName()
, "{0} {1} : MDB Message recieved : {2}"
, new String[] {
RecieveMDB435.class.getSimpleName()
,ConstantValueEJB.JMS_QUQUE_435_NAME
,msg.getText()
});
} catch (JMSException e1) {
logger.log(Level.SEVERE, e1.getMessage());
}
}
}
|
package com.example.maikebg.bodycarespa;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
mTextMessage.setText(R.string.hom);
return true;
case R.id.nav_Agendar:
Intent intent = new Intent(MainActivity.this,Agendar_Activity.class);
startActivity(intent);
case R.id.nav_notificacoes:
mTextMessage.setText(com.example.maikebg.bodycarespa.R.string.dev);
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public void QuickClick(View view) {
Intent intent = new Intent(MainActivity.this,Quick_Activity.class);
startActivity(intent);
}
public void AuriculoClick(View view) {
Intent intent = new Intent(MainActivity.this,Auriculo_Activity.class);
startActivity(intent);
}
public void VentosaClick(View view) {
Intent intent = new Intent(MainActivity.this,Ventosa_Activity.class);
startActivity(intent);
}
public void ReflexologiaClick(View view) {
Intent intent = new Intent(MainActivity.this,Reflexologia_Activity.class);
startActivity(intent);
}
public void DoinClick(View view) {
Intent intent = new Intent(MainActivity.this,Doin_Activity.class);
startActivity(intent);
}
public void AgendarClick(View view) {
Intent intent = new Intent(MainActivity.this,Agendar_Activity.class);
startActivity(intent);
}
public void ContatoClick(View view) {
Toast.makeText(MainActivity.this,"In construction",Toast.LENGTH_SHORT).show();
}
}
|
package br.com.exemplo.dataingestion.adapters.events.producers;
import br.com.exemplo.dataingestion.adapters.events.entities.DataLancamentoEvent;
import br.com.exemplo.dataingestion.adapters.events.mappers.EventMapper;
import br.com.exemplo.dataingestion.domain.entities.Lancamento;
import br.com.exemplo.dataingestion.domain.producer.ProducerService;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.RequiredArgsConstructor;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
@RequiredArgsConstructor
@Component
@Scope(value = "prototype")
public class ProducerServiceImpl implements ProducerService {
@Value("${data.ingestion.producer.topic}")
private String producerTopic;
private final KafkaTemplate<String, DataLancamentoEvent> kafkaTemplate;
private final EventMapper<Lancamento,DataLancamentoEvent> lancamentoDataLancamentoEventEventMapper;
private final MeterRegistry simpleMeterRegistry;
@Override
public Lancamento produce(Lancamento lancamento) {
simpleMeterRegistry.counter("kafka.contador","type","producao","thread",String.valueOf(Thread.currentThread().getId())).increment();
Timer.Sample sample = Timer.start(simpleMeterRegistry);
ProducerRecord producerRecord = new ProducerRecord(producerTopic, lancamentoDataLancamentoEventEventMapper.convert(lancamento));
sample.stop(simpleMeterRegistry.timer("kafka.time","type","producao","thread",String.valueOf(Thread.currentThread().getId())));
kafkaTemplate.send(producerRecord);
return lancamento;
}
}
|
package com.level01.정수내림차순으로배치하기;
import java.util.*;
public class MTest {
public static void main(String[] args) {
int n = 118372;
Solution solution = new Solution();
System.out.println(solution.solution(n));
}
}
class Solution {
public long solution(long n) {
long answer = 0;
String tmp = "";
String [] nArr = (n+"").split("");
Arrays.sort(nArr);
for(int i = nArr.length-1; i >= 0; i--){
tmp += nArr[i];
}
answer = Long.parseLong(tmp);
return answer;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.game;
import android.os.Bundle;
import com.tencent.mm.plugin.webview.ui.tools.WebViewUI.g;
class GameWebViewUI$a extends g {
final /* synthetic */ GameWebViewUI qgm;
private GameWebViewUI$a(GameWebViewUI gameWebViewUI) {
this.qgm = gameWebViewUI;
super(gameWebViewUI);
}
/* synthetic */ GameWebViewUI$a(GameWebViewUI gameWebViewUI, byte b) {
this(gameWebViewUI);
}
public final Object onMiscCallBack(String str, Bundle bundle) {
Object onMiscCallBack = GameWebViewUI.B(this.qgm).kdM.onMiscCallBack(str, bundle);
return onMiscCallBack != null ? onMiscCallBack : super.onMiscCallBack(str, bundle);
}
}
|
package com.kzw.leisure.presenter;
import com.kzw.leisure.bean.Chapter;
import com.kzw.leisure.bean.ChapterRule;
import com.kzw.leisure.bean.Query;
import com.kzw.leisure.contract.ReadBookContract;
import com.kzw.leisure.realm.ChapterList;
import com.kzw.leisure.rxJava.RxSubscriber;
import java.util.List;
/**
* author: kang4
* Date: 2019/12/6
* Description:
*/
public class ReadBookPresenter extends ReadBookContract.Presenter {
@Override
public void getChapterList(Query query, ChapterRule rule, ChapterList chapterList,boolean isFromNet) {
mRxManage.addSubscribe(mModel.getChapterList(query,rule,chapterList,isFromNet).subscribeWith(new RxSubscriber<List<Chapter>>() {
@Override
protected void _onNext(List<Chapter> chapters) {
mView.returnResult(chapters);
}
@Override
protected void _onError(String message) {
mView.returnFail(message);
}
}));
}
}
|
package com.tencent.mm.plugin.game.gamewebview.ui;
import android.os.Bundle;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.xweb.x5.a.a.a.a.b;
class d$3 extends b {
final /* synthetic */ d jJO;
d$3(d dVar) {
this.jJO = dVar;
}
public final Object onMiscCallBack(String str, Bundle bundle) {
boolean z = false;
String str2 = "MicroMsg.GameWebPageView";
String str3 = "method = %s, bundler == null ? %b";
Object[] objArr = new Object[2];
objArr[0] = str;
if (bundle == null) {
z = true;
}
objArr[1] = Boolean.valueOf(z);
x.i(str2, str3, objArr);
if (bi.oW(str) || bundle == null) {
return super.onMiscCallBack(str, bundle);
}
if (!(d.i(this.jJO) == null || d.i(this.jJO).kdM == null)) {
Object onMiscCallBack = d.i(this.jJO).kdM.onMiscCallBack(str, bundle);
if (onMiscCallBack != null) {
return onMiscCallBack;
}
}
return super.onMiscCallBack(str, bundle);
}
}
|
import java.sql.Timestamp;
import java.util.Collection;
import java.util.LinkedList;
import java.util.regex.*;
public class Finder
{
private static String parameter1;
private static String parameter2;
private static String mode;
public static void setMode(String mode) {
Finder.mode = mode;
}
public static void setParameter1(String parameter1) {
Finder.parameter1 = parameter1;
}
public static void setParameter2(String parameter2) {
Finder.parameter2 = parameter2;
}
public static LinkedList<Message> findAll(Collection<Message> messageCollection) {
LinkedList<Message> list = new LinkedList<>();
for (Message message : messageCollection) {
if (check(message)) {
list.add(message);
}
}
return list;
}
public static LinkedList<Message> printAll(Collection<Message> messageCollection) {
LinkedList<Message> list = new LinkedList<>();
for (Message message : messageCollection) {
if (check(message)) {
list.add(message);
System.out.println(message.toString());
}
}
return list;
}
private static boolean check(Message message) throws IllegalArgumentException {
switch (mode) {
case "by author":
return parameter1.equals(message.getAuthor());
case "by id":
return parameter1.equals(message.getId().toString());
case "by lexeme":
return message.toString().contains(parameter1);
case "by regex":{
Pattern pattern = Pattern.compile(parameter1);
Matcher matcher = pattern.matcher(message.toString());
return matcher.find(0);
}
case "time range":
{
Timestamp min = Timestamp.valueOf(parameter1);
Timestamp max = Timestamp.valueOf(parameter2.toString());
return (!message.getTimestamp().before(min)) && (!message.getTimestamp().after(max));
}
default:
return false;
}
}
}
|
package com.tencent.mm.plugin.luckymoney.f2f.a;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.vb;
import com.tencent.mm.protocal.c.vc;
import com.tencent.mm.sdk.platformtools.x;
public final class a extends l implements k {
private e diJ;
private b eAN;
private vb kMZ;
private vc kNa;
public a(String str) {
com.tencent.mm.ab.b.a aVar = new com.tencent.mm.ab.b.a();
aVar.dIG = new vb();
aVar.dIH = new vc();
aVar.dIF = 1987;
aVar.dII = 0;
aVar.dIJ = 0;
aVar.uri = "/cgi-bin/mmpay-bin/ftfhb/ffclearwxhb";
this.eAN = aVar.KT();
this.kMZ = (vb) this.eAN.dID.dIL;
this.kMZ.kLZ = str;
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
this.kNa = (vc) ((b) qVar).dIE.dIL;
x.i("NetSceneF2FLuckyMoneyClear", "errType %d,errCode %d,errMsg %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(this.kNa.hUm), this.kNa.hUn});
if (this.diJ != null) {
this.diJ.a(i2, this.kNa.hUm, this.kNa.hUn, this);
}
}
public final int getType() {
return 1987;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.eAN, this);
}
}
|
package exercise_chapter7;
public class arrays {
public static void main(String[] args) {
int [] testList = {3,2,64,23,88,4};
java.util.Arrays.sort(testList);
printArrays(testList);
int [] test2 = new int [5];
java.util.Arrays.fill(test2, 0,2,3);
printArrays(test2);
int index = java.util.Arrays.binarySearch(testList, 64);
System.out.println("index is " + index);
boolean isEqual = java.util.Arrays.equals(test2, testList);
System.out.println(isEqual);
}
public static void printArrays(int[] list) {
for(int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
}
}
|
package calculators;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
public class Calculator {
private JFrame frame;
private JTextField textField;
double firstnum;
double secondnum;
double result;
String operations;
String answer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Calculator window = new Calculator();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Calculator() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 256, 380);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setBounds(10, 11, 218, 33);
frame.getContentPane().add(textField);
textField.setColumns(10);
//--------------Row 1-------------
JButton btnBackspace = new JButton("\u2190");
btnBackspace.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String backspace = null;
if(textField.getText().length() > 0){
StringBuilder strB = new StringBuilder(textField.getText());
strB.deleteCharAt(textField.getText().length() - 1);
backspace = strB.toString();
textField.setText(backspace);
}
}
});
btnBackspace.setFont(new Font("Tahoma", Font.BOLD, 15));
btnBackspace.setBounds(10, 54, 50, 50);
frame.getContentPane().add(btnBackspace);
JButton btnClear = new JButton("C");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText(null);
}
});
btnClear.setFont(new Font("Tahoma", Font.BOLD, 18));
btnClear.setBounds(66, 54, 50, 50);
frame.getContentPane().add(btnClear);
JButton btnPercentage = new JButton("%");
btnPercentage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum = Double.parseDouble(textField.getText());
textField.setText("");
operations = "%";
}
});
btnPercentage.setFont(new Font("Tahoma", Font.BOLD, 13));
btnPercentage.setBounds(122, 54, 50, 50);
frame.getContentPane().add(btnPercentage);
JButton btnPlus = new JButton("+");
btnPlus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum = Double.parseDouble(textField.getText());
textField.setText("");
operations = "+";
}
});
btnPlus.setFont(new Font("Tahoma", Font.BOLD, 18));
btnPlus.setBounds(178, 54, 50, 50);
frame.getContentPane().add(btnPlus);
//--------------Row 2-------------------
final JButton btn7 = new JButton("7");
btn7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn7.getText();
textField.setText(EnterNumber);
}
});
btn7.setFont(new Font("Tahoma", Font.BOLD, 18));
btn7.setBounds(10, 110, 50, 50);
frame.getContentPane().add(btn7);
final JButton btn8 = new JButton("8");
btn8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn8.getText();
textField.setText(EnterNumber);
}
});
btn8.setFont(new Font("Tahoma", Font.BOLD, 18));
btn8.setBounds(66, 110, 50, 50);
frame.getContentPane().add(btn8);
final JButton btn9 = new JButton("9");
btn9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn9.getText();
textField.setText(EnterNumber);
}
});
btn9.setFont(new Font("Tahoma", Font.BOLD, 18));
btn9.setBounds(122, 110, 50, 50);
frame.getContentPane().add(btn9);
JButton btnSubtract = new JButton("-");
btnSubtract.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum = Double.parseDouble(textField.getText());
textField.setText("");
operations = "-";
}
});
btnSubtract.setFont(new Font("Tahoma", Font.BOLD, 18));
btnSubtract.setBounds(178, 110, 50, 50);
frame.getContentPane().add(btnSubtract);
//----------------Row 3------------------------
final JButton btn4 = new JButton("4");
btn4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn4.getText();
textField.setText(EnterNumber);
}
});
btn4.setFont(new Font("Tahoma", Font.BOLD, 18));
btn4.setBounds(10, 166, 50, 50);
frame.getContentPane().add(btn4);
final JButton btn5 = new JButton("5");
btn5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn5.getText();
textField.setText(EnterNumber);
}
});
btn5.setFont(new Font("Tahoma", Font.BOLD, 18));
btn5.setBounds(66, 166, 50, 50);
frame.getContentPane().add(btn5);
final JButton btn6 = new JButton("6");
btn6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn6.getText();
textField.setText(EnterNumber);
}
});
btn6.setFont(new Font("Tahoma", Font.BOLD, 18));
btn6.setBounds(122, 166, 50, 50);
frame.getContentPane().add(btn6);
JButton btnMultiply = new JButton("*");
btnMultiply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum = Double.parseDouble(textField.getText());
textField.setText("");
operations = "*";
}
});
btnMultiply.setFont(new Font("Tahoma", Font.BOLD, 18));
btnMultiply.setBounds(178, 166, 50, 50);
frame.getContentPane().add(btnMultiply);
//----------------Row 4------------------------
final JButton btn1 = new JButton("1");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn1.getText();
textField.setText(EnterNumber);
}
});
btn1.setFont(new Font("Tahoma", Font.BOLD, 18));
btn1.setBounds(10, 222, 50, 50);
frame.getContentPane().add(btn1);
final JButton btn2 = new JButton("2");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn2.getText();
textField.setText(EnterNumber);
}
});
btn2.setFont(new Font("Tahoma", Font.BOLD, 18));
btn2.setBounds(66, 222, 50, 50);
frame.getContentPane().add(btn2);
final JButton btn3 = new JButton("3");
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn3.getText();
textField.setText(EnterNumber);
}
});
btn3.setFont(new Font("Tahoma", Font.BOLD, 18));
btn3.setBounds(122, 222, 50, 50);
frame.getContentPane().add(btn3);
JButton btnDivide = new JButton("/");
btnDivide.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
firstnum = Double.parseDouble(textField.getText());
textField.setText("");
operations = "/";
}
});
btnDivide.setFont(new Font("Tahoma", Font.BOLD, 18));
btnDivide.setBounds(178, 222, 50, 50);
frame.getContentPane().add(btnDivide);
//----------------Row 5------------------------
JButton btnEquals = new JButton("=");
btnEquals.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String answer;
secondnum = Double.parseDouble(textField.getText());
if (operations == "+"){
result = firstnum + secondnum;
answer = String.valueOf(result);
textField.setText(answer);
}
else if (operations == "-"){
result = firstnum - secondnum;
answer = String.valueOf(result);
textField.setText(answer);
}
else if (operations == "*"){
result = firstnum * secondnum;
answer = String.valueOf(result);
textField.setText(answer);
}
else if (operations == "/"){
result = firstnum / secondnum;
answer = String.valueOf(result);
textField.setText(answer);
}
else if (operations == "%"){
result = firstnum % secondnum;
answer = String.valueOf(result);
textField.setText(answer);
}
}
});
btnEquals.setFont(new Font("Tahoma", Font.BOLD, 18));
btnEquals.setBounds(178, 278, 50, 50);
frame.getContentPane().add(btnEquals);
JButton btnPM = new JButton("\u00B1");
btnPM.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double ops = Double.parseDouble(String.valueOf(textField.getText()));
ops =ops * (-1);
textField.setText(String.valueOf(ops));
}
});
btnPM.setFont(new Font("Tahoma", Font.BOLD, 18));
btnPM.setBounds(122, 278, 50, 50);
frame.getContentPane().add(btnPM);
final JButton btnDecimal = new JButton(".");
btnDecimal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!textField.getText().contains(".")) {
textField.setText(textField.getText() + btnDecimal.getText());
}
}
});
btnDecimal.setFont(new Font("Tahoma", Font.BOLD, 18));
btnDecimal.setBounds(66, 278, 50, 50);
frame.getContentPane().add(btnDecimal);
final JButton btn0 = new JButton("0");
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String EnterNumber = textField.getText() + btn0.getText();
textField.setText(EnterNumber);
}
});
btn0.setFont(new Font("Tahoma", Font.BOLD, 18));
btn0.setBounds(10, 278, 50, 50);
frame.getContentPane().add(btn0);
}
}
// I got this code from DJ Oamen on YouTube from his Java Calculator Project
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Objetos;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.Sprite;
/**
*
* @author Alberto Ortiz
*/
public class ControladorPowerUps {
private Vector contenedor;
public ControladorPowerUps() {
this.contenedor = new Vector();
}
public void vaciarControlador() {
this.contenedor.removeAllElements();
}
public int getSize() {
return this.contenedor.size();
}
public void BorrarPowerup(PowerUp powerup) {
this.contenedor.removeElement(powerup);
}
public void AgregarPowerUp(PowerUp powerup) {
this.contenedor.addElement(powerup);
}
public PowerUp PowerUpAt(int index) {
return (PowerUp) this.contenedor.elementAt(index);
}
public void dibujar(Graphics g) {
for (int i = 0; i < this.contenedor.size() - 1; i++) {
PowerUp temporal = (PowerUp) this.contenedor.elementAt(i);
temporal.dibujar(g);
}
}
public void actualizar(int tiempo) {
for (int i = 0; i < this.contenedor.size() - 1; i++) {
PowerUp temporal = (PowerUp) this.contenedor.elementAt(i);
temporal.actualizar(tiempo);
if (temporal.destruido) {
this.contenedor.removeElementAt(i);
}
}
}
}
|
package view;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import service.*;
import entity.Income;
import entity.UserInfo;
/**
* 收入表窗体
* @author 甘运标,吴舟
*
*/
public class FindIncome extends JFrame {
private JTable jTable;
private DefaultTableModel dtm;
private JScrollPane jScrollPane;
private IncomService incomeService = new IncomService();
private FindIncomeJpanel findIncomeJpanel = new FindIncomeJpanel();
private IncomeTableJpanel incomeTableJpanel=new IncomeTableJpanel();
private static Income income = new Income();
private List<Income> list;
private String where;
private UserService userService=new UserService();
public FindIncome( String where) {
this.setTitle("收入情况");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// 自动适配所有控件大小
this.setSize(600, 600);
// frame.pack();
// 设置窗体位置在屏幕中央
this.setLayout(null);// 设置当前窗体空布局
this.setLocationRelativeTo(null);
this.setResizable(false);
// this.setUndecorated(true);
// this.setExtendedState(JFrame.MAXIMIZED_BOTH); // 最大化
this.setContentPane(incomeTableJpanel);//设置背景图片
this.init();
this.where=where;
this.bindData();
// 显示窗体
this.setVisible(true);
}
public void init() {
this.jTable= new JTable() {
public boolean isCellEditable(int row, int column) {
return false;
}
};
this.jTable.setBackground(Color.gray);
this.jTable.setForeground(Color.blue);
this.jTable.setGridColor(Color.blue);
this.jScrollPane = new JScrollPane();
this.jScrollPane.getViewport().add(jTable);
this.jScrollPane.setBounds(0, 150, 595, 422);
this.add(jScrollPane);
}
public void bindData() {
Income in=new Income();
IncomService incomeservice = new IncomService();
in.setI_data("%"+where+"%");
if(where.equals("")){
List<Income> incomeList4=incomeservice.getI_MoneyByYear(in);
String[] co = new String[] { "年", "收入情况" };
this.dtm = new DefaultTableModel(new Object[][] {}, co);
this.jTable.setModel(dtm);
for(Income i:incomeList4){
String[] month =i.getI_data().split("-");
this.dtm.addRow(new Object[]{month[0]+"年","收入"+i.getI_money()+"元"});
}
}
else{
if(where.split("-").length==1){
List<Income> incomeList2 = incomeservice.getI_MoneyByMonth(in);
String[] co = new String[] { "月份", "收入情况" };
this.dtm = new DefaultTableModel(new Object[][] {}, co);
this.jTable.setModel(dtm);
for(Income i:incomeList2){
String[] month =i.getI_data().split("-");
this.dtm.addRow(new Object[]{month[1]+"月","收入"+i.getI_money()+"元"});
}
}
if(where.split("-").length==2){
List<Income> incomeList = incomeservice.getI_MoneyByDay(in);
String[] co = new String[] { "日", "收入情况"};
this.dtm = new DefaultTableModel(new Object[][] {}, co);
this.jTable.setModel(dtm);
for(Income i:incomeList){
String[] day =i.getI_data().split("-");
String[] _day=day[2].split(" ");
this.dtm.addRow(new Object[]{day[0]+"年"+day[1]+"月"+_day[0]+"号","收入"+i.getI_money()+"元"});
}
}
if(where.split("-").length==3){
List<Income> incomeList3 = incomeservice.getIncome(in);
String[] co = new String[] { "时刻", "收入情况" };
this.dtm = new DefaultTableModel(new Object[][] {}, co);
this.jTable.setModel(dtm);
for(Income i:incomeList3){
String[] day =i.getI_data().split("-");
String[] _day=day[2].split(" ");
this.dtm.addRow(new Object[]{day[0]+"年"+day[1]+"月"+_day[0]+"号"+_day[1]+"时刻","收入"+i.getI_money()+"元"});
}
}
}
}
}
|
package com.spring.boot.rocks.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.spring.boot.rocks.model.AppUser;
@Repository
public interface UserRepository extends JpaRepository<AppUser, Long> {
AppUser findByUsername(String username);
// AppUser findByid(Long id);
}
|
package lesson4.homework;
import java.util.Scanner;
public class Faktorial {
public static void main(String[] args) {
int a;
long b = 1;
Scanner scan = new Scanner(System.in);
System.out.print("Введите натурально число: ");
if (scan.hasNextInt()) {
a = scan.nextInt();
for (int i = a; i > 0; i--) {
b = b * i;
}
System.out.println("Факториал числа " +a+ " = " + b);
}
else {
System.out.println("Вы ввелине верное значение.");
}
}
}
|
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* 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 monasca.api.app.validation;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import java.util.Map;
@Test
public class ValidationTest {
public void testSimpleParseAndValidateDimensions() {
final Map<String, String> dimensions = Validation.parseAndValidateDimensions("aa:bb,cc:dd");
assertEquals(dimensions.size(), 2);
assertEquals(dimensions.get("aa"), "bb");
assertEquals(dimensions.get("cc"), "dd");
}
public void testParseAndValidateDimensionsWithColon() {
final Map<String, String> dimensions = Validation.parseAndValidateDimensions("aa:bb,url:http://localhost:8081/healthcheck");
assertEquals(dimensions.size(), 2);
assertEquals(dimensions.get("aa"), "bb");
assertEquals(dimensions.get("url"), "http://localhost:8081/healthcheck");
}
}
|
package com.websharp.async;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.websharputil.file.FileUtil;
import android.os.AsyncTask;
public class AsyncDownloadFile extends AsyncTask<Void, Integer, Boolean> {
public String fileUrl = "";
public String fileName = "";
public String savePath = "";
public DownloadListener listener;
public boolean stop = false;
protected void onPreExecute() {
if (listener != null)
listener.DownlaodPre();
};
@Override
protected Boolean doInBackground(Void... params) {
try {
int count;
File f = new File(savePath + fileName);
if (f.exists()) {
f.delete();
}
URL url = new URL(fileUrl);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(savePath + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 && !stop) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (listener != null)
listener.DownloadProgress(values[0]);
}
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
if (listener != null)
listener.DownloadCancel();
}
protected void onPostExecute(Boolean result) {
if (listener != null)
listener.DownloadComplete(result);
};
public void setDownloadListener(DownloadListener lis) {
this.listener = lis;
}
public interface DownloadListener {
public void DownlaodPre();
public void DownloadComplete(boolean result);
public void DownloadCancel();
public void DownloadProgress(int progress);
}
}
|
package com.research.robertodvp.audioanalyzer;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Created by robertov on 16/05/2017.
*/
public class PersonListItemView extends GridLayout {
TextView mNameView;
TextView mAddressView;
TextView mAgeView;
ImageView mImageView;
public static PersonListItemView inflate(ViewGroup parent) {
return (PersonListItemView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.li_person, parent, false);
}
public PersonListItemView(Context context) {
super(context);
}
public PersonListItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PersonListItemView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mNameView = (TextView) findViewById(R.id.name);
mAddressView = (TextView) findViewById(R.id.address);
mAgeView = (TextView) findViewById(R.id.age);
mImageView = (ImageView) findViewById(R.id.image);
}
public void populate(Person p) {
mNameView.setText(p.mName == null ? "Unknown" : p.mName );
mAddressView.setText(p.mAddress == null ? "Unknown" : p.mAddress);
mAgeView.setText(p.mAge < 0 ? "Unknown" : String.valueOf(p.mAge));
if (p.mAvatarUri == null) {
mImageView.setVisibility(View.VISIBLE);
// mImageView.setVisibility(View.GONE);
} else {
mImageView.setVisibility(View.VISIBLE);
mImageView.setImageURI(p.mAvatarUri);
}
}
}
|
package com.systex.sysgateii.util;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.Arrays;
public class StrUtil {
public static boolean isNotEmpty(String s) {
if (s == null || s.isEmpty()) {
return false;
}
return true;
}
public static boolean isEmpty(String s) {
return !isNotEmpty(s);
}
public static boolean isNumeric(String s) {
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(s, pos);
return s.length() == pos.getIndex();
}
public static String padOnRight(String org, byte pad, int newLength) {
if (org.length() > newLength) {
return org;
}
byte[] newArr = new byte[newLength];
Arrays.fill(newArr, pad);
byte[] orgByteArr = org.getBytes();
System.arraycopy(orgByteArr, 0, newArr, 0, orgByteArr.length);
return new String(newArr);
}
public static String padSpace(String org, int len) {
String org_text = padOnRight(org, (byte) 0x20, len);
if (org_text.length() > len) {
org_text = org_text.substring(0, len);
}
return org_text;
}
/**
* 左補零
*
* @param org
* @param newLength
* @return
*/
public static String padZeroLeft(String org, int newLength) {
return padOnLeft(org, (byte) 0x30, newLength);
}
/**
* 左補滿 當 newLength 的值小於 輸入字串長度時,回傳原有字串
*
* @param org 原有的字串
* @param pad 要補滿的字元(byte)
* @param newLength 長度
* @return 補滿的字串
*/
public static String padOnLeft(String org, byte pad, int newLength) {
if (org.length() > newLength) {
return org;
}
byte[] newArr = new byte[newLength];
Arrays.fill(newArr, pad);
byte[] orgByteArr = org.getBytes();
System.arraycopy(orgByteArr, 0, newArr, newArr.length - orgByteArr.length, orgByteArr.length);
return new String(newArr);
}
public static void main(String args[]) {
System.out.println(padSpace("12345678901", 10) + "*");
}
}
|
package HW7;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Comparator;
//Changes made to check exception.In evaluate function,1.0 is chaged to 1 to check exception. An exception is added in evaluate function(commented). If it is uncommented the program will run even if error is thrown in evaluate function
//Assertion added in add function. If we add values less than 0, it will throw exception
public class StorageOrderNewGenerics<E extends Comparable<E>> {
int initialSize = 2;
int filled = 0;
E[] data;
E[] localData;
static int interatorPosition = 0;
Comparator<E> comparator;
Class<E> eclass;
public E[] arrayInitialize(int size) {
E[] x = (E[]) Array.newInstance(eclass, size);
return (x);
}
public StorageOrderNewGenerics(Comparator<E> comparator, Class<E> eclass) {
//data = (E[]) Array.newInstance(initialSize);
this.eclass = eclass;
data = arrayInitialize(initialSize);
for (int index = 0; index < data.length - 1; index++) {
data[index] = null;
}
this.comparator = comparator;
}
public void copy(E[] to, E[] from) {
for (int index = 0; index < filled; index++) {
to[index] = from[index];
}
}
public void sort() {
if (data.length == 1)
return;
localData = arrayInitialize(filled);
copy(localData, data);
mergesort(0, localData.length - 1);
copy(data, localData);
}
void mergesort(int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
mergesort(l, m);
mergesort(m + 1, r);
// Merge the sorted halves
merge(l, m, r);
}
}
void merge(int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;//we added +1 here because, we are passing index and the length of array must be index+1
int n2 = r - m;
/* Create temp arrays */
E[] L = arrayInitialize(n1);
E R[] = arrayInitialize(n2);
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = localData[l + i];
for (int j = 0; j < n2; ++j)
R[j] = localData[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (comparator.compare(L[i], R[j]) < 0) {
localData[k] = L[i];
i++;
} else {
localData[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
localData[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of L[] if any */
while (j < n2) {
localData[k] = R[j];
j++;
k++;
}
}
public String toInteger() {
String result = "";
for (int index = 0; index < data.length - 1; index++) {
if (data[index] != null)
result = "" + index + ". " + data[index] +
((index == data.length - 1) ? "." : ",\n") + result;
}
return result;
}
public boolean add(E e) {
assert 0<=Integer.parseInt(e.toString()):-1;
for (int index = 0; index < data.length - 1; index++) {
if (data[index] == null) {
data[index] = e;
filled++;
sort();
return true;
}
}
if (filled < data.length) {
localData = arrayInitialize(data.length * 2);
copy(localData, data);
data = localData;
return (add(e));
}
return false;
}
public boolean remove(E e) {
for (int index = 0; index < filled; index++) {
if (data[index].compareTo(e) == 0) {
data[index] = data[filled - 1];
data[filled - 1] = null;
filled--;
sort();
return true;
}
}
return false;
}
public boolean contain(E e) {
for (int index = 0; index < filled; index++) {
if (data[index].compareTo(e) == 0)
return true;
}
return false;
}
public int size() {
return filled - 1;
}
public void startFromBeginning() {
interatorPosition = 0;
}
public boolean hasNext() {
return (interatorPosition < filled);
}
public E next() {
return data[interatorPosition++];
}
public boolean addAll(StorageOrderNewGenerics<? super E> c) {
while (c.hasNext()) {
add((E)c.next());
}
return true;
}
public double evaluate() {
double result = 0;
while (hasNext()) {
try {
E aInteger = next();
// if (aInteger!=0) {
result += 1.0 / Integer.parseInt(aInteger.toString());
//}
} catch (Exception ex) {
System.out.println("The input type is not integer");
}
}
return result;
}
public static void main(String args[]) {
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
};
StorageOrderNewGenerics<String> aStorageOrderNewGenerics = new StorageOrderNewGenerics<String>(comparator, String.class);
try {
aStorageOrderNewGenerics.add("asd");
aStorageOrderNewGenerics.add("sdf");
aStorageOrderNewGenerics.add("sfs");
aStorageOrderNewGenerics.add("dasd");
aStorageOrderNewGenerics.add("adsd");
aStorageOrderNewGenerics.add("Aaa");
// try {
// aStorageOrderNewGenerics.add(Integer.parseInt("abcd"));
// } catch (NumberFormatException ex) {
// System.out.println("Please enter a valid integer");
// }
//System.out.println("aStorageOrderNewGenerics.evaluate(); " + aStorageOrderNewGenerics.evaluate());
System.out.println(aStorageOrderNewGenerics);
System.out.println("aStorageOrderNewSort.contains(a) " + aStorageOrderNewGenerics.contain("aaa"));
// System.out.println("aStorageOrderNewSort.contains(f) " + aStorageOrderNewGenerics.contain(4));
// System.out.println("aStorageOrderNewSort.remove(a) " + aStorageOrderNewGenerics.remove(2));
// System.out.println("aStorageOrderNewSort.remove(a) " + aStorageOrderNewGenerics.remove(1));
System.out.println(aStorageOrderNewGenerics);
aStorageOrderNewGenerics.startFromBeginning();
while (aStorageOrderNewGenerics.hasNext()) {
System.out.println(" " + aStorageOrderNewGenerics.next());
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
|
package main.java.com.utilities;
/*
* Represents item being used for training/testing
*
* Author: Dylan Lasher
*/
import main.java.com.deepNeuralNetwork.Matrix;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Item
{
private final double[] features;
private final int label;
public Item(double[] features, int label)
{
this.features = features;
this.label = label;
}
public int getLabel()
{
return label;
}
public double[] getFeatures()
{
return features;
}
public Matrix toX()
{
return new Matrix(this.features.length, 1, this.features);
}
public Matrix toY()
{
return new Matrix(this.label);
}
public Matrix toYoneHot(int labels)
{
double[] oneHotVec = Utils.oneHotVec(this.label, labels);
return Matrix.columnVec(oneHotVec);
}
public static Matrix toX(List<Item> items)
{
List<Matrix> list = new ArrayList<>(items.size());
for (Item item : items)
{
list.add(item.toX());
}
return Matrix.appendColumns(list);
}
public static Matrix toY(List<Item> items)
{
List<Matrix> list = new ArrayList<>(items.size());
for (Item item : items)
{
list.add(item.toY());
}
return Matrix.appendColumns(list);
}
public static Matrix toYoneHot(List<Item> items, int labels)
{
List<Matrix> list = new ArrayList<>(items.size());
for (Item item : items)
{
list.add(item.toYoneHot(labels));
}
return Matrix.appendColumns(list);
}
public static Map<Integer, List<Item>> toMap(List<Item> items)
{
Map<Integer, List<Item>> map = new HashMap<>();
for (Item item : items)
{
List<Item> list = map.get(item.label);
if(list == null)
{
list = new ArrayList<>();
map.put(item.label, list);
}
list.add(item);
}
return map;
}
}
|
package com.smxknife.java2.collections.list;
import java.util.Vector;
/**
* @author smxknife
* 2020/7/9
*/
public class VectorDemo {
public static void main(String[] args) {
Vector<Integer> vector = new Vector<>();
vector.elements();
}
}
|
package com.smxknife.mianshi;
import java.util.Objects;
/**
* 单向链表归并排序
* 由于链表(LinkedList)不支持随机访问(Random Access),只允许顺序访问,
* 因此对于链表的O(logn)时间复杂度的排序算法不可以采用诸如快速排序等基于随机访问的排序算法,而归并排序可以满足这一需求
*
* 分治思想
* 1. 采用快慢指针找到中间元算
* 2. 先排左表,再排右表
* 3. 合并
* @author smxknife
* 2021/6/2
*/
public class _07_DanXiangLianBiaoGuiBingPaiXu {
public static void main(String[] args) {
Node head = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(4);
Node node4 = new Node(3);
head.next = node2;
node2.next = node3;
node3.next = node4;
Node sortN = sort(head);
for (;sortN != null; sortN = sortN.next) {
System.out.println(sortN.value);
}
}
private static Node sort(Node head) {
if (head == null || head.next == null) {
return head;
}
final Node middle = getMiddle(head);
final Node right = middle.next;
middle.next = null;
return mergeSort(sort(head), sort(right));
}
/**
* @param leftP
* @param rightP
* @return
*/
private static Node mergeSort(Node leftP, Node rightP) {
Node subHead = new Node(0);
Node curr = subHead;
Node left = leftP;
Node right = rightP;
while (left != null && right != null) {
final int lv = left.value;
final int rv = right.value;
Node min = null;
if (lv < rv) {
min = left;
left = left.next;
} else {
min = right;
right = right.next;
}
min.next = null;
curr.next = min;
curr = min;
}
curr.next = (left == null) ? right : left;
return subHead.next;
}
private static Node getMiddle(Node head) {
if (Objects.isNull(head)) {
return null;
}
Node slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private static class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.