text
stringlengths 10
2.72M
|
|---|
import Entidades.Articulo;
import Entidades.Usuario;
import freemarker.template.Configuration;
import org.apache.commons.codec.binary.Hex;
import spark.ModelAndView;
import spark.Request;
import spark.Spark;
import spark.template.freemarker.FreeMarkerEngine;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static spark.Spark.*;
public class Main {
private static JavaCrud _crud = null;
public static void main(String[] args) {
Spark.staticFiles.location( "/www" );
Map<String, Object> attributes = new HashMap<>( );
try {
_crud = new JavaCrud( );
//_crud.runSetUp();
} catch ( Exception e ){
//
}
Configuration configuration = new Configuration();
configuration.setClassForTemplateLoading(Main.class, "/Templates");
FreeMarkerEngine freeMarkerEngine = new FreeMarkerEngine(configuration);
before( ( request, response ) -> {
request.session(true);
setLogeado( attributes, request );
attributes.put( "hide_chat", false );
attributes.put( "session_id", request.session( ).id( ) );
} );
after( (request, response) ->{
if( attributes.containsKey( "autor_needed" ) && attributes.get("autor_needed").equals(true) && ( attributes.get( "autor" ).equals( false ) && attributes.get( "administrator" ).equals( false ) ) ){
halt( "No cuenta con permisos de autor!" );
}
if( attributes.containsKey( "administrator_needed" ) && attributes.get("administrator_needed").equals(true) && attributes.get( "administrator" ).equals( false ) ){
halt( "No cuenta con permisos de administrador!" );
}
} );
get( "/", (request, response) -> {
int n_pagina = 1;
int etiqueta = 0;
String id_etiqueta = request.queryParams( "etiqueta" );
String pagina = request.queryParams( "p" );
if( id_etiqueta != null ){
if( !isInteger( id_etiqueta ) ){
halt("No es un id de etiqueta valido!" );
}
etiqueta = Integer.parseInt( id_etiqueta );
}
else {
id_etiqueta = "0";
}
if( pagina != null && isInteger( pagina ) ){
n_pagina = Integer.parseInt( pagina );
}
attributes.put("autor_needed", false );
attributes.put("administrator_needed", false );
int n_paginas = (int) Math.ceil( _crud.totalArticulos( Integer.parseInt( id_etiqueta ) ) );
List< Articulo > articulos = _crud.oArticulos( etiqueta, n_pagina );
if( ( n_pagina <= 0 || n_pagina > n_paginas ) ){
halt( 404, "El contenido que busca no existe!" );
}
attributes.put( "articulos", articulos );
attributes.put( "p_actual", n_pagina );
attributes.put( "n_paginas", n_paginas );
attributes.put( "id_etiqueta", id_etiqueta );
attributes.put( "titulo", "Inicio" );
return new ModelAndView( attributes, "index.ftl" );
}, freeMarkerEngine );
get( "/creararticulo", (request, response) -> {
attributes.put( "titulo", "Crear articulo" );
attributes.put( "autor_needed", true );
attributes.put( "articulo", new Articulo( ) );
attributes.put( "etiquetas", new ArrayList<>());
attributes.put( "action", "/creararticulo" );
return new ModelAndView( attributes, "manejararticulo.ftl" );
}, freeMarkerEngine );
get( "/manejararticulo/:id_articulo", (request, response) -> {
attributes.put( "titulo", "Editar articulo" );
int id_articulo = Integer.parseInt( request.params( "id_articulo" ) );
//Permisos
attributes.put( "autor_needed", true );
Articulo articulo = _crud.oArticulo( id_articulo );
if( articulo == null ){
halt( 404, "No existe el articulo!");
}
attributes.put( "articulo", articulo );
attributes.put( "action", "/manejararticulo" );
return new ModelAndView( attributes, "manejararticulo.ftl" );
}, freeMarkerEngine );
get( "/usuario/:id_usuario", (request, response) -> {
attributes.put( "titulo", "Editar usuario" );
String id_usuario = request.params( "id_usuario" );
if( id_usuario == null || !isInteger(id_usuario) ){
halt(404, "No existe el usuario!!");
}
int id_usuario_int = Integer.parseInt( id_usuario );
Usuario usuario = _crud.oUsuario( id_usuario_int );
if( usuario == null ) halt(404, "No existe el usuario!");
if( attributes.get("administrator").equals(false) && Integer.parseInt( request.cookie("user_id") ) != usuario.getId()) halt(403, "No tiene permisos de acceso a esta seccion!");
attributes.put( "usuario", _crud.oUsuario( id_usuario_int ) );
attributes.put( "action", "/actualizarusuario" );
return new ModelAndView( attributes, "manejarusuario.ftl" );
}, freeMarkerEngine );
get( "/crearusuario", (request, response) -> {
attributes.put( "titulo", "Crear usuario" );
//Permisos
attributes.put( "administrator_needed", true );
Usuario usuario = new Usuario( );
attributes.put( "usuario", usuario );
attributes.put( "action", "/crearusuario" );
return new ModelAndView( attributes, "manejarusuario.ftl" );
}, freeMarkerEngine );
get( "/entrar", (request, response) -> {
if( attributes.get("logeado").equals(true) ){
response.redirect("/");
}
attributes.put( "titulo", "Entrar en mi cuenta" );
return new ModelAndView( attributes, "entrar.ftl" );
}, freeMarkerEngine );
get( "/articulo/:id", (request, response) -> {
attributes.put( "titulo", "Ver articulo" );
int id_articulo = Integer.parseInt( request.params("id") );
Articulo articulo = null;
Usuario usuario = null;
try {
int id_usuario = 0;
if( attributes.get("logeado").equals(true)){
id_usuario = Integer.parseInt(request.cookie("user_id"));
}
articulo = _crud.oArticulo(id_articulo);
usuario = _crud.oUsuario( id_usuario );
if( usuario == null ){
usuario = new Usuario();
usuario.setNombre("");
usuario.setAutor(false);
usuario.setAdministrator(false);
usuario.setId(0);
}
attributes.put("autor_needed", false );
attributes.put("administrator_needed", false );
if( articulo == null ) halt( 404, "El articulo no existe!" );
attributes.put( "articulo", articulo );
attributes.put( "usuario", usuario );
}
catch ( Exception e ){
System.out.print(e);
e.printStackTrace();
}
return new ModelAndView( attributes, "articulo.ftl" );
}, freeMarkerEngine );
get( "/registro", (request, response) -> {
attributes.put( "titulo", "Registrarme" );
if( attributes.get("logeado").equals(true) ){
response.redirect("/");
}
attributes.put("usuario", new Usuario( ) );
attributes.put("administrator", false );
attributes.put("action", "registro" );
return new ModelAndView( attributes, "manejarusuario.ftl" );
}, freeMarkerEngine );
get( "/usuarios", (request, response) -> {
attributes.put( "titulo", "Ver usuarios" );
//Permisos
attributes.put( "administrator_needed", true );
attributes.put("usuarios", _crud.oUsuarios( ) );
return new ModelAndView( attributes, "usuarios.ftl" );
}, freeMarkerEngine );
get( "/chatroom", (request, response) -> {
attributes.put( "titulo", "Chat room" );
//Permisos
attributes.put( "autor_needed", true );
attributes.put( "hide_chat", true );
attributes.put("usuarios", _crud.oUsuarios( ) );
return new ModelAndView( attributes, "chatroom.ftl" );
}, freeMarkerEngine );
get( "/salir", (request, response) -> {
if( attributes.get("logeado").equals(true) ){
response.removeCookie("user_id");
response.redirect("/");
}
response.redirect("/");
return "";
} );
post( "/creararticulo", (request, response) -> {
if( attributes.get("autor").equals(false)){
halt( 403, "Usted no tiene permisos para crear articulos!");
}
String titulo = request.queryParams( "titulo" );
String contenido = request.queryParams( "contenido" );
String etiquetas[ ] = request.queryParamsValues( "etiquetas" );
if (titulo==null){
halt("Titulo vacio");
}
if(contenido==null){
halt("Contenido vacio");
}
if(titulo.length()> 100){
halt("EL titulo excede el limite del tamaño");
}
if(contenido.length()> 5000 ){
halt("El contenido excede el limite del tamaño");
}
if( titulo.length() == 0 ){
halt( "El titulo no puede estar vacio!" );
}
if( contenido.length() == 0 ){
halt( "El articulo debe de tener contenido!" );
}
if( request.cookie( "user_id" ) == null){
halt("No tiene permiso para crear una publicación");
}
int user_id = Integer.parseInt( request.cookies( ).get( "user_id" ) );
if( _crud.crearArticulo( titulo, contenido, user_id, etiquetas ) ) {
response.redirect("/");
return "";
} else {
return "Error creando el articulo!";
}
} );
post( "/manejararticulo", (request, response) -> {
if( attributes.get("administrator").equals(false) && attributes.get("autor").equals(false) ){
halt( 403, "Usted no tiene permisos para modificar articulos!");
}
String titulo = request.queryParams( "titulo" );
String contenido = request.queryParams( "contenido" );
String etiquetas[ ] = request.queryParamsValues( "etiquetas" );
String id = request.queryParams( "id" );
if (titulo==null){
halt("Titulo vacio");
}
if(contenido==null){
halt("Contenido vacio");
}
if(titulo.length()> 100){
halt("EL titulo excede el limite del tamaño");
}
if(contenido.length()> 5000 ){
halt("El contenido excede el limite del tamaño");
}
if( titulo.length() == 0 ){
halt( "El titulo no puede estar vacio!" );
}
if( contenido.length() == 0 ){
halt( "El articulo debe de tener contenido!" );
}
if( request.cookie( "user_id" ) == null){
halt("No tiene permiso para crear una publicación");
}
if( id == null || !isInteger( id ) ){
halt( "Id incorrecto" );
}
int id_articulo = Integer.parseInt( id );
Articulo articulo = _crud.oArticulo( id_articulo );
if( _crud.actualizarArticulo( articulo, etiquetas ) ) {
response.redirect("/articulo/" + id );
return "";
} else {
return "Error actualizando el articulo!";
}
} );
post( "/crearusuario", (request, response) -> {
String username = request.queryParams( "usuario" );
String nombre = request.queryParams( "nombre" );
String password = request.queryParams( "clave" );
boolean administrator = false;
boolean autor = false;
if (username==null){
halt("Username vacio");
}
if(nombre==null){
halt("Nombre vacio");
}
if(password==null){
halt("Password vacio");
}
if(username.length()> 20){
halt("Excede el limite del tamaño");
}
if(nombre.length()> 20 ){
halt("Excede el limite del tamaño");
}
if(password.length()> 255 ){
halt("Excede el limite del tamaño");
}
if( attributes.get("administrator").equals(true) ){
String administratorS = request.queryParams("administrator");
String autorS = request.queryParams("autor");
if( administratorS != null ) administrator = true;
if( autorS != null ) autor = true;
}
if( _crud.crearUsuario( username, nombre, password, administrator, autor ) ) {
if( attributes.get("administrator").equals(false) ) {
response.redirect("/");
}
else {
return "Usuario creado exitosamente! <a href=\"usuarios\">Ver usuarios</a>";
}
return "";
} else {
return "Error creando el usuario!";
}
} );
get( "/deletecomment/:id_comentario", (request, response) -> {
int id_comentario = Integer.parseInt( request.params( "id_comentario" ) );
//Permisos
attributes.put( "autor_needed", true );
if( _crud.borrarComentario( id_comentario ) ){
return "Comentario eliminado! <a href=\"/\">Volver al inicio</a>";
}
return "";
} );
post( "/actualizarusuario", (request, response) -> {
String username = request.queryParams( "usuario" );
String nombre = request.queryParams( "nombre" );
String password = request.queryParams( "clave" );
String administratorS = request.queryParams( "administrator" );
String autorS = request.queryParams( "autor" );
boolean administrator = false;
boolean autor = false;
if( attributes.get("administrator").equals(true) ){
administratorS = request.queryParams("administrator");
autorS = request.queryParams("autor");
if( administratorS != null ) administrator = true;
if( autorS != null ) autor = true;
}
if( attributes.get("administrator").equals(false) ) {
halt(403, "No tiene acceso a esta seccion!");
}
if (username==null){
halt("Username vacio");
}
if(nombre==null){
halt("Nombre vacio");
}
if(username.length() > 20){
halt("El usuario excede el limite del tamaño");
}
if(nombre.length()> 100 ){
halt("El nombre excede el limite del tamaño" );
}
int id = Integer.parseInt( request.queryParams( "id" ) );
Usuario usuario = new Usuario( );
usuario.setNombre(nombre);
usuario.setAdministrator(administrator);
usuario.setAutor(autor);
if( password != null ) usuario.setPassword( password );
usuario.setId( id );
usuario.setUsername( username );
if( _crud.actualizarUsuario( usuario,attributes.get("administrator").equals(true) ) ) {
if( attributes.get("administrator").equals(false) ) {
response.redirect("/");
}
else {
return "Usuario actualizado exitosamente! <a href=\"/usuarios\">Ver usuarios</a>";
}
return "";
} else {
return "Error actualizando el usuario!";
}
} );
post( "/entrar", (request, response) -> {
String usuario = request.queryParams( "usuario" );
String clave = request.queryParams( "clave" );
if( request.cookie("user_id") != null ) {
response.redirect("/");
return "";
}
Integer user_id = _crud.datosLoginCorrecto( usuario, clave );
if( user_id != null ){
response.cookie( "user_id", user_id.toString( ), 3600 );
response.redirect("/");
return "";
}
else {
return "Datos incorrectos";
}
} );
post( "/registro", (request, response) -> {
String nickname = request.queryParams( "usuario" );
String nombre = request.queryParams( "nombre" );
String clave = request.queryParams( "clave" );
if( request.cookie("user_id") != null ) {
response.redirect("/");
return "";
}
if( _crud.crearUsuario( nickname, nombre, clave, false, false ) ){
return "Usuario creado!<a href=\"/entrar\">Entrar a mi cuenta</a>";
}
else {
return "No se pudo crear el usuario";
}
} );
post( "/crearcomentario", (request, response) -> {
String comentario_cuerpo = request.queryParams( "comentario" );
if( attributes.get("logeado").equals(false) ){
halt(403,"No tiene permisos para comentar!");
}
int id_articulo = Integer.parseInt( request.queryParams("id_articulo" ) );
Articulo articulo = _crud.oArticulo( id_articulo );
Usuario usuario = _crud.oUsuario( Integer.parseInt( request.cookie( "user_id" ) ) );
if( _crud.crearComentario( comentario_cuerpo, articulo, usuario ) ){
response.redirect("/articulo/" + request.queryParams("id_articulo" ) );
}
else {
return "No se pudo crear el comentario";
}
return "";
} );
post( "/ratecomment", (request, response) -> {
if( attributes.get( "logeado" ).equals( false ) ){
halt(403, "Usted necesita estar logeado!" );
}
String comentario = request.queryParams( "id_c" );
String articulo = request.queryParams( "id_a" );
String rating = request.queryParams( "rating" );
if( articulo == null || rating == null || comentario == null || !isInteger( comentario ) || !isInteger( rating ) || !isInteger( articulo ) ){
halt( 403, "Parametros invalidos!" );
}
int id_comentario = Integer.parseInt( comentario );
int id_articulo = Integer.parseInt( articulo );
if( _crud.createCommentRate( id_comentario, Integer.parseInt( request.cookie( "user_id" ) ), rating ) ){
response.redirect( "/articulo/" + id_articulo + "#comment_" + id_comentario );
}
else {
halt( 500, "No se pudo crear el comentario" );
}
return "";
} );
post( "/ratepost", (request, response) -> {
if( attributes.get( "logeado" ).equals( false ) ){
halt(403, "Usted necesita estar logeado!" );
}
String articulo = request.queryParams( "id_a" );
String rating = request.queryParams( "rating" );
if( articulo == null || rating == null || !isInteger( rating ) || !isInteger( articulo ) ){
halt( 403, "Parametros invalidos!" );
}
int id_articulo = Integer.parseInt( articulo );
if( _crud.createPostRate( id_articulo, Integer.parseInt( request.cookie( "user_id" ) ), rating ) ){
response.redirect( "/articulo/" + id_articulo );
}
else {
halt( 500, "No se pudo crear el rating!" );
}
return "";
} );
post( "/pusher/auth", ( request, response) -> {
attributes.put( "autor_needed", false );
attributes.put( "administrator_needed", false );
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec( "76d78d64d8db9687b210".getBytes( ), "HmacSHA256");
sha256_HMAC.init( secretKey );
byte[] hash = sha256_HMAC.doFinal( ( request.queryParams("socket_id") + ":private-chat-channel" ).getBytes( ) );
String key_socket = new String( Hex.encodeHexString( hash ) );
return "{\"auth\":\"2532e367e3b179f0db38:"+ key_socket +"\"}";
} );
}
static void setLogeado( Map< String, Object > attributes, Request request ){
String cookie = request.cookie( "user_id" );
boolean logeado = false;
boolean administrator = false;
boolean autor = false;
if( cookie != null){
if( isInteger( cookie ) ) {
Usuario usuario = _crud.oUsuario(Integer.parseInt(request.cookie("user_id")));
if( usuario != null ){
logeado = true;
administrator = usuario.isAdministrator();
autor = usuario.isAutor();
}
}
}
attributes.put( "logeado", logeado );
attributes.put( "administrator", administrator );
attributes.put( "autor", autor );
}
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}
}
|
package com.asiainfo.crm.demo.service.interfaces;
import com.ai.appframe2.service.ServiceFactory;
import org.junit.Before;
import org.junit.Test;
import resource.so.bo.BOTempTestUserBean;
import resource.so.ivalues.IBOTempTestUserValue;
import java.sql.Timestamp;
public class IBOTempTestUserDAOTest {
private IBOTempTestUserSV iboTempTestUserSV;
@Before
public void setUp() throws Exception {
if (iboTempTestUserSV == null) {
iboTempTestUserSV = (IBOTempTestUserSV) ServiceFactory.getService(IBOTempTestUserSV.class);
}
}
@Test
public void testAddUsers() throws Exception {
IBOTempTestUserValue iboTempTestUserValue = (IBOTempTestUserValue) new BOTempTestUserBean();
// iboTempTestUserValue.setId();
iboTempTestUserValue.setAddr("浙江杭州");
iboTempTestUserValue.setAge(25L);
iboTempTestUserValue.setBirthday(new Timestamp(System.currentTimeMillis()));
iboTempTestUserValue.setMail("zxc@gmail.com");
iboTempTestUserValue.setName("zjy8");
iboTempTestUserValue.setQq("111111");
iboTempTestUserValue.setSex("男");
iboTempTestUserValue.setTel("155555555");
iboTempTestUserSV.addUsers(iboTempTestUserValue);
}
@Test
public void testDelUsers() throws Exception {
iboTempTestUserSV.delUser(new long[] {22L});
}
@Test
public void testUpdateUser() throws Exception {
BOTempTestUserBean boTempTestUserBean = iboTempTestUserSV.getUserById(4L);
boTempTestUserBean.setAddr("南京");
boTempTestUserBean.setName("xiaolio");
iboTempTestUserSV.updateUser((IBOTempTestUserValue) boTempTestUserBean);
}
@Test
public void testGetUserById() throws Exception {
BOTempTestUserBean boTempTestUserBean = iboTempTestUserSV.getUserById(4L);
System.out.println(boTempTestUserBean.getName());
}
@Test
public void testGetUsers() throws Exception {
BOTempTestUserBean[] users = iboTempTestUserSV.getUserList(0L,"",0,"男","","","","",null,0,999);
for (BOTempTestUserBean user:users
) {
System.out.println(user.getName());
}
}
@Test
public void testGetUsersCount() throws Exception{
int count = iboTempTestUserSV.getUserCount(0L,"",0,"男","","","","",null);
System.out.println(count);
}
}
|
package com.tencent.mm.plugin.game.ui;
import com.tencent.mm.plugin.game.ui.r.c;
import com.tencent.mm.protocal.c.yd;
import com.tencent.mm.protocal.c.ye;
import java.util.LinkedList;
public class r$b {
public int actionType;
public String appId;
public String bHt;
public long createTime;
public String dCS;
public String fky;
public String iconUrl;
public String kcb;
public ye kcc;
public String kcd;
public LinkedList<String> kce;
public int kcf;
public int kcg;
public boolean kch = false;
public boolean kci = false;
public c kcj;
public String name;
public int type;
public static r$b ap(int i, String str) {
r$b r_b = new r$b();
r_b.type = i;
r_b.name = str;
r_b.kcj = new c();
return r_b;
}
public static r$b a(yd ydVar) {
r$b r_b = new r$b();
r_b.type = 2;
r_b.name = ydVar.bHD;
r_b.fky = ydVar.jOS;
r_b.iconUrl = ydVar.lPl;
r_b.kcd = ydVar.rDG;
r_b.kcf = ydVar.rEb;
r_b.kcg = ydVar.rEc;
r_b.appId = ydVar.jQb;
r_b.dCS = ydVar.jSv;
r_b.createTime = (long) ydVar.create_time;
r_b.kcj = new c(ydVar.rDG, (byte) 0);
return r_b;
}
}
|
package com.algonquincollege.saab0018.hsvcolorpicker;
import android.app.DialogFragment;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.Observable;
import java.util.Observer;
import HSVModel.HSVModel;
/**
* The Controller for HSVModel.
* <p>
* As the Controller:
* a) event handler for the View
* b) observer of the Model (HSVModel)
* <p>
* Features the Update / React Strategy.
*
* @author Matt Saab (saab0018)
* @version 1.0
*/
public class MainActivity extends AppCompatActivity implements Observer, SeekBar.OnSeekBarChangeListener {
private static final String ABOUT_DIALOG_TAG;
private static final int HUE;
private static final int SATURATION;
private static final int VALUE;
static {
ABOUT_DIALOG_TAG = "About Dialog";
HUE = 0;
SATURATION = 1;
VALUE = 2;
}
private static final String LOG_TAG = "HSV";
//private AboutDialogFragment mAboutDialog;
private TextView mColorSwatch;
private HSVModel mModel;
private SeekBar mHueSB;
private SeekBar mSaturationSB;
private SeekBar mValueSB;
private float[] mHSV = new float[]{0.f,0.f,0.f};
private TextView mHuePrompt;
private TextView mSaturationPrompt;
private TextView mValuePrompt;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mModel = new HSVModel();
mModel.setHue(HSVModel.MIN_H);
mModel.setSaturation(HSVModel.MIN_S);
mModel.setValue(HSVModel.MIN_V);
mModel.addObserver(this);
// reference each View
mColorSwatch = (TextView) findViewById(R.id.colorSwatch);
mHueSB = (SeekBar) findViewById(R.id.hueSB);
mSaturationSB = (SeekBar) findViewById(R.id.saturationSB);
mValueSB = (SeekBar) findViewById(R.id.lightnessSB);
mHuePrompt = (TextView) findViewById(R.id.hue);
mSaturationPrompt = (TextView) findViewById(R.id.saturation);
mValuePrompt = (TextView) findViewById(R.id.lightness);
mHueSB.setMax((int) HSVModel.MAX_H);
mSaturationSB.setMax((int) HSVModel.MAX_S);
mValueSB.setMax((int) HSVModel.MAX_V);
// set the domain (i.e. max) for each component
mHueSB.setOnSeekBarChangeListener(this);
mSaturationSB.setOnSeekBarChangeListener(this);
mValueSB.setOnSeekBarChangeListener(this);
this.updateView();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
mColorSwatch.setOnLongClickListener( new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v ) {
toastMessage();
return true;
}
});
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// Did the user cause this event?
// YES > continue
// NO > leave this method
if (!fromUser) {
return;
}
// Determine which <SeekBark> caused the event (switch + case)
// GET the SeekBar's progress, and SET the model to it's new value
switch (seekBar.getId()) {
case R.id.hueSB:
mHSV[HUE] = (float) progress;
mModel.setHue(mHSV[HUE]);
mHuePrompt.setText("Hue: " + mModel.hueToString());
break;
case R.id.saturationSB:
mHSV[SATURATION] = (float) progress;
mModel.setSaturation(mHSV[SATURATION]);
mSaturationPrompt.setText("Saturation: " + mModel.saturationToString());
break;
case R.id.lightnessSB:
mHSV[VALUE] = (float) progress;
mModel.setValue(mHSV[VALUE]);
mValuePrompt.setText("Value / Ligntness: " + mModel.valueToString());
break;
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// No-Operation
}
public void onStopTrackingTouch(SeekBar seekBar) {
// No-Operation
}
@Override
public void update(Observable observable, Object data) {
this.updateView();
}
private void updateColorSwatch() {
mColorSwatch.setBackgroundColor((int)mModel.getColor());
}
private void updateHueSB() {
mHueSB.setProgress((int) mModel.getHue());
//Log.d("Hue", "" + mModel.getHue());
}
private void updateSaturationSB() {
mSaturationSB.setProgress((int) mModel.getSaturation());
//Log.d("Saturation", "" + mModel.getSaturation());
}
private void updateValueSB() {
mValueSB.setProgress((int) mModel.getValue());
//Log.d("Value", "" + mModel.getValue());
}
public void updateView() {
this.updateColorSwatch();
this.updateHueSB();
this.updateSaturationSB();
this.updateValueSB();
}
public void clearTextViews() {
mHuePrompt.setText("Hue ");
mSaturationPrompt.setText("Saturation ");
mValuePrompt.setText("Value / Lightness ");
}
public void toastMessage(){
Toast.makeText(this, mModel.toString(), Toast.LENGTH_SHORT).show();
}
public boolean colorButtonClick(View button) {
switch (button.getId()) {
case R.id.blackButton:
mModel.asBlack();
clearTextViews();
toastMessage();
break;
case R.id.redButton:
mModel.asRed();
clearTextViews();
toastMessage();
break;
case R.id.limeButton:
mModel.asLime();
clearTextViews();
toastMessage();
break;
case R.id.blueButton:
mModel.asBlue();
clearTextViews();
toastMessage();
break;
case R.id.yellowButton:
mModel.asYellow();
clearTextViews();
toastMessage();
break;
case R.id.cyanButton:
mModel.asCyan();
clearTextViews();
toastMessage();
break;
case R.id.magentaButton:
mModel.asMagenta();
clearTextViews();
toastMessage();
break;
case R.id.silverButton:
mModel.asSilver();
clearTextViews();
toastMessage();
break;
case R.id.grayButton:
mModel.asGray();
clearTextViews();
toastMessage();
break;
case R.id.maroonButton:
mModel.asMaroon();
clearTextViews();
toastMessage();
break;
case R.id.oliveButton:
mModel.asOlive();
clearTextViews();
toastMessage();
break;
case R.id.greenButton:
mModel.asGreen();
clearTextViews();
toastMessage();
break;
case R.id.purpleButton:
mModel.asPurple();
clearTextViews();
toastMessage();
break;
case R.id.tealButton:
mModel.asTeal();
clearTextViews();
toastMessage();
break;
case R.id.navyButton:
mModel.asNavy();
clearTextViews();
toastMessage();
break;
default:
return true;
}
return false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_about) {
DialogFragment newFragment = new AboutDialogFragment();
newFragment.show(getFragmentManager(), ABOUT_DIALOG_TAG);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
// ================================
// POO JAVA - IMAC 2 - ANIK Myriam
// TP 8
// Pour (dé)commenter un bloc : Cmd+Shift+/ ou Ctrl + Shift + /
// ================================
import java.util.*;
public class Main
{
public static void main(String[] args)
{
var apple1 = new Apple(20, "Golden");
var apple2 = new Apple(40, "Pink Lady");
var pear1 = new Pear(5);
// System.out.print(apple1);
// System.out.print(pear1);
// var basket = new Basket();
// basket.add(apple1);
// basket.add(apple2);
// basket.add(pear1);
// TEST QUANTITE
var basket = new Basket();
basket.add(apple1, 5); // 5 pommes
basket.add(apple2);
basket.add(pear1, 7); // 7 poires
System.out.println(basket);
// var set = new HashSet<Apple>();
// set.add(new Apple(20, "Golden"));
// System.out.println(set.contains(new Apple(20, "Golden")));
}
}
|
package org.tc.svc;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public interface WsDemo {
@WebMethod
public String sayHello(String name);
}
|
package com.qgil.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qgil.common.pojo.DatatablesView;
import com.qgil.mapper.QgilProenumMapper;
import com.qgil.pojo.QgilProenum;
import com.qgil.pojo.QgilProenumExample;
import com.qgil.pojo.QgilProenumExample.Criteria;
import com.qgil.service.QgilProEnumService;
/**
* 资产名称管理Service
* @author 陈安一
*
*/
@Service
public class QgilProEnumServiceImpl implements QgilProEnumService {
@Autowired
private QgilProenumMapper qgilproenumMapper;
@Override
public QgilProenum getQgilProenumById(long parseLong) {
QgilProenum res = qgilproenumMapper.selectByPrimaryKey(parseLong);
return res;
}
@Override
public QgilProenum getQgilProenumByName(String proenumname) {
System.out.println("impl==>" + proenumname);
QgilProenum res = qgilproenumMapper.selectByName(proenumname);
return res;
}
@Override
public int addQgilProenum(QgilProenum proenum) {
int res = qgilproenumMapper.insert(proenum);
return res;
}
@Override
public int editQgilProenum(QgilProenum proenum) {
int res = qgilproenumMapper.updateByPrimaryKey(proenum);
return res;
}
@Override
public int removeQgilProenum(long id) {
int res = qgilproenumMapper.deleteByPrimaryKey(id);
return res;
}
@Override
public DatatablesView<?> getQgilProenumsByPagedParam(QgilProenum proenum, Integer start, Integer pageSize) {
// TODO Auto-generated method stub
QgilProenumExample gme = new QgilProenumExample();
Criteria criteria = gme.createCriteria();
if (proenum.getProenumname() !=null && !"".equals(proenum.getProenumname())) {
criteria.andProenumnameLike("%"+proenum.getProenumname()+"%");
}
gme.setOrderByClause("create_time DESC LIMIT" + " " + start + "," + pageSize);
List<QgilProenum> list = qgilproenumMapper.selectByExample(gme);
int count = qgilproenumMapper.countByExample(gme);
DatatablesView result = new DatatablesView();
result.setData(list);
result.setRecordsTotal(count);
return result;
}
@Override
public DatatablesView<?> getQgilProenumsByParam(QgilProenum proenum) {
// TODO Auto-generated method stub
QgilProenumExample gme = new QgilProenumExample();
if (proenum != null && proenum.getProenumname() != null && !"".equals(proenum.getProenumname())) {
gme.createCriteria().andProenumnameEqualTo(proenum.getProenumname());
}
List<QgilProenum> list = qgilproenumMapper.selectByExample(gme);
DatatablesView result = new DatatablesView();
result.setData(list);
result.setRecordsTotal(list.size());
return result;
}
}
|
package jneiva.hexbattle.componente;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.badlogic.gdx.math.Vector2;
import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import jneiva.hexbattle.Game;
import jneiva.hexbattle.comum.Vector2Accessor;
import jneiva.hexbattle.map.Mapa;
import jneiva.hexbattle.tiles.Celula;
import jneiva.hexbattle.unidade.Unidade;
public class Movimento extends Componente {
public int alcance;
private Unidade unidade;
public Movimento(int a) {
alcance = a;
}
@Override
public void acordar() {
unidade = (Unidade) this.getEntidade();
}
public void atravessar(List<Celula> caminho) {
unidade.colocar(caminho.get(caminho.size() - 1));
unidade.turno.contadorMovimento += caminho.size();
Timeline sequencia = Timeline.createSequence();
System.out.println(Game.manager);
for (Celula cel : caminho) {
sequencia.push(andar(cel));
}
sequencia.start(Game.manager);
try {
TimeUnit.MILLISECONDS.sleep( 500 * caminho.size());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Tween andar(Celula alvo) {
Vector2 centro = alvo.posicao.getPosCentro();
return Tween.to(unidade.render.pos, Vector2Accessor.TYPE_XY, 0.5f).target(centro.x, centro.y);
}
}
|
package com.mochasoft.fk.security.mapper;
import com.mochasoft.fk.mapper.MyBatisRepository;
import com.mochasoft.fk.security.entity.RoleUser;
import java.util.List;
@MyBatisRepository
public interface RoleUserMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_ROLE_USER
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
int deleteByPrimaryKey(String id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_ROLE_USER
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
int insert(RoleUser record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_ROLE_USER
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
RoleUser selectByPrimaryKey(String id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_ROLE_USER
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
List<RoleUser> selectAll();
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table MOCHA_SECU_ROLE_USER
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
int updateByPrimaryKey(RoleUser record);
/**
* 根据用户userId获取用户的所有角色名称.
* @param userId
* @return 角色名称列表
*/
List<String> selectByUserId(String userId);
}
|
package com.jackie.classbook.common;
/**
* Created with IntelliJ IDEA.
* Description:
*
* @author xujj
* @date 2018/12/4
*/
public enum SexEnum {
MALE((byte)1, "男"), FEMALE((byte)0, "女");
private byte key;
private String value;
SexEnum(byte key, String value){
this.key = key;
this.value = value;
}
public byte getKey() {
return key;
}
public String getValue() {
return value;
}
public static String getValue(byte key){
if (MALE.getKey() == key){
return MALE.getValue();
}else if (FEMALE.getKey() == key){
return FEMALE.getValue();
}else {
return "不明";
}
}
}
|
/*
* The MIT License
*
* Copyright 2019 tibo.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package be.cylab.mark.integration;
import be.cylab.mark.client.Client;
import be.cylab.mark.core.DetectionAgentProfile;
import be.cylab.mark.core.Evidence;
import be.cylab.mark.detection.TimeAverage;
import java.net.URL;
/**
*
* @author tibo
*/
public class TimeAverageIT extends MarkCase {
public final void testTimeAverage() throws Throwable {
DetectionAgentProfile agent = new DetectionAgentProfile();
agent.setClassName(TimeAverage.class.getName());
agent.setLabel("detection.timeaverage");
agent.setTriggerLabel("data");
getActivationController().setAgentProfile(agent);
Client datastore = new Client(new URL("http://127.0.0.1:8080"));
Link link = new Link("1.2.3.4", "my.server.com");
Evidence ev = new Evidence();
ev.setLabel("data");
ev.setScore(1);
ev.setSubject(link);
datastore.addEvidence(ev);
ev.setScore(2);
datastore.addEvidence(ev);
ev.setScore(3);
datastore.addEvidence(ev);
Thread.sleep(3000);
Evidence[] ta_evidences =
datastore.findEvidence("detection.timeaverage", link);
assertTrue(ta_evidences.length > 0);
assertEquals(2.0, ta_evidences[ta_evidences.length - 1].getScore());
}
}
|
package algorithm.kakaoBlindTest._2018;
import java.util.*;
/*
* 시작: 18:10
* 끝: 20:07 틀림!
* 걸린시간: 1:57
*
* 시간을 포맷화하는 방법
* 00:00 형태의 String배열도 Arrays.sort하면 정렬이됨
*
*/
public class kakao_blind_2018_4 {
static class Time {
int hour;
int minute;
Time(String timetable) {
String hour = "";
String minute = "";
hour += timetable.charAt(0);
hour += timetable.charAt(1);
minute += timetable.charAt(3);
minute += timetable.charAt(4);
this.hour = Integer.parseInt(hour);
this.minute = Integer.parseInt(minute);
}
void add(int t) {
this.minute += t;
if (this.minute >= 60) {
this.minute = 60 - this.minute;
this.hour++;
}
}
void sub(int t) {
if (this.minute == 0) {
this.minute = 59;
this.hour--;
} else if (this.minute - t < 0) {
this.minute = 60 + (this.minute - t);
this.hour--;
} else {
this.minute -= t;
}
}
// 양수면 this가 t보다 큼, 음수면 작음
int compareTo(Time t) {
if (this.hour > t.hour) {
return 1;
} else if (this.hour == t.hour) {
if (this.minute > t.minute) {
return 1;
}
if (this.minute == t.minute) {
return 0;
} else
return -1;
} else {
return -1;
}
}
String convertString() {
return String.format("%02d", this.hour) + ":" + String.format("%02d", this.minute);
}
}
static String solution(int n, int t, int m, String[] timetable) {
/*
* 셔틀은 09:00부터 총 n회 t분 간격으로 역에 도착하며, 하나의 셔틀에는 최대 m명의 승객이 탈 수 있다. 셔틀은 도착했을 때 도착한
* 순간에 대기열에 선 크루까지 포함해서 대기 순서대로 태우고 바로 출발한다. 예를 들어 09:00에 도착한 셔틀은 자리가 있다면 09:00에
* 줄을 선 크루도 탈 수 있다. 같은 시각에 도착한 크루 중 대기열에서 제일 뒤에 선다. 모든 크루는 잠을 자야 하므로 23:59에 집에
* 돌아간다 -> 어떤 크루도 다음날 셔틀을 타는 일은 없다.
*/
String answer = "";
int tSize = timetable.length;
Time[] times = new Time[tSize];
Arrays.sort(timetable);
for (int i = 0; i < tSize; i++) {
times[i] = new Time(timetable[i]);
}
System.out.println(timetable);
// 대기열 큐 생성
Queue<Time> wq = new LinkedList<>();
for (Time time : times) {
wq.offer(time);
}
// 현재 셔틀버스에 타고있는 사람
Stack<Time> cs = new Stack<>();
// 시뮬레이션 시작
Time currentTime = new Time("09:00");
Time ans = null;
// 셔틀 운행 횟수 n, 셔틀 운행 간격 t, 한 셔틀에 탈 수 있는 최대 크루 수 m, 크루가 대기열에 도착하는 시각을 모은 배열
while (true) {
// 반복문을 돌 때마다 현재 셔틀버스에 타고 있는 사람은 0명이됨
cs.clear();
for (int i = 0; i < m; i++) {
if (wq.isEmpty()) { // 대기열이 비어있으면 반복문 종료
break;
}
if (wq.peek().compareTo(currentTime) < 0) { // 현재 시간보다 더 이전에 대기열에 들어온 크루는 대기열에서 나오고 셔틀버스에 탑승한다
// 모든 크루는 잠을 자야 하므로 23:59에 집에 돌아간다. 따라서 어떤 크루도 다음날 셔틀을 타는 일은 없다.
if (wq.peek().compareTo(new Time("23:59")) >= 0) {
wq.poll();
continue;
}
if (cs.size() <= m) {
cs.push(wq.poll());
}
}
}
if (n == 1) { // 셔틀버스의 운행횟수가 1번 남았을 때
if (cs.isEmpty()) { // 셔틀버스가 비어있으면 콘은 현재 시간에 탑승해도 된다
ans = currentTime;
break;
}
ans = cs.peek(); // 셔틀버스에 가장 마지막에 탈 수 있었던 크루가 탄 시간을 확인한다
if (ans.compareTo(new Time("09:00")) < 0) {
if (cs.size() == m) { // 크루들이 첫 차에 다 탈 수 있어서 버스가 꽉 찬다면
ans.sub(1);// 마지막 사람보다 1분 빨리오면됨
} else { // 첫 차에 자리가 남음
ans = new Time("09:00"); // 첫차시간에 타면 됨
}
} else { // 첫차가 아니면
if (cs.size() == m) { // 셔틀버스가 꽉 찼을 때
// 마지막 사람보다 1분 빨리오면됨
ans.sub(1);
} // 꽉 안찼으면 마지막에 탄 크루와 같은 시간에 타면 됨
}
break;
}
currentTime.add(t);
n--;
}
return ans.convertString(); // 콘이 셔틀을 타고 사무실로 갈 수 있는 도착 시각 중 제일 늦은 시각을 구하여라.
}
public static void main(String[] args) {
// 셔틀 운행 횟수 n, 셔틀 운행 간격 t, 한 셔틀에 탈 수 있는 최대 크루 수 m, 크루가 대기열에 도착하는 시각을 모은 배열
// int n = 1;
// int t = 1;
// int m = 5;
// String[] timetable = { "08:00", "08:01", "08:02", "08:03" };
// int n = 1;
// int t = 1;
// int m = 5;
// String[] timetable = { "08:00", "08:01", "08:02", "08:03" };
// int n = 2;
// int t = 1;
// int m = 2;
// String[] timetable = { "09:00", "09:00", "09:00", "09:00" };
int n = 10;
int t = 60;
int m = 45;
String[] timetable = { "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59", "23:59",
"23:59", "23:59", "23:59", "23:59", "23:59", "23:59" };
System.out.println(solution(n, t, m, timetable));
}
}
|
package com.tencent.mm.pluginsdk.ui.preference;
import com.tencent.mm.g.a.iq;
import com.tencent.mm.pluginsdk.c.a;
import com.tencent.mm.sdk.b.b;
class FMessageListView$1 extends a {
final /* synthetic */ FMessageListView qOF;
FMessageListView$1(FMessageListView fMessageListView) {
this.qOF = fMessageListView;
}
public final void j(b bVar) {
if (bVar instanceof iq) {
FMessageListView.a(this.qOF, ((iq) bVar).bSd.bHA);
}
}
}
|
package com.javarush.task.task19.task1909;
import java.io.*;
import java.util.ArrayList;
/*
Замена знаков
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader breader = new BufferedReader(new InputStreamReader(System.in));
String f1 = breader.readLine();
String f2 = breader.readLine();
breader.close();
BufferedReader reader = new BufferedReader(new FileReader(f1));
ArrayList<Integer> list = new ArrayList<Integer>();
while (reader.ready()) {
int data = reader.read();
list.add(data);
}
reader.close();
char a = '.';
int as = (int) a;
char s = '!';
int sa = (int) s;
ArrayList<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == as) {
l.add(sa);
} else {
l.add(list.get(i));
}
}
BufferedWriter writer = new BufferedWriter(new FileWriter(f2));
for (int i = 0; i < l.size(); i++) {
writer.write(l.get(i));
}
writer.close();
}
}
|
package com.ttan.string;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* @Description: 第一个只出现一次的字符
* @author ttan
* @time 2019年7月3日 下午2:27:57
*/
public class FirstNotRepeatingChar {
/*在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符
* ,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
*/
public int FirstNotRepeatingChar(String str) {
if (str == null || "".equals(str)) {
return -1;
}
int[] counts = new int[256];
// //用一个类似hash的东西来存储字符出现的次数
for (int i = 0; i < str.length(); i++) {
counts[str.charAt(i)]++;
}
for (int j = 0; j < counts.length; j++) {
if (counts[str.charAt(j)] == 1) {
return j;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(new FirstNotRepeatingChar().FirstNotRepeatingChar("googgle"));
}
}
|
package com.hand6.health.api.controller.v1;/**
* Created by Administrator on 2019/7/14.
*/
import com.hand6.health.app.service.impl.ReportServiceImpl;
import com.hand6.health.domain.entity.MotionSummary;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
/**
* @author xxxx
* @description
* @date 2019/7/14
*/
@RestController
@RequestMapping("/v1/report")
public class ReportController {
@Autowired
private ReportServiceImpl reportService;
@GetMapping(value = "/motionSummary")
public void motionSummary(MotionSummary motionSummary, HttpServletResponse response){
reportService.export(motionSummary,response);
}
}
|
/*
* 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.webbeans.component.creation;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.inject.Produces;
import jakarta.enterprise.inject.spi.AnnotatedMethod;
import jakarta.enterprise.inject.spi.AnnotatedParameter;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.inject.spi.BeanAttributes;
import jakarta.enterprise.inject.spi.InterceptionType;
import jakarta.interceptor.AroundConstruct;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.AroundTimeout;
import jakarta.interceptor.InvocationContext;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.webbeans.component.InterceptorBean;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.exception.WebBeansConfigurationException;
import org.apache.webbeans.plugins.OpenWebBeansEjbLCAPlugin;
import org.apache.webbeans.util.Asserts;
import org.apache.webbeans.util.ClassUtil;
/**
* Bean builder for {@link org.apache.webbeans.component.InterceptorBean}s.
*/
public abstract class InterceptorBeanBuilder<T, B extends InterceptorBean<T>> extends AbstractBeanBuilder
{
protected final WebBeansContext webBeansContext;
protected final AnnotatedType<T> annotatedType;
protected final BeanAttributes<T> beanAttributes;
private final OpenWebBeansEjbLCAPlugin ejbPlugin;
private final Class<? extends Annotation> prePassivateClass;
private final Class<? extends Annotation> postActivateClass;
protected Map<InterceptionType, Method[]> interceptionMethods;
protected InterceptorBeanBuilder(WebBeansContext webBeansContext, AnnotatedType<T> annotatedType, BeanAttributes<T> beanAttributes)
{
Asserts.assertNotNull(webBeansContext, Asserts.PARAM_NAME_WEBBEANSCONTEXT);
Asserts.assertNotNull(annotatedType, "annotated type");
Asserts.assertNotNull(beanAttributes, "beanAttributes");
this.webBeansContext = webBeansContext;
this.annotatedType = annotatedType;
this.beanAttributes = beanAttributes;
ejbPlugin = webBeansContext.getPluginLoader().getEjbLCAPlugin();
if (ejbPlugin != null)
{
prePassivateClass = ejbPlugin.getPrePassivateClass();
postActivateClass = ejbPlugin.getPostActivateClass();
}
else
{
prePassivateClass = null;
postActivateClass = null;
}
}
/**
* If this method returns <code>false</code> the {@link #getBean()} method must not get called.
*
* @return <code>true</code> if the Interceptor is enabled and a Bean should get created
*/
public abstract boolean isInterceptorEnabled();
protected void checkInterceptorConditions()
{
Set<AnnotatedMethod<? super T>> methods = webBeansContext.getAnnotatedElementFactory().getFilteredAnnotatedMethods(annotatedType);
for(AnnotatedMethod<?> method : methods)
{
for (AnnotatedParameter<?> parameter : method.getParameters())
{
if (parameter.isAnnotationPresent(Produces.class))
{
throw new WebBeansConfigurationException("Interceptor class : " + annotatedType.getJavaClass()
+ " can not have producer methods but it has one with name : "
+ method.getJavaMember().getName());
}
}
}
}
/**
* <p>Grab all methods which act as interceptors for the various
* {@link jakarta.enterprise.inject.spi.InterceptionType}s.</p>
*
* <p>This method will also check some rules, e.g. that there must not be
* more than a single {@link jakarta.interceptor.AroundInvoke} method
* on a class.</p>
*
* <p>For the interceptors where multiple are allowed, the following rules apply:
* <ul>
* <li>Superclass methods first</li>
* <li>Non-private methods override and derogates their superclass counterparts.</li>
* <li>Private methods with the same signature stack (superclass first).</li>
* <li>There must only be a single method for each InterceptorType in the same class.</li>
* </ul>
* </p>
* @return <code>true</code> if we found some interceptor methods
*/
public boolean defineInterceptorMethods()
{
List<Class> classHierarchy = webBeansContext.getInterceptorUtil().getReverseClassHierarchy(annotatedType.getJavaClass());
Collection<Method> aroundInvokeMethod = null;
List<AnnotatedMethod> postConstructMethods = new ArrayList<>();
List<AnnotatedMethod> preDestroyMethods = new ArrayList<>();
List<AnnotatedMethod> aroundTimeoutMethods = new ArrayList<>();
List<AnnotatedMethod> aroundConstructMethods = new ArrayList<>();
// EJB related interceptors
List<AnnotatedMethod> prePassivateMethods = new ArrayList<>();
List<AnnotatedMethod> postActivateMethods = new ArrayList<>();
boolean interceptorFound = false;
Set<AnnotatedMethod<? super T>> methods = webBeansContext.getAnnotatedElementFactory().getFilteredAnnotatedMethods(annotatedType);
for (Class clazz : classHierarchy)
{
for (AnnotatedMethod m : methods)
{
int arouncConstructCount = 0;
if (clazz == m.getJavaMember().getDeclaringClass())
{
if (m.getAnnotation(AroundConstruct.class) != null)
{
if (arouncConstructCount > 0)
{
throw new WebBeansConfigurationException("only one AroundConstruct allowed per Interceptor");
}
arouncConstructCount++;
aroundConstructMethods.add(m);
}
// we only take methods from this very class and not sub- or superclasses
if (m.getAnnotation(AroundInvoke.class) != null)
{
if (aroundInvokeMethod != null)
{
for (Method ai : aroundInvokeMethod)
{
if (ai.getDeclaringClass() == m.getJavaMember().getDeclaringClass())
{
throw new WebBeansConfigurationException("only one AroundInvoke allowed per Interceptor");
}
}
}
checkAroundInvokeConditions(m);
if (aroundInvokeMethod == null)
{
aroundInvokeMethod = new ArrayList<>();
}
aroundInvokeMethod.add(m.getJavaMember());
}
// PostConstruct
if (m.getAnnotation(PostConstruct.class) != null)
{
checkSameClassInterceptors(postConstructMethods, m);
postConstructMethods.add(m); // add at last position
}
// PreDestroy
if (m.getAnnotation(PreDestroy.class) != null)
{
checkSameClassInterceptors(preDestroyMethods, m);
preDestroyMethods.add(m); // add at last position
}
// AroundTimeout
if (m.getAnnotation(AroundTimeout.class) != null)
{
checkSameClassInterceptors(aroundTimeoutMethods, m);
aroundTimeoutMethods.add(m); // add at last position
}
// and now the EJB related interceptors
if (ejbPlugin != null)
{
if (m.getAnnotation(prePassivateClass) != null)
{
checkSameClassInterceptors(prePassivateMethods, m);
prePassivateMethods.add(m); // add at last position
}
// AroundTimeout
if (m.getAnnotation(AroundTimeout.class) != null)
{
checkSameClassInterceptors(aroundTimeoutMethods, m);
postActivateMethods.add(m); // add at last position
}
// AroundTimeout
if (m.getAnnotation(postActivateClass) != null)
{
checkSameClassInterceptors(postActivateMethods, m);
postActivateMethods.add(m); // add at last position
}
}
}
}
}
// and now for setting the bean info
interceptionMethods = new HashMap<>();
if (aroundInvokeMethod != null)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.AROUND_INVOKE, aroundInvokeMethod.toArray(new Method[aroundInvokeMethod.size()]));
}
if (postConstructMethods.size() > 0)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.POST_CONSTRUCT, getMethodArray(postConstructMethods));
}
if (preDestroyMethods.size() > 0)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.PRE_DESTROY, getMethodArray(preDestroyMethods));
}
if (aroundTimeoutMethods.size() > 0)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.AROUND_TIMEOUT, getMethodArray(aroundTimeoutMethods));
}
if (prePassivateMethods.size() > 0)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.PRE_PASSIVATE, getMethodArray(prePassivateMethods));
}
if (postActivateMethods.size() > 0)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.POST_ACTIVATE, getMethodArray(postActivateMethods));
}
if (aroundConstructMethods.size() > 0)
{
interceptorFound = true;
interceptionMethods.put(InterceptionType.AROUND_CONSTRUCT, getMethodArray(aroundConstructMethods));
}
return interceptorFound;
}
private void checkAroundInvokeConditions(AnnotatedMethod method)
{
List<AnnotatedParameter<T>> parameters = method.getParameters();
List<Class<?>> clazzParameters = new ArrayList<>();
for(AnnotatedParameter<T> parameter : parameters)
{
clazzParameters.add(ClassUtil.getClazz(parameter.getBaseType()));
}
Class<?>[] params = clazzParameters.toArray(new Class<?>[clazzParameters.size()]);
if (params.length != 1 || !params[0].equals(InvocationContext.class))
{
throw new WebBeansConfigurationException("@AroundInvoke annotated method : "
+ method.getJavaMember().getName() + " in class : " + annotatedType.getJavaClass().getName()
+ " can not take any formal arguments other than InvocationContext");
}
if (!method.getJavaMember().getReturnType().equals(Object.class))
{
throw new WebBeansConfigurationException("@AroundInvoke annotated method : "
+ method.getJavaMember().getName()+ " in class : " + annotatedType.getJavaClass().getName()
+ " must return Object type");
}
if (Modifier.isStatic(method.getJavaMember().getModifiers()) ||
Modifier.isFinal(method.getJavaMember().getModifiers()))
{
throw new WebBeansConfigurationException("@AroundInvoke annotated method : "
+ method.getJavaMember().getName( )+ " in class : " + annotatedType.getJavaClass().getName()
+ " can not be static or final");
}
}
/**
* @return the a Method array with the native members of the AnnotatedMethod list
*/
private Method[] getMethodArray(List<AnnotatedMethod> methodList)
{
Method[] methods = new Method[methodList.size()];
int i=0;
for (AnnotatedMethod am : methodList)
{
methods[i++] = am.getJavaMember();
}
return methods;
}
private void checkSameClassInterceptors(List<AnnotatedMethod> alreadyDefinedMethods, AnnotatedMethod annotatedMethod)
{
Class clazz = null;
for (AnnotatedMethod alreadyDefined : alreadyDefinedMethods)
{
if (clazz == null)
{
clazz = annotatedMethod.getJavaMember().getDeclaringClass();
}
// check for same class -> Exception
if (alreadyDefined.getJavaMember().getDeclaringClass() == clazz)
{
throw new WebBeansConfigurationException("Only one Interceptor of a certain type is allowed per class, but multiple found in class "
+ annotatedMethod.getJavaMember().getDeclaringClass().getName()
+ " methods: " + annotatedMethod.getJavaMember().toString()
+ " and " + alreadyDefined.getJavaMember().toString());
}
}
}
protected abstract B createBean(Class<T> beanClass,
boolean enabled,
Map<InterceptionType, Method[]> interceptionMethods);
public B getBean()
{
return createBean(annotatedType.getJavaClass(), isInterceptorEnabled(), interceptionMethods);
}
}
|
package lesson;
import patterned.Strategy;
public class YourStrategy implements Strategy {
/**
* [課題] 自分なりの戦略を実装してください
*/
@Override
public boolean highLow(int number) {
return false;
}
}
|
package Assigment1;
public class abstractscientificcalc extends Abstarctsimplecalc
{
void multiply ()
{
c = a * b *2;
System.out.println("Result of Multiplication = " + c);
}
}
|
package com.catcher.seeexpress.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "expressrecord.db";
private static final int DB_SERVION = 1;
private static final String CREATE_TABLE_EXPRESSHISTORY = "create table exhistory(exnumber primary key, extype,exname)";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_SERVION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_EXPRESSHISTORY); //创建快递查询历史记录表
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
|
package cn.org.cerambycidae.Servlet.DataBase;
import cn.org.cerambycidae.pojo.Student;
import cn.org.cerambycidae.service.Impl.StudentMybatisServiceImpl;
import cn.org.cerambycidae.service.StudentService;
import cn.org.cerambycidae.util.DataBaseUtil.NameAndAgeRequest;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.List;
@WebServlet(urlPatterns = {"/DataBase/ShowDataBaseServlet"})
public class ShowDataBaseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
PrintWriter pw = response.getWriter();
//得到查询响应数据
String name = request.getParameter("name");
name = URLDecoder.decode(name,"UTF-8");
String age = request.getParameter("age");
//数据处理,数据库连接方面,用来响应消息
StudentService service=new StudentMybatisServiceImpl();
List<Student> students = service.selectByExample(NameAndAgeRequest.Conversion(name,age));
//分页查找商品销售记录,需判断是否有带查询条件
//将商品销售记录转换成json字符串
String listJson = JSONObject.toJSONString(students);
//得到总记录数
int total = students.size();
//需要返回的数据有总记录数和行数据
String json = "{\"total\":" + total + ",\"rows\":" + listJson + "}";
pw.print(json);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
|
package com.example.csy.activitypractice;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.sunflower.FlowerCollector;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.LinkedHashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
public class SpeechRecognitionActivity extends AppCompatActivity implements View.OnClickListener {
@BindView(R.id.iat_text)
EditText iatText;
@BindView(R.id.iat_recognize)
Button iatRecognize;
@BindView(R.id.iat_stop)
Button iatStop;
@BindView(R.id.iat_cancel)
Button iatCancel;
@BindView(R.id.parent)
LinearLayout parent;
private ImageView btnClose;
private TextView tvTips;
private LinearLayout llySpeak;
private ImageView imgSpeak;
private WaveLineView waveLineView;
private PopupWindow popWnd = null;
private View contentView = null;
private static String TAG = "CSYLALA";
// 语音听写对象
private SpeechRecognizer mIat;
// 引擎类型
private String mEngineType = SpeechConstant.TYPE_CLOUD;
// 用HashMap存储听写结果
private HashMap<String, String> mIatResults = new LinkedHashMap<String, String>();
private Toast mToast;
private int ret = 0;
private static final int AUDIO_RECORD = 0;//申请打电话权限的请求码,≥0即可
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speech_recognition);
ButterKnife.bind(this);
initLayout();
requestPermissions();
}
private void requestPermissions() {
//检测是否有拨打电话的权限
int checkSelfPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {
init();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_RECORD);//动态申请打电话权限
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case AUDIO_RECORD:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
init();
} else {
Toast.makeText(this, "用户未允许打电话权限", Toast.LENGTH_SHORT).show();
boolean b = shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE);
if(!b) {
//用户没同意授权,还不让下次继续提醒授权了,这是比较糟糕的情况
Toast.makeText(this,"用户勾选了下次不再提醒选项", Toast.LENGTH_SHORT).show();
}
}
default:
break;
}
}
private void init() {
// 初始化识别无UI识别对象
// 使用SpeechRecognizer对象,可根据回调消息自定义界面;
mIat = SpeechRecognizer.createRecognizer(SpeechRecognitionActivity.this, mInitListener);
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
/**
* 初始化Layout。
*/
private void initLayout() {
iatRecognize.setOnClickListener(this);
iatStop.setOnClickListener(this);
iatCancel.setOnClickListener(this);
}
private void showTip(final String str) {
mToast.setText(str);
mToast.show();
}
/**
* 初始化监听器。
*/
private InitListener mInitListener = new InitListener() {
@Override
public void onInit(int code) {
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code);
}
}
};
/**
* 听写监听器。
*/
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onBeginOfSpeech() {
// 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
// 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。
showTip(error.getPlainDescription(true));
if (error.getErrorCode() == 10118) {
noContent();
}
}
@Override
public void onEndOfSpeech() {
// 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入
showTip("结束说话");
}
@Override
public void onResult(RecognizerResult results, boolean isLast) {
Log.d(TAG, results.getResultString());
printResult(results);
}
@Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume);
waveLineView.setVolume(30 + (int) (volume * 2.5));
waveLineView.setMoveSpeed((float) (290 - volume * 0.5));
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
// 若使用本地能力,会话id为null
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
//没有说话
private void noContent() {
if (waveLineView.isRunning()) {
waveLineView.stopAnim();
}
tvTips.setText("好像没有听清您说话呢");
imgSpeak.setVisibility(View.VISIBLE);
llySpeak.setVisibility(View.VISIBLE);
}
private void printResult(RecognizerResult results) {
String text = JsonParser.parseIatResult(results.getResultString());
String sn = null;
// 读取json结果中的sn字段
try {
JSONObject resultJson = new JSONObject(results.getResultString());
sn = resultJson.optString("sn");
} catch (JSONException e) {
e.printStackTrace();
}
mIatResults.put(sn, text);
StringBuffer resultBuffer = new StringBuffer();
for (String key : mIatResults.keySet()) {
resultBuffer.append(mIatResults.get(key));
}
if (results != null && resultBuffer.toString().length() != 0) {
iatText.setText(resultBuffer.toString());
iatText.setSelection(iatText.length());
closePopWindow();
} else {
noContent();
}
}
@Override
public void onClick(View view) {
if (null == mIat) {
// 创建单例失败,与 21001 错误为同样原因,参考 http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=9688
this.showTip("创建对象失败,请确认 libmsc.so 放置正确,且有调用 createUtility 进行初始化");
return;
}
switch (view.getId()) {
// 开始听写
case R.id.iat_recognize:
startListen();
break;
// 停止听写
case R.id.iat_stop:
mIat.stopListening();
showTip("停止听写");
break;
// 取消听写
case R.id.iat_cancel:
mIat.cancel();
showTip("取消听写");
break;
default:
break;
}
}
private void startListen() {
showPopupWindow();
// 移动数据分析,收集开始听写事件
FlowerCollector.onEvent(SpeechRecognitionActivity.this, "iat_recognize");
iatText.setText(null);// 清空显示内容
tvTips.setText("请输入内容");
mIatResults.clear();
// 设置参数
setParam();
// 不显示听写对话框
ret = mIat.startListening(mRecognizerListener);
if (ret != ErrorCode.SUCCESS) {
showTip("听写失败,错误码:" + ret);
} else {
showTip("开始了");
}
}
private void showPopupWindow() {
if (popWnd == null) {
if (contentView == null) {
contentView = LayoutInflater.from(SpeechRecognitionActivity.this).inflate(R.layout.popup_window_speak, null);
}
popWnd = new PopupWindow(ViewGroup.LayoutParams.MATCH_PARENT, 600);
popWnd.setContentView(contentView);
popWnd.setOutsideTouchable(true);
popWnd.setFocusable(true);
popWnd.setOutsideTouchable(true);
waveLineView = contentView.findViewById(R.id.waveLineView);
btnClose = contentView.findViewById(R.id.btn_close);
llySpeak = contentView.findViewById(R.id.lly_speak);
imgSpeak = contentView.findViewById(R.id.img_speak);
tvTips = contentView.findViewById(R.id.tv_tips);
}
popWnd.setAnimationStyle(R.style.mypopwindow_anim_style);
popWnd.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
if (waveLineView.isRunning()) {
waveLineView.stopAnim();
}
waveLineView.startAnim();
llySpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startListen();
}
});
btnClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
closePopWindow();
}
});
popWnd.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
closePopWindow();
}
});
}
private void closePopWindow() {
imgSpeak.setVisibility(View.GONE);
llySpeak.setVisibility(View.GONE);
popWnd.dismiss();
waveLineView.stopAnim();
mIat.stopListening();//取消听写
}
/**
* 参数设置
*
* @return
*/
public void setParam() {
// 清空参数
mIat.setParameter(SpeechConstant.PARAMS, null);
// 设置听写引擎
mIat.setParameter(SpeechConstant.ENGINE_TYPE, mEngineType);
// 设置返回结果格式
mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
String lag = "mandarin";
// 设置语言
mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
// 设置语言区域
mIat.setParameter(SpeechConstant.ACCENT, lag);
//此处用于设置dialog中不显示错误码信息
//mIat.setParameter("view_tips_plain","false");
// 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理
mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
// 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音
mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
mIat.setParameter(SpeechConstant.ASR_PTT, "1");
// 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
// 注:AUDIO_FORMAT参数语记需要更新版本才能生效
mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
}
@Override
protected void onResume() {
// 开放统计 移动数据统计分析
FlowerCollector.onResume(SpeechRecognitionActivity.this);
FlowerCollector.onPageStart(TAG);
super.onResume();
if (waveLineView != null) {
waveLineView.onResume();
}
}
@Override
protected void onPause() {
// 开放统计 移动数据统计分析
FlowerCollector.onResume(SpeechRecognitionActivity.this);
FlowerCollector.onPageStart(TAG);
super.onPause();
if (waveLineView != null) {
waveLineView.onPause();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (waveLineView != null) {
waveLineView.release();
}
if (null != mIat) {
// 退出时释放连接
mIat.cancel();
mIat.destroy();
}
}
}
|
package arenaworker.abilities;
import arenaworker.Player;
public class Invisibility extends Ability {
boolean isInvisible = false;
long duration = 1500L;
long start;
public Invisibility(Player player, int abilityNum) {
super(player, abilityNum);
cooldown = 5000L;
}
@Override
public void Fire() {
super.Fire();
player.GoInvis(duration);
}
}
|
import java.util.*;;
public class FindallAnagraminstring {
public static void main(String[] args) {
String s="cbaebabacd";
String p="abc";
System.out.println(findAnagrams(s,p).toString());
}
public static List<Integer> findAnagrams(String s, String p) {
if (p.length() > s.length()) {
return new ArrayList<>();
}
ArrayList<Integer>ans=new ArrayList<>();
int s_len=s.length();
int p_len=p.length();
HashMap<Character,Integer>map=new HashMap<>();
HashMap<Character,Integer>s_map=new HashMap<>();
for(int i=0;i<p_len;i++){
map.put(p.charAt(i), (map.get(p.charAt(i)) != null) ? map.get(p.charAt(i)) + 1 : 1);
s_map.put(s.charAt(i), (s_map.get(s.charAt(i)) != null) ? s_map.get(s.charAt(i)) + 1 : 1);
}
for(int i=0;i<s_len-p_len;i++) {
if(map.equals(s_map)){
ans.add(i);
}
if(s_map.get(s.charAt(i)) !=null&&s_map.get(s.charAt(i))==1){
s_map.remove(s.charAt(i));
}else{
s_map.put( s.charAt(i),s_map.get(s.charAt(i))-1);
}
if(s_map.containsKey(s.charAt(i+p_len))){
s_map.put( s.charAt(i+p_len),s_map.get(s.charAt(i+p_len))+1);
}else{
s_map.put(s.charAt(i+p_len),1);
}
}
if(map.equals(s_map)){
ans.add(s_len-p_len);
}
return ans;
}
}
|
/*******************************************************************************
* Copyright (c) 2012, All Rights Reserved.
*
* Generation Challenge Programme (GCP)
*
*
* This software is licensed for use under the terms of the GNU General Public
* License (http://bit.ly/8Ztv8M) and the provisions of Part F of the Generation
* Challenge Programme Amended Consortium Agreement (http://bit.ly/KQX1nL)
*
*******************************************************************************/
package org.generationcp.browser.germplasm.containers;
import java.io.Serializable;
import java.util.ArrayList;
import org.generationcp.browser.germplasm.TraitQueries;
import org.generationcp.commons.exceptions.InternationalizableException;
import org.generationcp.middleware.pojos.Scale;
import org.generationcp.middleware.pojos.ScaleDiscrete;
import org.generationcp.middleware.pojos.Trait;
import org.generationcp.middleware.pojos.TraitMethod;
import com.vaadin.data.Container;
import com.vaadin.data.Item;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.ui.CheckBox;
public class TraitDataIndexContainer implements Serializable {
private static final long serialVersionUID = 1L;
public static final Object ISO3166_PROPERTY_SHORT = "short";
public static final Object ISO3166_PROPERTY_NAME = "name";
// Trait Object
private static final Object TRAIT_ID = "traitID";
@SuppressWarnings("unused")
private static final Object TRAIT_ABBR = "trabbr";
private static final Object TRAIT_NAME = "traitName";
private static final Object TRAIT_DESCRIPTION = "traitDesc";
// Scale Object
private static final Object SCALE_ID = "scaleID";
private static final Object SCALE_NAME = "scaleName";
private static final Object SCALE_TYPE = "scaleType";
// Method Object
private static final Object METHOD_ID = "methodID";
private static final Object METHOD_NAME = "methodName";
private static final Object METHOD_DESCRIPTION = "methodDescription";
// ScaleDiscrete Value
private static final Object SCALE_VALUE = "scaleValue";
private static final Object SCALE_DISCRETE_VALUE = "scaleDiscreteValue";
private static final Object SCALE_SELECTED = "select";
private static final Object SCALE_VALUE_DESCRIPTION = "Value";
// Criteria Value
private static final Object CRITERIA_VALUES = "criteriaValue";
private TraitQueries queryTrait;
// Results GIDS
private static final Object GID = "gid";
public TraitDataIndexContainer() {
queryTrait = new TraitQueries();
}
public IndexedContainer getAllTrait() throws InternationalizableException {
IndexedContainer container = new IndexedContainer();
// Create the container properties
container.addContainerProperty(TRAIT_ID, Integer.class, "");
container.addContainerProperty(TRAIT_NAME, String.class, "");
container.addContainerProperty(TRAIT_DESCRIPTION, String.class, "");
ArrayList<Trait> query = queryTrait.getTrait();
for (Trait t : query) {
addTraitData(container, t.getTraitId(), t.getAbbreviation(), t.getName(), t.getDescripton());
}
return container;
}
private static void addTraitData(Container container, int traitID, String trabbr, String traitName, String traitDesc) {
Object itemId = container.addItem();
Item item = container.getItem(itemId);
item.getItemProperty(TRAIT_ID).setValue(traitID);
item.getItemProperty(TRAIT_NAME).setValue(traitName);
item.getItemProperty(TRAIT_DESCRIPTION).setValue(traitDesc);
}
public IndexedContainer getScaleByTraitID(int traitID) {
IndexedContainer container = new IndexedContainer();
// Create the container properties
container.addContainerProperty(SCALE_ID, Integer.class, "");
container.addContainerProperty(SCALE_NAME, String.class, "");
container.addContainerProperty(SCALE_TYPE, String.class, "");
ArrayList<Scale> query = queryTrait.getScale(traitID);
for (Scale s : query) {
// addTraitData(container,t.getId(),t.getName(),t.getDescripton());
String type = "discrete";
if (s.getType().equals("C")) {
type = "continuous";
}
addScaleData(container, s.getId(), s.getName(), type);
}
return container;
}
private static void addScaleData(Container container, int scaleID, String scaleName, String scaleType) {
Object itemId = container.addItem();
Item item = container.getItem(itemId);
item.getItemProperty(SCALE_ID).setValue(scaleID);
item.getItemProperty(SCALE_NAME).setValue(scaleName);
item.getItemProperty(SCALE_TYPE).setValue(scaleType);
}
public IndexedContainer getMethodTraitID(int traitID) {
IndexedContainer container = new IndexedContainer();
// Create the container properties
container.addContainerProperty(METHOD_ID, Integer.class, "");
container.addContainerProperty(METHOD_NAME, String.class, "");
container.addContainerProperty(METHOD_DESCRIPTION, String.class, "");
ArrayList<TraitMethod> query = queryTrait.getTraitMethod(traitID);
for (TraitMethod m : query) {
// addTraitData(container,t.getId(),t.getName(),t.getDescripton());
addMethodData(container, m.getId(), m.getName(), m.getDescription());
}
return container;
}
private static void addMethodData(Container container, int methodID, String methodName, String methodDescription) {
Object itemId = container.addItem();
Item item = container.getItem(itemId);
item.getItemProperty(METHOD_ID).setValue(methodID);
item.getItemProperty(METHOD_NAME).setValue(methodName);
item.getItemProperty(METHOD_DESCRIPTION).setValue(methodDescription);
}
public IndexedContainer getValueByScaleID(int scaleID) throws InternationalizableException {
IndexedContainer container = new IndexedContainer();
// Create the container properties
container.addContainerProperty(SCALE_SELECTED, CheckBox.class, "");
container.addContainerProperty(SCALE_VALUE_DESCRIPTION, String.class, "");
container.addContainerProperty(SCALE_VALUE, String.class, "");
final ArrayList<ScaleDiscrete> query = queryTrait.getScaleDiscreteValue(scaleID);
for (ScaleDiscrete v : query) {
addScaleValueData(container, v.getValueDescription(), v.getId().getValue());
}
return container;
}
private static void addScaleValueData(Container container, String scaleDescription, String scaleValue) {
Object itemId = container.addItem();
Item item = container.getItem(itemId);
boolean activ = false;
item.getItemProperty(SCALE_SELECTED).setValue(new CheckBox(null, activ));
item.getItemProperty(SCALE_VALUE_DESCRIPTION).setValue(scaleDescription);
item.getItemProperty(SCALE_VALUE).setValue(scaleValue);
}
public IndexedContainer addSearchCriteria() {
IndexedContainer container = new IndexedContainer();
// Create the container properties
container.addContainerProperty(TRAIT_ID, Integer.class, "");
container.addContainerProperty(SCALE_ID, Integer.class, "");
container.addContainerProperty(METHOD_ID, Integer.class, "");
container.addContainerProperty(TRAIT_NAME, String.class, "");
container.addContainerProperty(SCALE_NAME, String.class, "");
container.addContainerProperty(METHOD_NAME, String.class, "");
container.addContainerProperty(CRITERIA_VALUES, String.class, "");
container.addContainerProperty(SCALE_TYPE, String.class, "");
container.addContainerProperty(SCALE_DISCRETE_VALUE, String.class, "");
return container;
}
public IndexedContainer addGidsResult(ArrayList<Integer> gids) {
IndexedContainer container = new IndexedContainer();
// Create the container properties
container.addContainerProperty(GID, Integer.class, "");
for (Integer gid : gids) {
// addTraitData(container,t.getId(),t.getName(),t.getDescripton());
addGids(container, gid);
}
return container;
}
private static void addGids(Container container, Integer gid) {
Object itemId = container.addItem();
Item item = container.getItem(itemId);
item.getItemProperty(GID).setValue(gid);
}
}
|
/** ****************************************************************************
* Copyright (c) The Spray Project.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spray Dev Team - initial API and implementation
**************************************************************************** */
package org.eclipselabs.spray.xtext.ui.quickfix;
import java.util.List;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.resource.IEObjectDescription;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceDescriptions;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.impl.ResourceDescriptionsProvider;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.eclipse.xtext.validation.Issue;
import org.eclipse.xtext.xbase.lib.IteratorExtensions;
import org.eclipselabs.spray.shapes.CommonLayout;
import org.eclipselabs.spray.shapes.ConnectionDefinition;
import org.eclipselabs.spray.shapes.Rectangle;
import org.eclipselabs.spray.shapes.RectangleEllipseLayout;
import org.eclipselabs.spray.shapes.ShapeContainer;
import org.eclipselabs.spray.shapes.ShapeDefinition;
import org.eclipselabs.spray.shapes.ShapeLayout;
import org.eclipselabs.spray.shapes.ShapesFactory;
import org.eclipselabs.spray.shapes.ShapesPackage;
import org.eclipselabs.spray.shapes.ui.quickfix.LinkingQuickfixModificationJob;
import org.eclipselabs.spray.xtext.scoping.AppInjectedAccess;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
public abstract class AbstractShapeDSLModificationJob extends IUnitOfWork.Void<XtextResource> {
public enum ModificationJobType implements LinkingQuickfixModificationJob {
SHAPE,
CONNECTION;
public AbstractShapeDSLModificationJob create(final IXtextDocument sprayXtextDocument, final Issue issue) {
AbstractShapeDSLModificationJob job = null;
if (this == ModificationJobType.SHAPE) {
job = new ShapeDefinitionModificationJob(sprayXtextDocument, issue);
} else if (this == ModificationJobType.CONNECTION) {
job = new ConnectionDefinitionModificationJob(sprayXtextDocument, issue);
}
return job;
}
/*
* (non-Javadoc)
* @see org.eclipselabs.spray.xtext.ui.quickfix.QuickfixTargetDSLURIProvider#getDSLURI(org.eclipse.xtext.resource.IResourceDescriptions, org.eclipse.emf.common.util.URI)
*/
@Override
public URI getDSLURI(IResourceDescriptions dscriptions, final URI uriToProblem) {
if (dscriptions == null) {
ResourceDescriptionsProvider serviceProvider = AppInjectedAccess.getit();
dscriptions = serviceProvider.createResourceDescriptions();
}
final String spraySegment = uriToProblem.trimFragment().lastSegment();
final String lastSegment = spraySegment.substring(0, spraySegment.length() - ".spray".length()) + ".shape";
final String uriToSprayFile = uriToProblem.trimFragment().trimSegments(1).appendSegment(lastSegment).toString();
List<IResourceDescription> filteredDescs = IteratorExtensions.toList(Iterables.filter(dscriptions.getAllResourceDescriptions(), new Predicate<IResourceDescription>() {
public boolean apply(IResourceDescription desc) {
return desc.getURI().trimFragment().toString().equals(uriToSprayFile);
}
}).iterator());
URI uri = null;
if (filteredDescs.size() > 0) {
uri = filteredDescs.get(0).getURI();
List<IEObjectDescription> containers = IteratorExtensions.toList(filteredDescs.get(0).getExportedObjectsByType(ShapesPackage.Literals.SHAPE_CONTAINER_ELEMENT).iterator());
if (containers.size() > 0) {
uri = containers.get(0).getEObjectURI();
} else {
// no quick fix, when there is a [spray-filename].shape but with empty content
uri = null;
}
} else {
// no quick fix, when there is no [spray-filename].shape resource
uri = null;
}
return uri;
}
}
private IXtextDocument sprayXtextDocument;
private Issue issue;
protected EObject newElement;
protected AbstractShapeDSLModificationJob(final IXtextDocument sprayXtextDocument, final Issue issue) {
AbstractShapeDSLModificationJob.this.sprayXtextDocument = sprayXtextDocument;
AbstractShapeDSLModificationJob.this.issue = issue;
}
@Override
public void process(XtextResource shapeResource) throws Exception {
ShapeContainer shapeContainer = null;
for (EObject eo : shapeResource.getContents()) {
if (eo instanceof ShapeContainer) {
shapeContainer = (ShapeContainer) eo;
break;
}
}
if (shapeContainer != null) {
String elementName = sprayXtextDocument.get(issue.getOffset(), issue.getLength());
newElement = createNewElement(shapeContainer, elementName);
}
}
protected abstract EObject createNewElement(ShapeContainer shapeContainer, String elementName);
private static class ShapeDefinitionModificationJob extends AbstractShapeDSLModificationJob {
ShapeDefinitionModificationJob(IXtextDocument sprayXtextDocument, Issue issue) {
super(sprayXtextDocument, issue);
}
@Override
protected EObject createNewElement(ShapeContainer shapeContainer, String shapeName) {
ShapeDefinition shapeDefinition = ShapesFactory.eINSTANCE.createShapeDefinition();
shapeDefinition.setName(shapeName);
Rectangle rectangle = ShapesFactory.eINSTANCE.createRectangle();
RectangleEllipseLayout rectangleEllipseLayout = ShapesFactory.eINSTANCE.createRectangleEllipseLayout();
CommonLayout commonLayout = ShapesFactory.eINSTANCE.createCommonLayout();
commonLayout.setXcor(0);
commonLayout.setYcor(0);
commonLayout.setWidth(100);
commonLayout.setHeigth(100);
rectangleEllipseLayout.setCommon(commonLayout);
rectangle.setLayout(rectangleEllipseLayout);
shapeDefinition.getShape().add(rectangle);
ShapeLayout shapeLayout = ShapesFactory.eINSTANCE.createShapeLayout();
shapeDefinition.setShapeLayout(shapeLayout);
shapeContainer.getShapeContainerElement().add(shapeDefinition);
return shapeDefinition;
}
}
private static class ConnectionDefinitionModificationJob extends AbstractShapeDSLModificationJob {
ConnectionDefinitionModificationJob(IXtextDocument sprayXtextDocument, Issue issue) {
super(sprayXtextDocument, issue);
}
@Override
protected EObject createNewElement(ShapeContainer shapeContainer, String shapeName) {
ConnectionDefinition connectionDefinition = ShapesFactory.eINSTANCE.createConnectionDefinition();
connectionDefinition.setName(shapeName);
shapeContainer.getShapeContainerElement().add(connectionDefinition);
return connectionDefinition;
}
}
public EObject getNewElement() {
return newElement;
}
}
|
package ru.mail.controller.filters;
import javax.servlet.*;
import java.io.IOException;
public class RequestEncodeFilter implements Filter {
private static final String ENCODING_TYPE="UTF-8";
private static final String CONTENT_TYPE="text/html; charset=UTF-8";
public RequestEncodeFilter() {
System.out.println("Request response encoder filter object has been created");
}
@Override
public void init(FilterConfig filterConfig) {
//Default
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("RequestEncode filter is working");
//setting request character encoding
request.setCharacterEncoding(ENCODING_TYPE);
chain.doFilter(request, response);
//setting response content type
response.setContentType(CONTENT_TYPE);
}
public void destroy() {
//Default
}
}
|
package clases;
public class Matematicas {
//ESTA CLASE LA VAMOS A UTILIZAR
//NO VA A ARRANCAR, SERA UNA HERRAMIENTA PARA
//OTRAS CLASES
//NO LLEVA METODO main()
//NOS CREAMOS UN METODO PARA SUMAR NUMEROS
//QUE RECIBIRA DOS NUMEROS Y DEVOLVERA LA SUMA
public int sumarNumeros(int num1, int num2) {
//ACCIONES
int suma = num1 + num2;
return suma;
}
public int getDoble(int num) {
return num * 2;
}
public double getPotencia(int num, int potencia) {
double resultado = Math.pow(num, potencia);
return resultado;
}
//EL MENU NO DEVUELVE NADA, SOLAMENTE
//MUESTRA OPCIONES void
public void menuMatematicas() {
System.out.println("1.- Sumar Números");
System.out.println("2.- Doble de número");
System.out.println("3.- Potencia de número");
System.out.println("Seleccione una opción: ");
}
}
|
package com.jadn.cc.core;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.os.IBinder;
import android.util.Log;
import com.jadn.cc.services.ContentService;
import com.jadn.cc.services.ContentService.LocalBinder;
import com.jadn.cc.trace.TraceUtil;
public class CarCastApplication extends Application {
public final static String[] releaseData = new String[]{
"01-JUL-2014", "Pause when the GPS (or another app) starts speaking.\n\nBluetooth play/pause next/prev working.",
"18-MAY-2014", "(Another crack at) Fix enabling of Start Download button, try to prevent 2 carcast downloads at once",
"04-MAY-2014", "Keep download results after download is completed... for analysis...",
"23-APR-2014", "If KitKat 4.4, display better data location error message. Fix podcast deletions again...",
"30-DEC-2013", "Fix the 'Erase History' function on the Subscription edit popup - it wasn't reliable.",
"15-NOV-2013", "Use the Apple iTunes database for finding podcasts. Thanks Apple! They maintain a good public database.",
"08-NOV-2013", "Fix 'Export OPML' to work on newer phones. Lets you move/email subscriptions from phone to phone.",
"04-NOV-2013", "REBUILD. Subscriptions can have a high priority. Thanks to Stephen Blott",
"02-NOV-2013", "Subscriptions can have a high priority. Thanks to Stephen Blott",
"29-OCT-2013", "CarCast now has Intents for Play/Pause - for use with things like Tasker. Thanks to Stephen Blott",
"20-OCT-2013", "Add setting to remove Audio Recorder (bottom of settings screen)",
"23-SEP-2013", "Get rid of Beta status for Data location change and emailing recordings.",
"21-JUL-2013", "BETA2 - allow change of data directory. (Changing it will drop all subscriptions/podcasts) Please let me know what you think.",
"20-MAY-2013", "Stop collecting anonymous data... I'm not using it and it slows my server down.",
"08-APR-2013", "New Setting: Keep Display Awake\nFix Help/FAQ page\n (Thanks Eddy Petrișor)\nBETA: Pay to Play Fast Support\n (Thanks Kerry Sainsbury!)",
"23-Feb-2013", "Fix OIML Import bug. Thanks to Kerry Sainsbury!",
"01-Feb-2013", "Fix for poorly formed subscriptions/feeds with spaces in enclosure URLs",
"26-Jan-2013", "BETA3 feature Audio Note mailer\n\nConfigure receiver email address\nmenu item to send auto notes on demand",
"24-Jan-2013", "BETA2 feature - more working\n\nAutomatically forward Audio Notes to your email when you connect to WiFi.",
"21-Jan-2013", "BETA feature\n\nAutomatically forward Audio Notes to your email when you connect to WiFi.",
"17-Jan-2013", "Two new preferences\n\nAuto delete \"Listened To\" Podcasts (during download)\n\nDon't warn when downloading on dataplan (aka unlimited dataplan)",
"22-Dec-2012", "You can now Export and Import your subscriptions using OPML (tested via email)",
"08-Aug-2012j", "OnSale",
"07-Aug-2012", "Add 'Export OPML' to Subscriptions screen (used to transfer subscriptions from phone to phone.)\n\nDont yet have OPML Import... coming soon.",
"30-Jul-2012", "Enable ipod/iphone headphones button to pause playback",
"18-Jul-2012", "Bug fixes for Kindle Fire",
"23-Jun-2012", "Added simple ability to reorder podcasts",
"09-Jun-2012", "Better debugging: When emailing download details 1000 lines of log info are sent.",
"03-Jun-2012", "New setting - Orientation Preference",
"02-Jun-2012", "Podcast database nearly 8000 entries\nBluetooth headset forward/next working (thx Ed)\nHandle subscription typos better",
"30-Mar-2012", "Don't duplicate every ESPN feed... despite it being their issue....",
"10-Mar-2012", "Add new Setting -> if no downloads then don't show notification.",
"25-Sep-2011", "For some headphone pause buttons and bluetooth pause buttons, CarCast now pauses.",
"11-Sep-2011", "Fix: A change to keep the Archos tablet from sleeping during downloads.\n\nThanks Stephen Blott!",
"22-Aug-2011", "Fix: Dont leave notification icon up after end of podcast(s) reached.",
"17-Aug-2011", "Fix: Click on podcast link from a web browser, will show/add subscription to CarCast.",
"14-Aug-2011a", "Hopefully a fix for Foreground/Background issues.\n\nThanks to Baruch Even!!!\nhttp://baruch.ev-en.org/",
"11-Aug-2011",
"Fix for www.flatironschurch.com podcast for Darrin Graham and friends",
"29-July-2011",
"Whew! I've been crazy busy with three other projects. Finally quieting down.\n\nAdded confirmations to menu items Delete/Reset on Subscriptions screen\n\nEnjoy, Bob",
"23-June-2011",
"New subscriptions arent Unlimited by default. If you suddenly start downloading hundreds of podcasts, check each subscriptions setting.",
"29-May-2011",
"Sorry the UI looks klunky (Subscription screen), but you can now specify max and order per subscription. This make audiobook listening possible. Yippie!! Thanks to Pat for laying the groundwork.",
"20-May-2011",
"On podcast screen, long press offers to 'delete all before'",
"10-May-2011",
"Restore 'press to play' from Podcasts screen",
"08-May-2011",
"Podcast list now has checkboxes for deleting",
"12-Apr-2011",
"In podcast list, show listened to podcasts with grey background",
"07-Apr-2011",
"Fixed loading of German (ISO-8859-1 encoded) podcasts",
"02-Apr-2011",
"Merged in Patrick's fixes for pausing on headset unplugged. Yet another fix to podcast character encodings.\n\nCarCast is opensource!",
"01-Apr-2011",
"Another fix to podcast character encodings",
"30-Mar-2011",
"Fix podcasts encodeded in Windows-1252 (I hate non UTF8 character encoding.)",
"27-Mar-2011",
"Fixed Spanish/Latin Subscriptions. Made subscription 'Test' show working message.",
"28-Feb-2011",
"Added code to keep wifi on, if it is on when downloading starts. (Round II)",
"26-Feb-2011",
"Try and make landscape mode more usable.",
"19-Feb-2011",
"Updated icon, Thanks to Peter Herrmann. More space between buttons on player.",
"28-Jan-2011",
"Fix layout for: Audio Recorder, Subscription Add",
"15-Jan-2011",
"Added menu item to podcasts screen - delete listened to.",
"27-Dec-2010",
"Head phone unplug pauses player, wifi alarm fix, feedback goes to group.",
"17-Dec-2010",
"Podcast search and stat collection are back on.",
"24-Nov-2010",
"Turned off Podcast search - I'm moving and the server will be in a box.\n Hopefully all back on by 15-DEC-2011",
"15-Nov-2010",
"enable/disable on subscriptions, warning when downloading without wifi, new icons on menus. ALL BY -> steffanfay@gmail.com <- send him thanks!!!",
"27-Oct-2010",
"Added automatic nightly download feature (beta).",
"18-Oct-2010",
"Move version info into settings title.",
"13-Oct-2010",
"Move Ads to top (based on user feedback!)\n\nNever Ads in Car Cast Pro.",
"10-Oct-2010",
"Experiement with Ads (I want to continue to improve Car Cast, Ads can help make that possible. Note: No Ads in Car Cast Pro.)",
"9-Oct-2010",
"Minor adjustments to main screen layout.",
"6-Oct-2010",
"Fix feedback email (headsmack), fix Podcast and Subscription screens so delete doesnt loose place. Also delete last works right. Thanks Yoav Weiss!",
"1-Oct-2010",
"Added confirm to 'Delete All' menu item on Podcasts screen for Jim Fulner.",
"21-Sep-2010",
"Added 'details' button to 'Download Podcasts' screen.",
"10-Sep-2010",
"Added a setting for detailed download information (with email option for problem troubleshooting)",
"2-Sep-2010",
"Re-enable screen rotation of player (for people with car docks.)",
"23-Aug-2010",
"Patrick Forhan: Sorted subscription list, No rotation in player mode",
"7-Aug-2010",
"Updated text size on podcast search page. Added privacy settings. (Also updated podcast search database!) NOTE: includes Patrick's internal changes to podcasts.txt",
"27-Jul-2010",
"Testing Patricks changes",
"18-Jul-2010",
"Bug Fixes: delete empty files, tweak download progress bar",
"24-Jun-2010",
"Make Audio Recorder more obvious.\n\nThanks Patrick Forhan!!\n\n'Car Cast Pro' will get this update in about a week.",
"22-Jun-2010b",
"Fix allowing phone display to turn off (Thanks to Ofer Webman!!), increase font on download screen.",
"22-Jun-2010",
"Fix allowing phone display to turn off.\n\nThanks to Ofer Webman!!",
"10-Jun-2010",
"Fix font sizes on rotated screen.",
"12-Jan",
"Fix 'podcast' list font sizes on Droid (for Clyde.)",
"2-Jan",
getAppTitle() + " is now open source.\n\nsee http://jadn.com/cc/",
"27-Dec",
"Change Droid layout to use g1 layout (for larger buttons.)",
"17-Dec",
"Handle feeds with bad lengths, for Matt L",
"11-Dec",
"Allow Landscape mode since new layout is usable in landscape.",
"09-Dec",
"Fix layout on Droid, thanks Pete Smith.\nAdd setting so you can disable 'Auto Play Next' Podcast for Jim H.\nChanged layout of main screen to be relative for HTC Tattoo users.",
"08-Dec",
"Add setting so you can disable 'Auto Play Next' Podcast for Jim H. Changed layout of main screen to be relative for HTC Tattoo users.",
"21-Nov",
"On Podcasts, touching a podcast will cause it to play. Thanks to Tom Howes.",
"09-Nov",
"Fix botch to yesterday's max 'ulimited' downloads fix.",
"08-Nov",
"Shackman found setting max downloads to unlimited was broken. Fixed. Thanks.",
"04-Nov",
"Change to work with more phones (1.5 compatible, not 1.6)",
"23-Oct",
"Thanks for using Car Cast. Please support Car Cast by providing feedback. (Use Menu/Email Feedback)\n\n- Fix to ignore bad search results.\n- Extra debug code for an unsual download problem.\n",
"18-Oct-2009",//
"22-Oct",
"added extra debugging code for playback problems",
"18-Oct-2009",//
"18-Oct",
"added Email Feedback button",
"18-Oct-2009",//
"15-Oct",
"bug fix in showing podcasts.",
"15-Oct-2009",//
"19-Sept",
"bug fixes in searching.",
"19-Sep-2009",//
"18-Sept",
"bug fixes in title processing. Added remote stacktrace reporting.",
"18-Sep-2009",//
"13-Sept",
"Simple Video Support (seems odd for commuting, but people have asked.) "
+ "If a video (.mp4) is in the feed, it will be saved to the camera directory for playback with camera application.",
"13-Sep-2009", //
"rc5", "Fix crash when choosing 'Search Again' on search results - sheesh.", "12-Sep-2009", //
"rc4", "Clicking on podcast title switches to Audio Recorder", "07-Sep-2009", //
"rc3", "Trippled size of podcast database for searches", "05-Sep-2009", //
"rc2", "Treat .m4a like .mp3\nThanks to Daniel Browne!!", "03-Sep-2009", //
"beta rc1", "fix subscription longpress", "01-Sep-2009", //
"adc2", "package rename", "31-Aug-2009", //
"beta 08.31", "added splash checkbox to settings", "31-Aug-2009", //
"beta 08.30", "Added subscription search", "30-Aug-2009", //
"beta 08.28b", "Email Podcast for first podcast fixed", "28-Aug-2009", //
"beta 08.28", "SplashScreen added/fix no podcasts bug", "28-Aug-2009", //
"beta 08.26", "Changed download default to 2 podcasts per subscription (instead of 5)", "25-Aug-2009", //
"beta 08.25", "on first run, use sample subscriptions", "25-Aug-2009", //
"beta 08.24", "focus on bug fixes", "24-Aug-2009", //
"oswald5", "ready for market?", "22-Aug-2009", //
"nanobots2", "added delete page", "21-Aug-2009", //
"monkey2", "add podcast list", "18-Aug-2009", //
"llama, llama Red Pajama", "Bow to Ed", "17-Aug-2009", //
"klondike", "remove extranous features", "14-Aug-2009", //
"Jumping Jackrabbit", "rework package structure", "11-Aug-2009", //
"Himalayas", "Uses actual service class for handing media content.", "06-Aug-2009", //
"ice cream 4", "pings home every 15. Immediately on wifi connect.", //
"29-July-2009", //
"hummus", "After phone call resume.", "26-July-2009", //
"grapes", "Fix deletion and remembering location", "09-July-2009", "french fries", "order podcasts by date", "22-Jun-2009", //
"easter egg", "add/delete sites", "21-Jun-2009"};
private Intent serviceIntent;
private ContentService contentService;
private ContentServiceListener contentServiceListener;
@Override
public void onCreate() {
super.onCreate();
serviceIntent = new Intent(this, ContentService.class);
//WifiConnectedReceiver.registerForWifiBroadcasts(getApplicationContext());
}
private ServiceConnection contentServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iservice) {
Log.i("CarCast", "onServiceConnected; CN is " + name + "; binder is " + iservice);
if (name.getClassName().equals(ContentService.class.getName())) {
contentService = ((LocalBinder) iservice).getService();
contentService.setApplicationContext(getApplicationContext());
contentServiceListener.onContentServiceChanged(contentService);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.i("CarCast", "onServiceDisconnected; CN is " + name);
if (name.getClassName().equals(ContentService.class.getName())) {
contentService = null;
contentServiceListener.onContentServiceChanged(contentService);
}
}
};
public void setContentServiceListener(ContentServiceListener listener) {
this.contentServiceListener = listener;
// make sure the service is running (may have been shut down by stopping
// CarCast previously). Note that after the service has been stopped, we
// need to bind to it again.
// BIND_AUTO_CREATE forces the service to start running and continue
// running until unbound.
bindService(serviceIntent, contentServiceConnection, Context.BIND_AUTO_CREATE);
// notify immediately if we have a contentService:
listener.onContentServiceChanged(contentService);
}
public static String getVersion() {
return releaseData[0];
}
public static String getVersionName(Context context, Class<?> cls) {
try {
ComponentName comp = new ComponentName(context, cls);
PackageInfo pinfo = context.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
return pinfo.versionName;
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return null;
}
}
public static void report(Throwable e1) {
TraceUtil.report(e1);
}
public static void esay(Throwable re) {
TraceUtil.report(re);
}
public static String getAppTitle() {
return "Car Cast";
}
public void stopContentService() {
Log.i("CarCast", "requesting stop; contentService is " + contentService);
stopService(serviceIntent);
}
public void directorySettingsChanged() {
contentService.directorySettingsChanged();
}
}
|
package Server;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CompaniesTable extends DataTable implements ResultFromTable {
public CompaniesTable(Statement stmt, DatabaseHandler mdbc) {
super(stmt, mdbc);
}
public ResultSet getResultFromTable(String table) {
ResultSet rs = null;
try {
rs = this.stmt.executeQuery("SELECT * FROM " + table);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public void addCompany(String name, String form, String district, String region, String employee_number, String owner, String foundation_year, String address, String e_mail, String site, int userId) {
String insert="INSERT INTO " + Const.COMPANY_TABLE + "(" + Const.COMPANY_NAME + "," +
Const.COMPANY_FORM + "," + Const.COMPANY_DISTRICT + "," + Const.COMPANY_REGION + "," +
Const.COMPANY_EMPLOYEE_NUMBER + "," + Const.COMPANY_OWNER + "," + Const.COMPANY_FOUNDATION_YEAR + "," +
Const.COMPANY_ADDRESS + "," + Const.COMPANY_MAIL + "," + Const.COMPANY_SITE + "," + Const.COMPANY_USER_ID + ")" +
" VALUES (" + this.quotate(name) + "," + this.quotate(form) + "," + this.quotate(district) + "," + this.quotate(region) + "," + this.quotate(employee_number) + "," + this.quotate(owner) + "," + this.quotate(foundation_year) + "," + this.quotate(address) + "," + this.quotate(e_mail) + "," + this.quotate(site) + "," + userId + ")";
try {
this.stmt.executeUpdate(insert);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void delCompany(String name)
{
int id=this.getCompanyId(name);
try {
stmt.executeUpdate("DELETE FROM " + Const.DEVIATION_TABLE + " WHERE (" + Const.DEVIATION_COMPANY_ID + " LIKE '" + id + "');");
stmt.executeUpdate("DELETE FROM " + Const.RISK_TABLE + " WHERE (" + Const.RISK_COMPANY_ID + " LIKE '" + id + "');");
stmt.executeUpdate("DELETE FROM " + Const.TRANSACTION_TABLE + " WHERE (" + Const.TRANSACTION_COMPANY_ID + " LIKE '" + id + "');");
stmt.executeUpdate("DELETE FROM " + Const.COMPANY_TABLE + " WHERE (" + Const.COMPANY_NAME + "='" + name + "');");
} catch (SQLException e) {
e.printStackTrace();
}
}
public int getCompanyId(String name) {
ResultSet resultSet;
int id = 0;
try {
resultSet = stmt.executeQuery("SELECT " + Const.COMPANY_ID + " FROM " + Const.COMPANY_TABLE + " WHERE " + Const.COMPANY_NAME + "='" + name + "';");
while (resultSet.next())
id = resultSet.getInt(Const.COMPANY_ID);
} catch (SQLException e) {
e.printStackTrace();
}return id;
}
public String getCompanyName(int id) {
ResultSet resultSet;
String companyName = null;
try {
resultSet = stmt.executeQuery("SELECT " + Const.COMPANY_NAME + " FROM " + Const.COMPANY_TABLE + " WHERE " + Const.COMPANY_ID + "='" + id + "';");
while (resultSet.next())
companyName=resultSet.getString(Const.COMPANY_NAME);
} catch (SQLException e) {
e.printStackTrace();
}
return companyName;
}
}
|
package com.example.connectly.jobprovider;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
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.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.example.connectly.Login;
import com.example.connectly.R;
import com.example.connectly.SharedPrefManager;
import com.example.connectly.ViewPagerAdapter;
import com.example.connectly.seeker.Seeker;
import com.example.connectly.seeker.SeekerAdapter;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import java.util.ArrayList;
import java.util.List;
public class ProviderProfile extends AppCompatActivity {
private Toolbar toolbar;
public static String userEmail;
public static SQLiteDatabase seekersDatabase,jobsDatabase;
private boolean editable = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.company_profile);
toolbar = findViewById(R.id.myToolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Profile");
userEmail = getIntent().getStringExtra("userEmail");
seekersDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE,null);
seekersDatabase.execSQL("CREATE TABLE IF NOT EXISTS company (email VARCHAR,password VARCHAR,companyname VARCHAR,phone VARCHAR, address VARCHAR)");
jobsDatabase = this.openOrCreateDatabase("Jobs", MODE_PRIVATE, null);
jobsDatabase.execSQL("CREATE TABLE IF NOT EXISTS alljobs (providerEmail VARCHAR, providerName VARCHAR, jobTitle VARCHAR, jobDescription VARCHAR, jobRequirements VARCHAR, jobLocation VARCHAR ,seekerEmail VARCHAR)");
TabLayout tabLayout = findViewById(R.id.tabBar);
TabItem tabInfoC = findViewById(R.id.tabInfoCom);
TabItem tabEinfoC = findViewById(R.id.tabEditInfoCom);
final ViewPager companyViewPager = findViewById(R.id.viewPager);
ProviderPagerAdapter pagerAdapter = new ProviderPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
companyViewPager.setAdapter(pagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
companyViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}});
}
//Attache menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu2, menu);
return true;
}
//on Click on menu items:
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id=item.getItemId();
if (id == R.id.menu2_home){
Intent intent= new Intent(ProviderProfile.this, ProviderHome.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
return true;
} else if (id == R.id.Menu2_profile){
Intent intent= new Intent(ProviderProfile.this, ProviderProfile.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
return true;
} else if (id == R.id.menu2_logout){
Intent intent= new Intent(ProviderProfile.this, Login.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public static class ViewRequsteActivity extends AppCompatActivity {
private Toolbar toolbar;
public Button viewBtn;
public String userEmail;
private TextView txt_no_users;
ListView lst_seekers;
private List<Seeker> seekersList = new ArrayList<>();
private SeekerAdapter seekerAdapter;
private SeekerAdapter.SeekersListAdapterCallback seeker_callback = new SeekerAdapter.SeekersListAdapterCallback() {
@Override
public void onClickView(int indx) {
if(!TextUtils.isEmpty(seekersList.get(indx).CVPath)) {
Intent intent = new Intent(ViewRequsteActivity.this, CVActivity.class);
intent.putExtra("userEmail", userEmail);
intent.putExtra("CVFullPath", seekersList.get(indx).CVPath);
startActivity(intent);
}
else {
Toast.makeText(ViewRequsteActivity.this, "The seeker not upload cv", Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_request);
viewBtn = findViewById(R.id.viewId);
toolbar = findViewById(R.id.myToolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("View Requests");
txt_no_users = findViewById(R.id.txt_no_users);
txt_no_users.setVisibility(View.GONE);
lst_seekers = findViewById(R.id.lst_seekers);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new viewRequestsFragment(), "Requests");
userEmail = SharedPrefManager.getSharedPrefManager(ViewRequsteActivity.this).getEmail();
seekerAdapter = new SeekerAdapter(ViewRequsteActivity.this, seekersList, seeker_callback);
lst_seekers.setAdapter(seekerAdapter);
loadSeekers();
}
private void loadSeekers(){
seekersList.clear();
SQLiteDatabase JobsDatabase = this.openOrCreateDatabase("Jobs", MODE_PRIVATE, null);
SQLiteDatabase SeekersDatabase = this.openOrCreateDatabase("Users", MODE_PRIVATE, null);
JobsDatabase.execSQL("CREATE TABLE IF NOT EXISTS alljobs (providerEmail VARCHAR, providerName VARCHAR, jobTitle VARCHAR, jobDescription VARCHAR, jobRequirements VARCHAR, jobLocation VARCHAR ,seekerEmail VARCHAR)");
Cursor allJobsForJobsProvider = JobsDatabase.rawQuery("SELECT * FROM alljobs WHERE providerEmail='"+ userEmail +"'",null);
if(allJobsForJobsProvider.getCount() > 0){
allJobsForJobsProvider.moveToFirst();
while (!allJobsForJobsProvider.isAfterLast()){
String seekerEmail = allJobsForJobsProvider.getString(allJobsForJobsProvider.getColumnIndex("seekerEmail"));
// Toast.makeText(this, "seekerEmail : "+seekerEmail, Toast.LENGTH_SHORT).show();
if(seekerEmail != null && !seekerEmail.equals("") ){
Cursor seekerCursor = SeekersDatabase.rawQuery("SELECT * FROM seeker WHERE email='"+seekerEmail+"'",null);
String seekerName = "";
String cvPath = "";
if (seekerCursor.getCount() > 0){
seekerCursor.moveToFirst();
seekerName = seekerCursor.getString(seekerCursor.getColumnIndex("firstname")) +" "+seekerCursor.getString(seekerCursor.getColumnIndex("lastname"));
cvPath = seekerCursor.getString(seekerCursor.getColumnIndex("CVPath")) ;
}
String jobTitle = allJobsForJobsProvider.getString(allJobsForJobsProvider.getColumnIndex("jobTitle"));
Seeker seeker = new Seeker();
seeker.name = seekerName;
seeker.title = jobTitle;
seeker.CVPath = cvPath;
seekersList.add(seeker);
}
allJobsForJobsProvider.moveToNext();
}
}
seekerAdapter.notifyDataSetChanged();
if(seekersList.size() == 0){
txt_no_users.setVisibility(View.VISIBLE);
lst_seekers.setVisibility(View.GONE);
}else{
txt_no_users.setVisibility(View.GONE);
lst_seekers.setVisibility(View.VISIBLE);
}
}
public void ViewCV_onClick(View view) {
Intent moveToRequest= new Intent(ViewRequsteActivity.this, CVActivity.class);
moveToRequest.putExtra("userEmail", userEmail);
startActivity(moveToRequest);
}
//Attache menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu2, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id=item.getItemId();
if (id == R.id.menu2_home){
Intent intent= new Intent(ViewRequsteActivity.this, ProviderHome.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
return true;
} else if (id == R.id.Menu2_profile){
Intent intent= new Intent(ViewRequsteActivity.this, ProviderProfile.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
return true;
} else if (id == R.id.menu2_logout){
SharedPrefManager.getSharedPrefManager(ViewRequsteActivity.this).removeAllSharedPrefValue();
Intent intent= new Intent(ViewRequsteActivity.this,Login.class);
intent.putExtra("userEmail", userEmail);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
public static class viewRequestsFragment extends Fragment {
View view;
public viewRequestsFragment() {
}
@Nullable
@Override
public View onCreateView(@Nullable LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_view_requests, container, false);
return view;
}
}
}
|
package com.fpmislata.banco.presentacion;
import com.fpmislata.banco.negocio.dominio.EntidadBancaria;
import com.fpmislata.banco.negocio.servicios.EntidadBancariaService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class NewMain {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
EntidadBancariaService entidadBancariaService = context.getBean(EntidadBancariaService.class);
EntidadBancaria entidadBancaria = entidadBancariaService.get(1);
System.out.println(entidadBancaria.getNombre());
}
}
|
package wrapers;
import java.util.List;
import java.util.ArrayList;
public class TestaOutrosWrapers {
public static void main(String[] args) {
Integer idadeRef = Integer.valueOf(29); //autoboxing
System.out.println(idadeRef.intValue()); //unboxing
Double dRef = Double.valueOf(3.2);//autoboxing
System.out.println(dRef.doubleValue());//unboxing
Boolean bRef = Boolean.FALSE;
System.out.println(bRef.booleanValue());
Number refNumero = Float.valueOf(29.9f);
List<Number> numeros = new ArrayList<>();
}
}
|
/*
* Copyright (c) 2013 M-Way Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jenkinsci.plugins.relution_publisher.constants;
import hudson.util.ListBoxModel;
import hudson.util.ListBoxModel.Option;
/**
* Indicates the release status of a build artifact.
* <p/>
* The release status of an application defines who will be able to access the application. A
* version with status <code>Development<code> will be shown as a development version and is
* usually only available to developers. A version uploaded to <code>Review</code> is available
* to reviewers, while a version uploaded as <code>Release</code> is available to end users.
* <p/>
* By default applications are be uploaded to <code>Development</code> and must be manually
* moved to <code>Review</code> by a developer, to make this version available for review. The
* version is then manually moved to <code>Release</code> by a reviewer if the version has passed
* review and should replace the currently released version.
* <p/>
* Changing the release status for an application allows to skip parts of this manual process,
* i.e. if the application is not reviewed/tested by a human.
*/
public final class ReleaseStatus {
/**
* Versions produced by the build process should be uploaded to <code>Development</code>.
*/
public final static ReleaseStatus DEVELOPMENT = new ReleaseStatus("DEVELOPMENT", "Development");
/**
* Versions produces by the build process should be uploaded to <code>Review</code>
*/
public final static ReleaseStatus REVIEW = new ReleaseStatus("REVIEW", "Review");
/**
* Versions produced by the build process should be uploaded to <code>Release</code>
*/
public final static ReleaseStatus RELEASE = new ReleaseStatus("RELEASE", "Release");
/**
* The key for the release status.
*/
public final String key;
/**
* The display name for the release status.
*/
public final String name;
private Option option;
private ReleaseStatus(final String key, final String name) {
this.key = key;
this.name = name;
}
/**
* Converts the {@link ReleaseStatus} to a a drop down item for a {@link ListBoxModel}.
* @return An {@link Option}.
*/
public Option asOption() {
if (this.option == null) {
this.option = new Option(this.name, this.key);
}
return this.option;
}
/**
* Adds all available {@link ReleaseStatus} items to the specified list box as drop down items.
* @param list The {@link ListBoxModel} to which the items should be added.
*/
public static void fillListBox(final ListBoxModel list) {
list.add(0, DEVELOPMENT.asOption());
list.add(1, REVIEW.asOption());
list.add(2, RELEASE.asOption());
}
}
|
package com.cg.eis.service;
import com.cg.eis.bean.*;
interface I{
String employeeScheme(int salary);
}
public class Scheme extends Employee4 implements I{
public String employeeScheme(int salary) {
String result="";
if((salary>5000)&& (salary<20000)) {
result= "C";
}
if((salary>=20000)&&(salary<40000)) {
result= "B";
}
if(salary>40000) {
result= "A";
}
if(salary<5000) {
result ="you are not elgibile";
}
return result;
}
}
|
package com.tencent.mm.plugin.webview.ui.tools.game;
import com.tencent.mm.R;
import com.tencent.mm.plugin.webview.ui.tools.WebViewUI;
import com.tencent.mm.pluginsdk.ui.applet.g;
import com.tencent.mm.pluginsdk.ui.applet.q.a;
import com.tencent.mm.sdk.platformtools.x;
public class GameChattingRoomWebViewUI extends WebViewUI {
private String jumpUrl = "";
private int qfF = 4;
private int qfG = 5;
final a qfH = new 1(this);
final a qfI = new 2(this);
protected final boolean Du(String str) {
return true;
}
protected final void Ro(String str) {
x.i("MicroMsg.GameChattingRoomWebViewUI", "url = %s", new Object[]{str});
this.jumpUrl = str;
String stringExtra = getIntent().getStringExtra("action");
if (stringExtra != null) {
String string;
if (getIntent().getStringExtra("app_name") == null) {
string = getString(R.l.app_back);
} else {
string = getString(R.l.confirm_dialog_back_app, new Object[]{r1});
}
String string2 = getString(R.l.confirm_dialog_stay_in_weixin);
if (stringExtra.equals("action_create")) {
g.a(this.mController, getString(R.l.created_chatroom), string, string2, this.qfH, this.qfI);
} else if (stringExtra.equals("action_join")) {
g.a(this.mController, getString(R.l.joined_chatroom), string, string2, this.qfH, this.qfI);
}
}
}
}
|
package com.ibm.ive.tools.japt.reduction.xta;
import com.ibm.ive.tools.japt.JaptRepository;
import com.ibm.ive.tools.japt.reduction.ClassSet;
import com.ibm.ive.tools.japt.reduction.EntryPointLister;
import com.ibm.jikesbt.BT_Class;
import com.ibm.jikesbt.BT_Field;
import com.ibm.jikesbt.BT_HashedClassVector;
/**
* @author sfoley
*
*/
public class Field extends DataMember {
BT_Field field;
/**
* Constructor for Field.
* @param member
*/
public Field(Repository repository, BT_Field field) {
super(repository.getClazz(field.getDeclaringClass()));
this.field = field;
}
public Field(Repository repository, BT_Field field, BT_HashedClassVector propagatedObjects, ClassSet allPropagatedObjects) {
super(repository.getClazz(field.getDeclaringClass()), propagatedObjects, allPropagatedObjects);
this.field = field;
}
boolean isPrimitive() {
return field.getFieldType().isPrimitive();
}
boolean isConstantStringField() {
return field.isStatic() && field.getFieldType().equals(getRepository().properties.javaLangString) && field.attributes.getAttribute("ConstantValue") != null;
}
/**
* A static field may contain a constant string obtained from the constant pool when created,
* as opposed to having a null initial value.
*/
void initializePropagation() {
if(isConstantStringField()) {
addCreatedObject(getRepository().properties.javaLangString);
}
addConditionallyCreatedObjects(field);
}
/**
* @return whether the field can hold an object of the given type
*/
boolean holdsType(BT_Class type) {
return getRepository().isCompatibleType(field.getFieldType(), type);
}
/**
* The field is included as part of an API so we must assume it can be accessed
* with any compatible arguments.
*/
// void propagateFromUnknownSource() {
// super.propagateFromUnknownSource();
// BT_ClassVector unknowns = new BT_HashedClassVector();
// if(!field.type.isBasicTypeClass) {
// unknowns.addUnique(field.type);
// for(int i=0; i<unknowns.size(); i++) {
// BT_Class creation = unknowns.elementAt(i); //adding all subtypes of a field, when the field is of type Object, includes ALL fields, which in turn generally prevents the removal of all objects
// Clazz clazz = addCreatedObject(creation);
// clazz.includeAllConstructors();
// }
// }
//
// Clazz clazz = getDeclaringClass();
// if(field.isStatic()) {
// clazz.setInitialized();
// }
// else {
// clazz.setInstantiated();
// clazz.includeAllConstructors();
// }
// }
/**
* The field is included as part of an API so we must assume it can be accessed
* with any compatible arguments.
*/
void propagateFromUnknownSource() {
super.propagateFromUnknownSource();
Clazz clazz = getDeclaringClass();
if(!field.isStatic()) {
addCreatedObject(clazz.getBTClass());
clazz.setInstantiated();
clazz.includeConstructors();
}
}
public void setAccessed() {
if(isAccessed()) {
return;
}
super.setAccessed();
if(field.isStatic()) {
declaringClass.setInitialized();
}
}
public void setRequired() {
if(isRequired()) {
return;
}
super.setRequired();
BT_Class type = field.getFieldType();
if(type.isBasicTypeClass) {
return;
}
Repository rep = getRepository();
JaptRepository japtRepository = rep.repository;
EntryPointLister lister = rep.entryPointLister;
boolean checkEntryPoints = (lister != null) && !japtRepository.isInternalClass(getBTClass());
if(checkEntryPoints && japtRepository.isInternalClass(type)) {
lister.foundEntryTo(type, field);
}
rep.getClazz(type).setRequired();
}
public String toString() {
return getName();
}
public String getName() {
return field.toString();
}
}
|
package menage;
public class MAIN {
public static void main(String[] args) {
// TODO Auto-generated method stub
principale p = new principale();
p.setVisible(true);
}
}
|
package io.cucumber.cucumberexpressions;
import org.apiguardian.api.API;
@API(status = API.Status.STABLE)
public class CucumberExpressionException extends RuntimeException {
CucumberExpressionException(String message) {
super(message);
}
CucumberExpressionException(String message, Throwable cause) {
super(message, cause);
}
}
|
package predictor;
public class KalmanFilter {
private double Q = 0.00001;
private double R = 0.1;
private double P = 1, X = 0, K;
private void measurementUpdate(){
K = (P + Q) / (P + Q + R);
//P = R * (P + Q) / (R + P + Q);
P = R * K;
}
public double update(double measurement){
measurementUpdate();
double result = X + (measurement - X) * K;
X = result;
return result;
}
}
|
package com.t.s.model.biz;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.t.s.model.dao.FreeBoardDao;
import com.t.s.model.dto.FreeBoardDto;
@Service
public class FreeBoardBizImpl implements FreeBoardBiz {
@Autowired
private FreeBoardDao dao;
@Override
public List<FreeBoardDto> selectFreeBoardList(int groupno, int pagenum) {
// TODO Auto-generated method stub
return dao.selectFreeBoardList(groupno,pagenum);
}
@Override
public int selectFreeBoardListCnt(int groupno) {
// TODO Auto-generated method stub
return dao.selectFreeBoardListCnt(groupno);
}
@Override
public FreeBoardDto selectFreeBoardDetail(int boardno) {
// TODO Auto-generated method stub
return dao.selectFreeBoardDetail(boardno);
}
@Override
public int insertFreeBoard(FreeBoardDto freeboarddto) {
// TODO Auto-generated method stub
return dao.insertFreeBoard(freeboarddto);
}
@Override
public int updateFreeBoard(FreeBoardDto freeboarddto) {
// TODO Auto-generated method stub
return dao.updateFreeBoard(freeboarddto);
}
@Override
public int deleteFreeBoard(int boardno) {
// TODO Auto-generated method stub
return dao.deleteFreeBoard(boardno);
}
@Override
public int deleteUserFreeBoard(String userid) {
// TODO Auto-generated method stub
return dao.deleteUserFreeBoard(userid);
}
}
|
package common;
import java.util.Arrays;
/**
* Created by Choen-hee Park
* User : chpark
* Date : 14/08/2020
* Time : 1:15 AM
*/
public class PrintableMain {
protected static <T, F> void printResult(T input, F function) {
// 입력,출력 모두 String으로 반환해서 출력하고있으므로, 입력,출력을 toString();으로 추상화하였다.
printResultWithManyInput(function, input);
}
protected static <T, F> void printResultWithManyInput(F function, T... input) {
StringBuilder sb = new StringBuilder();
sb.append("input : ");
for (T t : input) {
sb.append("<");
sb.append(t).append("> ");
}
sb.append("\nresult: <").append(toString(function)).append(">\n");
System.out.println(sb.toString());
}
private static <T> T toString(T input) {
// TODO: 타입 추가가 될 경우 분기문이 추가될 수 있음 (추가없이 더 추상화할 방법은 없을까?)
if (input instanceof Object[]) {
return (T) Arrays.toString((Object[]) input);
} else if (input instanceof int[]) {
return (T) Arrays.toString((int[]) input);
}
return input;
}
}
|
package Airplane;
import java.util.Random;
public abstract class Airplane {
public int startEngine (){
Random randomTime = new Random();
int timeBeforeStart = randomTime.nextInt(88-20)+20;
return timeBeforeStart;
}
public int takeOff(){
Random randomTime = new Random();
int fullTankDistance = randomTime.nextInt(1000-0)+0;
return fullTankDistance;
}
public void landing(){
System.out.println("The plane is landing");
}
}
|
package www.limo.com.mymovies.apiClients;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import www.limo.com.mymovies.entities.Movies;
public interface LatestMoviesInterface {
@GET("/schedule")
Call<List<Movies>> getLatestMovies();
}
|
package com.luban.command.weather.controller;
import com.luban.command.weather.service.WeatherService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName WeatherController
* @Author yuanlei
* @Date 2018/10/16 10:19
* @Version 1.0
**/
@RestController
@EnableAutoConfiguration
@RequestMapping("/index")
public class WeatherController {
@Autowired
private WeatherService weatherService;
/**
* 获取时间天气
* @return
*/
@GetMapping("/weathertime")
@ApiOperation(value = "创建时间天气接口",notes = "时间天气")
@ResponseBody
public String getWeatherTime(){
String weatherTime = weatherService.getWeatherTime();
return weatherTime;
}
}
|
package Tugas;
/**
*
* @author Master
*/
public class Windows extends Laptop{
public String fitur;
public Windows() {
}
public Windows(String fitur, String jnsBaterai, String merk, String jnsProcessor, int kecProcessor, int sizeMemory) {
super(jnsBaterai, merk, jnsProcessor, kecProcessor, sizeMemory);
this.fitur = fitur;
}
public void tampilWindows(){
super.tampilData();
System.out.println("Fitur\t\t\t: " + fitur);
}
}
|
package com.fenjuly.arrowdownloadbutton;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import com.fenjuly.library.ArrowDownloadButton;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
int count = 0;
int progress = 0;
ArrowDownloadButton button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (ArrowDownloadButton)findViewById(R.id.arrow_download_button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((count % 2) == 0) {
button.startAnimating();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
progress = progress + 1;
button.setProgress(progress);
}
});
}
}, 800, 20);
} else {
button.reset();
}
count++;
}
});
}
}
|
public class L338 {
public int[] countBits(int num) {
if(num==0){
return new int[]{0};
}
int[] numBits=new int[num+1];
numBits[0]=0;
numBits[1]=1;
for(int i=2;i<=num;i++){
if((i&1)==1){
numBits[i]=numBits[i-1]+1;
}else{
numBits[i]=numBits[i/2];
}
}
return numBits;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.auth;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.appbrand.jsapi.auth.JsApiLogin.LoginTask;
import com.tencent.mm.protocal.c.aoy;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.u.a.c;
import com.tencent.mm.u.a.c.a;
import java.util.LinkedList;
class JsApiLogin$LoginTask$4 implements a<c> {
final /* synthetic */ LoginTask fJD;
final /* synthetic */ LoginTask.a fJF;
JsApiLogin$LoginTask$4(LoginTask loginTask, LoginTask.a aVar) {
this.fJD = loginTask;
this.fJF = aVar;
}
public final /* synthetic */ void b(int i, int i2, String str, l lVar) {
c cVar = (c) lVar;
x.i("MicroMsg.JsApiLogin", "onSceneEnd errType = %d, errCode = %d ,errMsg = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
if (i == 0 && i2 == 0 && cVar != null) {
aoy CW = cVar.CW();
int i3 = CW.rRd.bMH;
String str2 = CW.rRd.bMI;
String str3 = CW.rRf;
x.i("MicroMsg.JsApiLogin", "stev NetSceneJSLogin jsErrcode %d", new Object[]{Integer.valueOf(i3)});
if (i3 == -12000) {
LinkedList linkedList = CW.rEI;
x.i("MicroMsg.JsApiLogin", "stev appName %s, appIconUrl %s", new Object[]{CW.jSv, CW.rbh});
this.fJF.a(linkedList, str2, r0, str3);
return;
} else if (i3 == 0) {
this.fJF.qe(CW.rRg);
x.i("MicroMsg.JsApiLogin", "resp data code [%s]", new Object[]{r0});
return;
} else if (i3 == -12001) {
this.fJF.aid();
x.e("MicroMsg.JsApiLogin", "onSceneEnd NetSceneJSLogin Invalid Scope %s", new Object[]{str2});
return;
} else if (i3 == -12002) {
this.fJF.aid();
x.e("MicroMsg.JsApiLogin", "onSceneEnd NetSceneJSLogin Invalid Data %s", new Object[]{str2});
return;
} else if (i3 == -12003) {
this.fJF.aid();
x.e("MicroMsg.JsApiLogin", "onSceneEnd NetSceneJSLogin Invalid ApiName %s", new Object[]{str2});
return;
} else {
this.fJF.aid();
x.e("MicroMsg.JsApiLogin", "onSceneEnd NetSceneJSLogin %s", new Object[]{str2});
return;
}
}
this.fJF.aid();
}
}
|
package com.mkay.scorecard;
/**
* Created by Marcus on 16/12/14.
*/
import android.widget.TextView;
public class News {
public String title;
public String datePublished;
public String content;
public News(String title, String datePublished, String content) {
this.title = title;
this.datePublished = datePublished;
this.content = content;
}
}
|
/*
* (C) Copyright 2016 Hewlett Packard Enterprise Development LP
*
* 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.infrastructure.persistence;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import java.text.ParseException;
@Test
public class PersistUtilsTest {
private final PersistUtils persistUtils = new PersistUtils();
public void test3DigitWithSpace() throws ParseException {
checkParseTimestamp("2016-01-01 01:01:01.123Z", "2016-01-01 01:01:01.123Z");
}
public void test2DigitWithSpace() throws ParseException {
checkParseTimestamp("2016-01-01 01:01:01.15Z", "2016-01-01 01:01:01.150Z");
}
public void test1DigitWithSpace() throws ParseException {
checkParseTimestamp("2016-01-01 01:01:01.1Z", "2016-01-01 01:01:01.100Z");
}
public void test3DigitWithT() throws ParseException {
checkParseTimestamp("2016-01-01T01:01:01.123Z", "2016-01-01T01:01:01.123Z");
}
public void test2DigitWithT() throws ParseException {
checkParseTimestamp("2016-01-01T01:01:01.15Z", "2016-01-01T01:01:01.150Z");
}
public void test1DigitWithT() throws ParseException {
checkParseTimestamp("2016-01-01T01:01:01.1Z", "2016-01-01T01:01:01.100Z");
}
private void checkParseTimestamp(final String start, final String expected) throws ParseException {
assertEquals(persistUtils.parseTimestamp(start).getTime(), persistUtils.parseTimestamp(expected).getTime());
}
}
|
package bufmgr;
import global.GlobalConst;
import global.PageId;
public class HashTableBuffer implements GlobalConst {
private HashTableBufferEntry hashTable[];
private int numFrames;
public HashTableBuffer(int numFrames) {
this.numFrames = numFrames;
this.hashTable = new HashTableBufferEntry[numFrames];
for(int i = 0; i < numFrames; i++) {
hashTable[i] = null;
}
}
private int hash(PageId pageNum) {
return (pageNum.pid % numFrames);
}
public boolean add(PageId pageNum, int frameNum) {
HashTableBufferEntry entry = new HashTableBufferEntry();
int index = hash(pageNum);
return false;
}
}
|
package jp.noxi.collection;
import java.util.List;
import org.junit.Test;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class InstanceOfCollectionTest {
@Test
public void testInstanceOf() throws Exception {
Enumerable<Object> enumerable = Linq.asEnumerable((Object) 1, 2, "a", "b");
List<String> result = enumerable.instanceOf(String.class).toList();
assertThat(result, is(contains("a", "b")));
}
@Test
public void testInstanceOf_empty() throws Exception {
Enumerable<Object> enumerable = Linq.asEnumerable((Object) 1, 2, "a", "b");
List<Long> result = enumerable.instanceOf(Long.class).toList();
assertThat(result, is(empty()));
}
}
|
package com.tencent.mm.plugin.emoji.provider;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.emoji.model.i;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.emotion.EmojiGroupInfo;
import com.tencent.mm.storage.emotion.EmojiInfo;
import com.tencent.mm.storage.emotion.o;
import java.util.ArrayList;
public class EmotionContentProvider extends ContentProvider {
private static final UriMatcher ijd;
static {
UriMatcher uriMatcher = new UriMatcher(-1);
ijd = uriMatcher;
uriMatcher.addURI("com.tencent.mm.storage.provider.emotion", "EmojiGroupInfo", 1);
ijd.addURI("com.tencent.mm.storage.provider.emotion", "userinfo", 2);
ijd.addURI("com.tencent.mm.storage.provider.emotion", "GetEmotionListCache", 3);
ijd.addURI("com.tencent.mm.storage.provider.emotion", "EmojiInfo", 4);
ijd.addURI("com.tencent.mm.storage.provider.emotion", "EmojiInfoDesc", 5);
}
public boolean onCreate() {
x.i("MicroMsg.EmotionContentProvider", "[onCreate]");
return true;
}
public Cursor query(Uri uri, String[] strArr, String str, String[] strArr2, String str2) {
x.i("MicroMsg.EmotionContentProvider", "[query] path:%s selection:%s", uri.getPath(), str);
switch (ijd.match(uri)) {
case 1:
au.HU();
return c.FO().b(str, strArr2, 2);
case 3:
au.HU();
return c.FO().b(str, strArr2, 2);
case 4:
au.HU();
return c.FO().b(str, strArr2, 2);
case 5:
au.HU();
return c.FO().b(str, strArr2, 2);
default:
return null;
}
}
public String getType(Uri uri) {
return null;
}
public Uri insert(Uri uri, ContentValues contentValues) {
switch (ijd.match(uri)) {
case 3:
au.HU();
return Uri.withAppendedPath(uri, String.valueOf(c.FO().insert("GetEmotionListCache", o.dhO.sKz, contentValues)));
default:
return uri;
}
}
public int delete(Uri uri, String str, String[] strArr) {
switch (ijd.match(uri)) {
case 3:
au.HU();
return c.FO().delete("GetEmotionListCache", str, strArr);
default:
return 0;
}
}
public int update(Uri uri, ContentValues contentValues, String str, String[] strArr) {
if (!g.Eg().Dx()) {
return -1;
}
switch (ijd.match(uri)) {
case 1:
au.HU();
return c.FO().update("EmojiGroupInfo", contentValues, str, strArr);
case 2:
au.HU();
c.DT().set(((Integer) contentValues.get("type")).intValue(), contentValues.get("value"));
return 0;
default:
return -1;
}
}
public Bundle call(String str, String str2, Bundle bundle) {
boolean z = true;
x.d("MicroMsg.EmotionContentProvider", "[call] method:%s", str);
Bundle bundle2;
Bundle bundle3;
Bundle bundle4;
if (str.equals("getAccPath")) {
bundle2 = new Bundle();
bundle2.putString("path", g.Ei().dqp);
return bundle2;
} else if (str.equals("getEmojiKey")) {
bundle2 = new Bundle();
bundle2.putString("key", i.aEA().igx.getKey());
return bundle2;
} else if (str.equals("ConfigStorage.getBoolean")) {
bundle3 = new Bundle();
au.HU();
bundle3.putBoolean("key", ((Boolean) c.DT().get(bundle.getInt("key"), Boolean.valueOf(false))).booleanValue());
return bundle3;
} else if (str.equals("ConfigStorage.getString")) {
bundle4 = new Bundle();
au.HU();
bundle4.putString("key", (String) c.DT().get(bundle.getInt("key"), (Object) ""));
return bundle4;
} else if (str.equals("getAllCustomEmoji")) {
bundle2 = new Bundle(EmojiInfo.class.getClassLoader());
bundle2.putParcelableArrayList("data", i.aEA().aDY());
return bundle2;
} else {
if (str.equals("getRamdomEmoji")) {
if (bundle != null) {
bundle.setClassLoader(EmojiInfo.class.getClassLoader());
EmojiInfo emojiInfo = (EmojiInfo) bundle.getParcelable("emoji");
bundle3 = new Bundle(EmojiInfo.class.getClassLoader());
bundle3.putParcelable("data", ((com.tencent.mm.plugin.emoji.b.c) g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().c(emojiInfo));
return bundle3;
}
String str3 = "MicroMsg.EmotionContentProvider";
String str4 = "[getRamdomEmoji] extras:%s";
Object[] objArr = new Object[1];
if (bundle != null) {
z = false;
}
objArr[0] = Boolean.valueOf(z);
x.e(str3, str4, objArr);
} else if (str.equals("getCurLangDesc")) {
bundle2 = new Bundle();
bundle2.putString("data", i.aEv().zf(str2));
return bundle2;
} else if (str.equals("countCustomEmoji")) {
bundle4 = new Bundle();
bundle4.putInt("data", i.aEA().igx.ln(true));
return bundle4;
} else if (str.equals("countProductId")) {
bundle2 = new Bundle();
bundle2.putInt("data", i.aEA().igx.zs(str2));
return bundle2;
} else if (str.equals("getDownloadedCount")) {
bundle2 = new Bundle();
bundle2.putInt("data", i.aEA().aDX());
return bundle2;
} else if (str.equals("getEmojiListByGroupId")) {
bundle4 = new Bundle(EmojiInfo.class.getClassLoader());
bundle4.putParcelableArrayList("data", (ArrayList) ((com.tencent.mm.plugin.emoji.b.c) g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().zk(str2));
return bundle4;
} else if (str.equals("getEmojiGroupInfoList")) {
bundle2 = new Bundle(EmojiGroupInfo.class.getClassLoader());
bundle2.putParcelableArrayList("data", i.aEA().aDW());
return bundle2;
}
return null;
}
}
}
|
package Algorithm;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
//给定一个二叉树,返回它的中序 遍历。
public class a94 {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ans =new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while (cur!=null||!stack.isEmpty()){
while (cur!=null){
stack.push(cur);
cur=cur.left;
}
cur=stack.pop();
ans.add(cur.val);
cur=cur.right;
}
return ans;
}
// private void inorder(TreeNode root, List<Integer> ans){
// if(root==null)return;
// inorder(root.left,ans);
// ans.add(root.val);
// inorder(root.right,ans);
// }
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package magap;
//import com.magapinv.www.interfacesmagap.Ingresar_Unidad;
//import com.magapinv.www.interfacesmagap.Movimiento_Inventario_Responsable;
//import com.magapinv.www.interfacesmagap.Reportes;
import com.magapinv.www.interfacesmagap.login;
/**
*
* @author User
*/
public class Magap {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Movimiento_Inventario_Responsable e = new Movimiento_Inventario_Responsable();
// e.setVisible(true);
// Reportes r= new Reportes();
// r.setVisible(true);
// Ingresar_Unidad i = new Ingresar_Unidad();
// i.setVisible(true);
login log =new login();
log.setVisible(true);
}
}
|
package ru.otus.hw01maven;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import java.util.Map;
/**
* The class compares the current list of domain names and IP addresses with a blacklist.
*/
public class HelloOtus extends AbstractSubnetsGenerate{
public static void main(String[] args){
final Map<String, Subnet> usedSites = AbstractSubnetsGenerate.getUsedSites();
final Map<String, Subnet> blackList = AbstractSubnetsGenerate.getBlackList();
final MapDifference<String, Subnet> diff = Maps.difference(usedSites, blackList);
System.out.println("\nList of all used sites:\n");
for (Map.Entry<String, Subnet> entry: usedSites.entrySet()){
String key = entry.getKey();
String value = entry.getValue().getDomain();
System.out.printf( "IP address: %s, Domain: %s \n", key, value );
}
System.out.println("\nList of allowed sites:\n");
for (Map.Entry<String, Subnet> entry: diff.entriesOnlyOnLeft().entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getDomain();
System.out.printf( "IP address: %s, Domain: %s \n", key, value );
}
System.out.println("\nList of new blocked sites: \n");
for (Map.Entry<String, Subnet> entry: diff.entriesOnlyOnRight().entrySet()) {
String key = entry.getKey();
String value = entry.getValue().getDomain();
System.out.printf( "IP address: %s, Domain: %s \n", key, value );
}
}
}
|
package project.exception;
public class DimensioniEccessiException extends RuntimeException{
private static final long serialVersionUID = 1L;
public DimensioniEccessiException() {}
public DimensioniEccessiException(String str) {
super(str);
}
}
|
package com.rc.components.room;
import com.rc.adapter.RoomItemViewHolder;
import com.rc.adapter.RoomItemsAdapter;
import com.rc.app.Launcher;
import com.rc.res.Colors;
import com.rc.components.NotificationTextArea;
import com.rc.components.RCMenuItemUI;
import com.rc.db.model.Room;
import com.rc.db.service.RoomService;
import com.rc.panels.RoomMembersPanel;
import com.rc.panels.RoomsPanel;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import static com.rc.panels.ChatPanel.CHAT_ROOM_OPEN_ID;
/**
* 房间列表右键菜单
* Created by song on 2019/9/20.
*/
public class RoomPopupMenu extends JPopupMenu
{
private JMenuItem itemEnter = new JMenuItem("打开");
private JMenuItem itemNotify = new JMenuItem("消息免打扰");
private JMenuItem itemDelete = new JMenuItem("删除聊天");
private RoomItemsAdapter roomItemsAdapter;
private RoomService roomService = Launcher.roomService;
public RoomPopupMenu(RoomItemsAdapter roomItemsAdapter)
{
this.roomItemsAdapter = roomItemsAdapter;
initMenuItem();
}
private void initMenuItem()
{
itemEnter.setUI(new RCMenuItemUI(100, 40));
itemEnter.addActionListener(new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
RoomItemViewHolder viewHolder = (RoomItemViewHolder) RoomPopupMenu.this.getInvoker();
roomItemsAdapter.openRoomPanel(viewHolder);
}
});
itemNotify.setUI(new RCMenuItemUI(100, 40));
itemNotify.addActionListener(new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
RoomItemViewHolder viewHolder;
if (RoomPopupMenu.this.getInvoker() instanceof NotificationTextArea)
{
NotificationTextArea textArea = (NotificationTextArea) RoomPopupMenu.this.getInvoker();
viewHolder = (RoomItemViewHolder) textArea.getParent().getParent();
}
else
{
viewHolder = (RoomItemViewHolder) RoomPopupMenu.this.getInvoker();
}
Room room = roomService.findById(viewHolder.getTag().toString());
room.setShowNotify(!room.isShowNotify());
roomService.update(room);
if (CHAT_ROOM_OPEN_ID.equals(room.getRoomId()) && RoomMembersPanel.getContext().isVisible())
{
RoomMembersPanel.getContext().updateUI();
}
RoomsPanel.getContext().updateRoomItem(room.getRoomId());
}
});
itemDelete.setUI(new RCMenuItemUI(100, 40));
itemDelete.addActionListener(new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
RoomItemViewHolder viewHolder = (RoomItemViewHolder) RoomPopupMenu.this.getInvoker();
// todo 发送删除聊天请求
}
});
this.add(itemEnter);
this.add(itemNotify);
this.add(itemDelete);
setBorder(new LineBorder(Colors.SCROLL_BAR_TRACK_LIGHT));
setBackground(Colors.FONT_WHITE);
}
@Override
public void show(Component invoker, int x, int y)
{
// 弃用
}
public void show(RoomItemViewHolder viewHolder, Component invoker, int x, int y)
{
Room room = roomService.findById(viewHolder.getTag().toString());
if (room.isShowNotify())
{
itemNotify.setText("消息免打扰");
}
else
{
itemNotify.setText("显示通知气泡");
}
super.show(invoker, x, y);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.tarkesh.utility;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
/**
*
* @author nsdc-ey
*/
public class EnchoderDecoder {
private static MessageDigest md;
public static String cryptWithBase64(String password) throws UnsupportedEncodingException {
byte[] message = password.getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
return encoded;
}
public static String decryptWithBase64(String encoded) throws UnsupportedEncodingException {
byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);
return new String(decoded, "UTF-8");
}
public static String cryptWithMD5(String pass) {
try {
md = MessageDigest.getInstance("MD5");
byte[] passBytes = pass.getBytes();
md.reset();
byte[] digested = md.digest(passBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digested.length; i++) {
sb.append(Integer.toHexString(0xff & digested[i]));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
System.out.println("Password encryption Error");
}
return null;
}
public static String decryptWithMD5(String pass) {
try {
md = MessageDigest.getInstance("MD5");
byte[] passBytes = pass.getBytes();
md.reset();
byte[] digested = md.digest(passBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digested.length; i++) {
sb.append(Integer.toHexString(0xff & digested[i]));
}
return sb.toString();
} catch (NoSuchAlgorithmException ex) {
System.out.println("Password encryption Error");
}
return null;
}
private static byte[] getSalt() throws NoSuchAlgorithmException, NoSuchProviderException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "SUN");
//Create array for salt
byte[] salt = new byte[16];
//Get a random salt
sr.nextBytes(salt);
//return salt
return salt;
}
private static String getSecurePassword(String passwordToHash, byte[] salt) {
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
//MessageDigest md = MessageDigest.getInstance("MD5");
// MessageDigest md = MessageDigest.getInstance("SHA-1");
// MessageDigest md = MessageDigest.getInstance("SHA-256");
// MessageDigest md = MessageDigest.getInstance("SHA-384");
MessageDigest md = MessageDigest.getInstance("SHA-512");
//Add password bytes to digest
md.update(salt);
//Get the hash's bytes
byte[] bytes = md.digest(passwordToHash.getBytes());
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return generatedPassword;
}
private static String generateStorngPasswordHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
int iterations = 1000;
char[] chars = password.toCharArray();
byte[] salt = getSalt();
PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 64 * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = skf.generateSecret(spec).getEncoded();
return iterations + ":" + toHex(salt) + ":" + toHex(hash);
}
private static String toHex(byte[] array) throws NoSuchAlgorithmException {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0) {
return String.format("%0" + paddingLength + "d", 0) + hex;
} else {
return hex;
}
}
private static boolean validatePassword(String password, String generatedSecuredPasswordHash) throws NoSuchAlgorithmException, InvalidKeySpecException {
String[] parts = generatedSecuredPasswordHash.split(":");
int iterations = Integer.parseInt(parts[0]);
byte[] salt = fromHex(parts[1]);
byte[] hash = fromHex(parts[2]);
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, hash.length * 8);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] testHash = skf.generateSecret(spec).getEncoded();
int diff = hash.length ^ testHash.length;
for (int i = 0; i < hash.length && i < testHash.length; i++) {
diff |= hash[i] ^ testHash[i];
}
return diff == 0;
}
private static byte[] fromHex(String hex) {
byte[] bytes = new byte[hex.length() / 2];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
}
return bytes;
}
}
|
package com.tencent.mm.plugin.wallet.balance.ui;
import android.graphics.Bitmap;
import com.tencent.mm.plugin.wallet.balance.ui.WalletBalanceSaveUI.7;
class WalletBalanceSaveUI$7$1 implements Runnable {
final /* synthetic */ Bitmap abc;
final /* synthetic */ 7 paO;
WalletBalanceSaveUI$7$1(7 7, Bitmap bitmap) {
this.paO = 7;
this.abc = bitmap;
}
public final void run() {
if (this.paO.paK.oZH != null && this.paO.paj != null && this.paO.paj.getTag() != null && this.paO.paj.getTag().equals(this.paO.paK.oZH.field_bindSerial)) {
this.paO.paj.setImageBitmap(this.abc);
}
}
}
|
/*
* 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 141052976
*/
public class Estado {
private int estado;
private String alfabeto;
private String comando;
public Estado() {}
public Estado(int estado, String alfabeto, String comando) {
this.estado = estado;
this.alfabeto = alfabeto;
this.comando = comando;
}
public int getEstado() {
return estado;
}
public void setEstado(int estado) {
this.estado = estado;
}
public String getAlfabeto() {
return alfabeto;
}
public void setAlfabeto(String alfabeto) {
this.alfabeto = alfabeto;
}
public String getComando() {
return comando;
}
public void setComando(String comando) {
this.comando = comando;
}
}
|
package cc.feefox.wechat.message.model;
/**
* 文本消息
*
* @Package: cc.feefox.wechat.message.model
* @author: cc
* @date: 2018年8月18日 下午2:52:48
*/
public class TextMessage extends BaseMessage {
// 消息内容
private String Content;
//
// private int FuncFlag;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
// public int getFuncFlag() {
// return FuncFlag;
// }
//
// public void setFuncFlag(int funcFlag) {
// FuncFlag = funcFlag;
// }
}
|
package cn.com.hln.modules.biz.sysdict.dto;
import java.io.Serializable;
/**
* @author chen_gang
* @version V1.0
* @Description 定义基础 dto 类
* @date 2014年9月24日 下午8:48:28
*/
public class BaseDTO implements Serializable {
private static final long serialVersionUID = -1641854051866090244L;
//操作当前系统的 user 的org id
private Long userOrgId;
//操作当前系统的 userId
private Long opUserId;
private String createUserNameExt;
private String createOrgNameExt;
private String baseExt2;
private String baseExt3;
private String baseExt4;
private String baseExt5;
private String baseExt6;
private String baseExt7;
public String getBaseExt6() {
return baseExt6;
}
public void setBaseExt6(String baseExt6) {
this.baseExt6 = baseExt6;
}
public String getBaseExt7() {
return baseExt7;
}
public void setBaseExt7(String baseExt7) {
this.baseExt7 = baseExt7;
}
public String getCreateUserNameExt() {
return createUserNameExt;
}
public void setCreateUserNameExt(String createUserNameExt) {
this.createUserNameExt = createUserNameExt;
}
public String getCreateOrgNameExt() {
return createOrgNameExt;
}
public void setCreateOrgNameExt(String createOrgNameExt) {
this.createOrgNameExt = createOrgNameExt;
}
public Long getUserOrgId() {
return userOrgId;
}
public void setUserOrgId(Long userOrgId) {
this.userOrgId = userOrgId;
}
public Long getOpUserId() {
return opUserId;
}
public void setOpUserId(Long opUserId) {
this.opUserId = opUserId;
}
public String getBaseExt2() {
return baseExt2;
}
public void setBaseExt2(String baseExt2) {
this.baseExt2 = baseExt2;
}
public String getBaseExt3() {
return baseExt3;
}
public void setBaseExt3(String baseExt3) {
this.baseExt3 = baseExt3;
}
public String getBaseExt4() {
return baseExt4;
}
public void setBaseExt4(String baseExt4) {
this.baseExt4 = baseExt4;
}
public String getBaseExt5() {
return baseExt5;
}
public void setBaseExt5(String baseExt5) {
this.baseExt5 = baseExt5;
}
}
|
/*
* 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 loc.dto;
/**
*
* @author hi
*/
public class RoomCartDTO {
private String roomID, hotelID, hotelName, typeID, statusID, image, checkInDate, checkOutDate;
private double price;
private int amount;
public RoomCartDTO() {
}
public RoomCartDTO(String roomID, String hotelID, String hotelName, String typeID, String image, String checkInDate, String checkOutDate, double price, int amount) {
this.roomID = roomID;
this.hotelID = hotelID;
this.hotelName = hotelName;
this.typeID = typeID;
this.image = image;
this.checkInDate = checkInDate;
this.checkOutDate = checkOutDate;
this.price = price;
this.amount = amount;
}
public String getRoomID() {
return roomID;
}
public void setRoomID(String roomID) {
this.roomID = roomID;
}
public String getHotelID() {
return hotelID;
}
public void setHotelID(String hotelID) {
this.hotelID = hotelID;
}
public String getHotelName() {
return hotelName;
}
public void setHotelName(String hotelName) {
this.hotelName = hotelName;
}
public String getTypeID() {
return typeID;
}
public void setTypeID(String typeID) {
this.typeID = typeID;
}
public String getStatusID() {
return statusID;
}
public void setStatusID(String statusID) {
this.statusID = statusID;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCheckInDate() {
return checkInDate;
}
public void setCheckInDate(String checkInDate) {
this.checkInDate = checkInDate;
}
public String getCheckOutDate() {
return checkOutDate;
}
public void setCheckOutDate(String checkOutDate) {
this.checkOutDate = checkOutDate;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
|
package com.plter.notes.atys;
class MediaType{
static final int PHOTO = 1;
static final int VIDEO = 2;
}
|
package com.ncst.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private final String TAG="MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
String str=savedInstanceState.getString("key");//得到数据
Log.d("MainActivity", "活动恢复,数据为:"+str);
} else {
Log.d("MainActivity", "这是活动正常启动");
}
Button btnNormal= ((Button) findViewById(R.id.btn_normal));
Button btnDialog= ((Button) findViewById(R.id.btn_dialog));
btnNormal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,NormalActivity.class);
startActivity(intent);
}
});
btnDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,DialogActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key","data");
Log.d(TAG, "onSaveInstanceState: ");
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
String str=savedInstanceState.getString("key");
Log.d(TAG, "onRestoreInstanceState: "+str);
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart: ");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: ");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause: ");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop: ");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy: ");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart: ");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.add_item:
Toast.makeText(this,"add clicked",Toast.LENGTH_SHORT).show();
break;
case R.id.delete_item:
Toast.makeText(this,"delete clicked",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
|
package cn.itcast.job.task.checkversion;
import cn.itcast.job.cache.ConfigConstant;
import cn.itcast.job.pojo.dependices.DependicesNode;
import cn.itcast.job.utils.FileUtil;
import cn.itcast.job.utils.StringUtil;
import java.io.IOException;
import java.util.Stack;
public class DependicesFileReadAndGetTree {
public static DependicesNode root;
public static Stack<DependicesNode> stack = new Stack<>();
public static DependicesNode dependicesFileReadAndGetTree() {
FileUtil.readFileEveryLine(ConfigConstant.DEPENDICES_PATH,
new FileUtil.ControlFileEveryLineCallback() {
@Override
public void control(String line) throws IOException {
if (line != null && line.contains("--- ")) {
if (root == null) {
root = new DependicesNode(true, null);
stack.push(root);
}
DependicesNode node = new DependicesNode(line);
System.out.println("node " + node.toString());
if (stack.peek().numOfShugang < node.numOfShugang) {
// node.parent = stack.peek();
node.setParent(stack.peek());
stack.push(node);
} else if (stack.peek().numOfShugang == node.numOfShugang) {
stack.pop();
// node.parent = stack.peek();
node.setParent(stack.peek());
stack.push(node);
} else if (stack.peek().numOfShugang > node.numOfShugang) {
while (!stack.isEmpty() && stack.peek().numOfShugang >= node.numOfShugang) {
stack.pop();
}
DependicesNode parent = stack.peek();
stack.push(node);
// node.parent = parent;
node.setParent(parent);
}
}
}
});
System.out.println("root " + root);
return root;
}
}
|
package samsungTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOJ_20055_컨베이어벨트위의로봇 {
private static int N,K;
private static int[] belt;
private static int[] roboat;
private static int[] beltR;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
belt = new int[N];
roboat = new int[N];
beltR = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
belt[i] = Integer.parseInt(st.nextToken());
}
for (int i = N-1; i >= 0; i--) {
beltR[i] = Integer.parseInt(st.nextToken());
}
int cnt = 0;
while(true) {
Job();
cnt++;
// 4. 내구도 확인
if(checkDur()) break;
}
System.out.println(cnt);
}
private static void Job() {
// 1. 벨트 회전
rotate();
// 2. 로봇 움직이기
moveRoboat();
// 3. 로봇올리기
dropRoboat();
}
// 1.
private static void rotate() {
int tmp = belt[N-1];
for (int i = N-1; i > 0; i--) {
belt[i] = belt[i-1];
roboat[i] = roboat[i-1];
}
belt[0] = beltR[0];
roboat[0] = 0;
roboat[N-1] = 0;
for (int i = 1; i < N; i++) {
beltR[i-1] = beltR[i];
}
beltR[N-1] = tmp;
}
// 2.
private static void moveRoboat() {
for (int i = N-2; i >= 0; i--) {
// 앞에 로봇이 없고 내구도 0 이 아니라면
if(roboat[i] == 1 && roboat[i+1] == 0 && belt[i+1] >=1) {
roboat[i+1] = 1;
roboat[i] = 0;
belt[i+1]--;
}
}
}
// 3.
private static void dropRoboat() {
if(roboat[0] == 0 && belt[0] >=1) {
roboat[0] = 1;
belt[0]--;
}
}
// 4.
private static boolean checkDur() {
// System.out.println(Arrays.toString(belt));
// System.out.println(Arrays.toString(beltR));
// System.out.println(Arrays.toString(roboat));
// System.out.println();
int cnt = 0;
for (int i = 0; i < N; i++) {
if(belt[i] == 0) cnt++;
if(cnt >= K) return true;
}
for (int i = 0; i < N; i++) {
if(beltR[i] == 0) cnt++;
if(cnt >= K) return true;
}
return false;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.clerezza.implementation.graphmatching;
import java.util.*;
/**
* An Iterator over all permuations of a list.
*
* @author reto
*/
class PermutationIterator<T> implements Iterator<List<T>> {
private Iterator<List<T>> restIterator;
private List<T> list;
private List<T> next;
int posInList = 0; //the position of the last element of next returned list
//with list, this is the one excluded from restIterator
PermutationIterator(List<T> list) {
this.list = Collections.unmodifiableList(list);
if (list.size() > 1) {
createRestList();
}
prepareNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public List<T> next() {
List<T> result = next;
if (result == null) {
throw new NoSuchElementException();
}
prepareNext();
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
private void createRestList() {
List<T> restList = new ArrayList<T>(list);
restList.remove(posInList);
restIterator = new PermutationIterator<T>(restList);
}
private void prepareNext() {
next = getNext();
}
private List<T> getNext() {
if (list.size() == 0) {
return null;
}
if (list.size() == 1) {
if (posInList++ == 0) {
return new ArrayList<T>(list);
} else {
return null;
}
} else {
if (!restIterator.hasNext()) {
if (posInList < (list.size() - 1)) {
posInList++;
createRestList();
} else {
return null;
}
}
List<T> result = restIterator.next();
result.add(list.get(posInList));
return result;
}
}
}
|
package com.hesoyam.pharmacy.pharmacy.repository;
import com.hesoyam.pharmacy.pharmacy.model.Order;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.time.LocalDateTime;
import java.util.List;
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("SELECT ord FROM Order ord LEFT JOIN FETCH ord.orderItems WHERE (SELECT COUNT(offer) FROM ord.offers offer WHERE offer.supplier.id=:userId AND offer.offerStatus ='CREATED') = 0 " +
"AND ord.orderStatus = 'CREATED'AND ord.deadLine >= :todayDate")
List<Order> getUserPendingActionOrders(@Param("userId")Long id, @Param("todayDate") LocalDateTime localDateTime, Pageable pageable);
List<Order> getAllByPharmacy_Id(Long pharmacyId);
}
|
public class QuiGonJin extends Jedi implements LightSaber, Pilot{
public QuiGonJin(){
super("Qui-Gon Jin","Light Side","Galactic Republic",false);
}
public String lightSaber(){
return "green lightsaber";
}
public boolean pilot(){
return true;
}
}
|
package hw.gorovtsov.mathtesting.input;
public class NumSetOne {
}
|
package com.kdp.wanandroidclient.event;
/**
* 事件类型
* author: 康栋普
* date: 2018/4/12
*/
public class Event {
public enum Type {
REFRESH_ITEM, REFRESH_LIST, SCROLL_TOP,SCALE
}
public Type type;
public Object object;
public Event(Type type) {
this(type,null);
}
public Event(Type type, Object object) {
this.type = type;
this.object = object;
}
}
|
package com.cmp404.pharmacymanagement.model;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedDate;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
@Entity
public class Item implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, updatable = false)
private Long id;
private String name;
private String description;
private Long quantity;
private BigDecimal price;
@CreatedDate
private Date createTime;
@UpdateTimestamp
private Date updateTime;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "pharmacy_id", nullable = false)
private Pharmacy pharmacy;
public Item() {
}
public Item(String name, String description, Long quantity, BigDecimal price, Pharmacy pharmacy) {
this.name = name;
this.description = description;
this.quantity = quantity;
this.price = price;
this.pharmacy = pharmacy;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Long getPharmacy() {
return pharmacy.getId();
}
public void setPharmacy(Pharmacy pharmacy) {
this.pharmacy = pharmacy;
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", quantity=" + quantity +
", price=" + price +
", pharmacy=" + pharmacy +
'}';
}
}
|
package com.example.mahe.ieeefinaltask;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class forg_pass extends AppCompatActivity {
public static String extramsg = "Hello";
public void sendMessage(View view)
{
EditText et_username = (EditText)findViewById(R.id.editText3);
String s = et_username.getText().toString();
Intent intent= new Intent(this, MainActivity.class);
intent.putExtra(extramsg,s);
startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forg_pass);
}
}
|
package linkedList;
//jian pan 5728309
import java.util.Scanner;
public class singlylinkedlist {
public static void main(String [] args){
node newnode = new node(1);
node newnode1 = new node(2);
node newnode2 = new node(3);
System.out.println(newnode);
System.out.println(newnode1);
System.out.println(newnode2);
linkedList list = new linkedList();
//System.out.println(list.toString());
list.insert(8);
list.insert(2);
list.insert(5);
list.insert(3);
//list.insert(2);
//list.insert(5);
//list.insert(3);
System.out.println(list.toString());
list.search(2);
System.out.println(list.count());
list.delete(8);
list.delete(2);
list.delete(3);
System.out.println(list.search(3));
System.out.println(list.toString());
//System.out.println(list.toString());
}
}
|
package negocio.excecao;
public class TipoNaoDeclaradoException extends Exception {
public TipoNaoDeclaradoException(){
super("Tipo nao declarado");
}
}
|
package com.kingfish.show.utils;
import org.apache.commons.lang3.time.FastDateFormat;
import java.util.Date;
public class DateTimeUtil {
private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String toString(Date date) {
return FastDateFormat.getInstance(DEFAULT_PATTERN).format(date);
}
}
|
package com.saasbp.auth.adapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.WebApplicationContext;
import com.saasbp.auth.adapter.out.other.EmailSender;
import com.saasbp.auth.adapter.out.persistence.EmailResetsRepository;
import com.saasbp.auth.adapter.out.persistence.UsersRepository;
import com.saasbp.auth.application.port.in.EmailResetUseCase;
import com.saasbp.auth.application.service.EmailResetService;
import com.saasbp.common.security.PrincipalService;
@Configuration
@Scope(WebApplicationContext.SCOPE_REQUEST)
public class RequestScopedBeansConfiguration {
@Autowired
private UsersRepository usersRepository;
@Autowired
private EmailSender emailResource;
@Autowired
private EmailResetsRepository emailResetsRepository;
@Autowired
private PrincipalService principalService;
@Bean
@Scope(WebApplicationContext.SCOPE_REQUEST)
public EmailResetUseCase getEmailResetUseCaseBean() {
System.out.println("new email reset");
return new EmailResetService(emailResource, principalService, emailResetsRepository, emailResetsRepository,
usersRepository, usersRepository);
}
}
|
package pe.gob.sunarp.adm.service;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import oracle.jdbc.OracleTypes;
import pe.gob.sunarp.adm.database.AccesoDB;
public class EMPLEADOService extends AbstractService {
public int createEmpleado(String co_area, String co_cargo, String est_empl,
String ape_pat, String ape_mat, String nombre
) {
Connection cn = null;
try {
// Inicio: El objeto Connection
cn = AccesoDB.getConnection();
cn.setAutoCommit(true);
//usuario de sistema
String USU_SIST = nombre.substring(1, 1)+ape_pat;
// Ejecutar SP
String sql = "{call ADM_EMPL_CREATE(?,?,?,?,?,?,?)}";
CallableStatement cstm = cn.prepareCall(sql);
cstm.setString(1, co_area);
cstm.setString(2, USU_SIST);
cstm.setString(3, co_cargo);
cstm.setString(4, est_empl);
cstm.setString(5, ape_pat);
cstm.setString(6, ape_mat);
cstm.setString(7, nombre);
cstm.executeUpdate();
cstm.close();
// Fin
this.setCode(1);
this.setMensaje("Proceso ejecutado correctamente.");
} catch (Exception e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} finally {
try {
cn.close();
} catch (Exception e) {
}
}
return this.getCode();
}
public Map<String, ?> getEmpleadoByID(String CO_EMPL) {
Map<String, Object> empleado = null;
Connection cn = null;
try {
// Conexión
cn = AccesoDB.getConnection();
// Proceso
String sql = "{call ADM_EMPL_FINDBYID(?,?,?,?,?,?,?,?)}";
CallableStatement cstm = cn.prepareCall(sql);
cstm.setString(1, CO_EMPL);
cstm.registerOutParameter(2, java.sql.Types.VARCHAR);
cstm.registerOutParameter(3, java.sql.Types.VARCHAR);
cstm.registerOutParameter(4, java.sql.Types.VARCHAR);
cstm.registerOutParameter(5, java.sql.Types.VARCHAR);
cstm.registerOutParameter(6, java.sql.Types.VARCHAR);
cstm.registerOutParameter(7, java.sql.Types.VARCHAR);
cstm.registerOutParameter(8, java.sql.Types.VARCHAR);
cstm.executeUpdate();
empleado = new HashMap<>();
empleado.put("CO_EMPL", CO_EMPL);
empleado.put("CO_AREA", cstm.getString(2));
empleado.put("USU_SIST", cstm.getString(3));
empleado.put("CO_CARGO", cstm.getString(4));
empleado.put("EST_EMPL", cstm.getString(5));
empleado.put("APE_PAT", cstm.getString(6));
empleado.put("APE_MAT", cstm.getString(7));
empleado.put("NOMBRE", cstm.getString(8));
cstm.close();
this.setCode(1);
} catch (SQLException e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} catch (Exception e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} finally {
try {
cn.close();
} catch (Exception e) {
}
}
return empleado;
}
public List<Map<String, ?>> getEmpleadosByTags(String paterno, String materno, String nombre) {
List<Map<String, ?>> lista = null;
Connection cn = null;
try {
// Conexión
cn = AccesoDB.getConnection();
// Proceso
String sql = "{call ADM_EMPL_GETEMPLEADOS(?,?,?,?)}";
CallableStatement cstm = cn.prepareCall(sql);
cstm.setString(1, paterno);
cstm.setString(2, materno);
cstm.setString(3, nombre);
cstm.registerOutParameter(4, OracleTypes.CURSOR);
cstm.executeUpdate();
ResultSet rs = (ResultSet) cstm.getObject(4);
lista = JdbcUtil.rsToList(rs);
rs.close();
cstm.close();
this.setCode(1);
} catch (SQLException e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} catch (Exception e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} finally {
try {
cn.close();
} catch (Exception e) {
}
}
return lista;
}
public int editEmpleadoData(String CO_EMPL, String APE_PAT, String APE_MAT, String NOMBRE,
String CO_AREA, String CO_CARGO, String EST_EMPL) {
Connection cn = null;
try {
// Inicio: El objeto Connection
cn = AccesoDB.getConnection();
cn.setAutoCommit(true);
// Ejecutar SP
String sql = "{call ADM_EMPL_EDITDATA(?,?,?,?,?,?,?)}";
CallableStatement cstm = cn.prepareCall(sql);
cstm.setString(1, CO_EMPL);
cstm.setString(2, APE_PAT);
cstm.setString(3, APE_MAT);
cstm.setString(4, NOMBRE);
cstm.setString(5, CO_AREA);
cstm.setString(6, CO_CARGO);
cstm.setString(7, EST_EMPL);
cstm.executeUpdate();
cstm.close();
// Fin
this.setCode(1);
this.setMensaje("Empleado actualizado correctamente.");
} catch (SQLException e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} catch (Exception e) {
this.setCode(-1);
this.setMensaje(e.getMessage());
} finally {
try {
cn.close();
} catch (SQLException e) {
} catch (Exception e) {
}
}
return this.getCode();
}
}
|
package com.infor.models;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Email {
private String host;
private String socketPort;
private String socketClass;
private String auth;
private String port;
private String userName;
private String password;
private String senderAddress;
private String toAddress;
private String subject;
private String message;
private Message msg;
private Properties props;
public Email(){}
public Email(String host,String socketPort,String socketClass,String auth,String port,String username,String password){
this.host = host;
this.socketPort = socketPort;
this.socketClass = socketClass;
this.auth = auth;
this.port = port;
this.userName = username;
this.password = password;
setProps();
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getSocketPort() {
return socketPort;
}
public void setSocketPort(String socketPort) {
this.socketPort = socketPort;
}
public String getSocketClass() {
return socketClass;
}
public void setSocketClass(String socketClass) {
this.socketClass = socketClass;
}
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSenderAddress() {
return senderAddress;
}
public void setSenderAddress(String senderAddress) {
this.senderAddress = senderAddress;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Message getMsg() {
return msg;
}
public void setMsg(Message msg) {
this.msg = msg;
}
public Properties getProps() {
return props;
}
public void setProps(Properties props) {
this.props = props;
}
private void setProps(){
props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.socketFactory.port", socketPort);
props.put("mail.smtp.socketFactory.class", socketClass);
props.put("mail.smtp.auth", auth);
props.put("mail.smtp.port", port);
}
public void send(){
setProps();
Session session= Session.getDefaultInstance(getProps(),
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUserName(),getPassword());
}
});
try {
msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(getSenderAddress()));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(getToAddress()));
msg.setSubject(getSubject());
msg.setText(getMessage());
Transport.send(msg);
System.out.println("Done sending email");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
|
package com.dreamcatcher.factory;
import com.dreamcatcher.action.Action;
import com.dreamcatcher.plan.action.PlanDeleteAction;
import com.dreamcatcher.plan.action.PlanDislikeAction;
import com.dreamcatcher.plan.action.PlanGetLatLngAction;
import com.dreamcatcher.plan.action.PlanLikeAction;
import com.dreamcatcher.plan.action.PlanMakeAction;
import com.dreamcatcher.plan.action.PlanModifyAction;
import com.dreamcatcher.plan.action.PlanModifyViewAction;
import com.dreamcatcher.plan.action.RouteModifyEndAction;
import com.dreamcatcher.plan.action.RouteModifyStartAction;
import com.dreamcatcher.plan.action.PlanViewAction;
import com.dreamcatcher.plan.action.PlanAutoCompleteInMapAction;
import com.dreamcatcher.plan.action.PlanMapViewAction;
public class PlanActionFactory {
private static Action routeModifyStartAction;
private static Action routeModifyEndAction;
private static Action planMapViewAction;
private static Action planAutoCompleteInMapAction;
private static Action planMakeAction;
private static Action planViewAction;
private static Action planModifyAction;
private static Action planDeleteAction;
private static Action planModifyViewAction;
private static Action planLikeAction;
private static Action planDislikeAction;
private static Action planGetLatLngAction;
static{
routeModifyStartAction = new RouteModifyStartAction();
routeModifyEndAction = new RouteModifyEndAction();
planMapViewAction = new PlanMapViewAction();
planAutoCompleteInMapAction = new PlanAutoCompleteInMapAction();
planMakeAction = new PlanMakeAction();
planViewAction = new PlanViewAction();
planModifyAction = new PlanModifyAction();
planDeleteAction = new PlanDeleteAction();
planModifyViewAction = new PlanModifyViewAction();
planLikeAction= new PlanLikeAction();
planDislikeAction= new PlanDislikeAction();
planGetLatLngAction=new PlanGetLatLngAction();
}
public static Action getPlanGetLatLngAction() {
return planGetLatLngAction;
}
public static Action getplanLikeAction() {
return planLikeAction;
}
public static Action getplanDisLikeAction() {
return planDislikeAction;
}
public static Action getPlanViewAction() {
return planViewAction;
}
public static Action getRouteModifyStartAction() {
return routeModifyStartAction;
}
public static Action getRouteModifyEndAction() {
return routeModifyEndAction;
}
public static Action getPlanMakeAction() {
return planMakeAction;
}
public static Action getPlanModifyAction() {
return planModifyAction;
}
public static Action getPlanDeleteAction() {
return planDeleteAction;
}
public static Action getPlanModifyViewAction() {
return planModifyViewAction;
}
public static Action getPlanMapViewAction() {
return planMapViewAction;
}
public static Action getPlanAutoCompleteInMapAction() {
return planAutoCompleteInMapAction;
}
}
|
/**
* 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.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import javax.security.auth.login.LoginException;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.MRConfig;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.mapreduce.QueueState;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapreduce.SleepJob;
import org.apache.hadoop.security.UserGroupInformation;
import static org.apache.hadoop.mapred.DeprecatedQueueConfigurationParser.*;
import static org.apache.hadoop.mapred.QueueManagerTestUtils.*;
import static org.apache.hadoop.mapred.QueueManager.toFullPropertyName;
public class TestQueueManagerWithDeprecatedConf extends TestCase {
static final Log LOG = LogFactory.getLog(
TestQueueManagerWithDeprecatedConf.class);
String submitAcl = QueueACL.SUBMIT_JOB.getAclName();
String adminAcl = QueueACL.ADMINISTER_JOBS.getAclName();
public void testMultipleQueues() {
JobConf conf = new JobConf();
conf.set(DeprecatedQueueConfigurationParser.MAPRED_QUEUE_NAMES_KEY,
"q1,q2,Q3");
QueueManager qMgr = new QueueManager(conf);
Set<String> expQueues = new TreeSet<String>();
expQueues.add("q1");
expQueues.add("q2");
expQueues.add("Q3");
verifyQueues(expQueues, qMgr.getLeafQueueNames());
}
public void testSchedulerInfo() {
JobConf conf = new JobConf();
conf.set(DeprecatedQueueConfigurationParser.MAPRED_QUEUE_NAMES_KEY,
"qq1,qq2");
QueueManager qMgr = new QueueManager(conf);
qMgr.setSchedulerInfo("qq1", "queueInfoForqq1");
qMgr.setSchedulerInfo("qq2", "queueInfoForqq2");
assertEquals(qMgr.getSchedulerInfo("qq2"), "queueInfoForqq2");
assertEquals(qMgr.getSchedulerInfo("qq1"), "queueInfoForqq1");
}
public void testQueueManagerWithDeprecatedConf() throws IOException {
String queueConfigPath =
System.getProperty("test.build.extraconf", "build/test/extraconf");
File hadoopConfigFile = new File(queueConfigPath, "mapred-site.xml");
try {
// queue properties with which the cluster is started.
Properties hadoopConfProps = new Properties();
hadoopConfProps.put(DeprecatedQueueConfigurationParser.
MAPRED_QUEUE_NAMES_KEY, "default,q1,q2");
hadoopConfProps.put(MRConfig.MR_ACLS_ENABLED, "true");
UserGroupInformation ugi =
UserGroupInformation.createRemoteUser("unknownUser");
hadoopConfProps.put(toFullPropertyName(
"default", submitAcl), ugi.getUserName());
hadoopConfProps.put(toFullPropertyName(
"q1", submitAcl), "u1");
hadoopConfProps.put(toFullPropertyName(
"q2", submitAcl), "*");
hadoopConfProps.put(toFullPropertyName(
"default", adminAcl), ugi.getUserName());
hadoopConfProps.put(toFullPropertyName(
"q1", adminAcl), "u2");
hadoopConfProps.put(toFullPropertyName(
"q2", adminAcl), "*");
UtilsForTests.setUpConfigFile(hadoopConfProps, hadoopConfigFile);
Configuration conf = new JobConf();
conf.setBoolean(MRConfig.MR_ACLS_ENABLED, true);
QueueManager queueManager = new QueueManager(conf);
//Testing job submission access to queues.
assertTrue("User Job Submission failed.",
queueManager.hasAccess("default", QueueACL.
SUBMIT_JOB, ugi));
assertFalse("User Job Submission failed.",
queueManager.hasAccess("q1", QueueACL.
SUBMIT_JOB, ugi));
assertTrue("User Job Submission failed.",
queueManager.hasAccess("q2", QueueACL.
SUBMIT_JOB, ugi));
//Testing the administer-jobs acls
assertTrue("User Job Submission failed.",
queueManager.hasAccess("default",
QueueACL.ADMINISTER_JOBS, ugi));
assertFalse("User Job Submission failed.",
queueManager.hasAccess("q1", QueueACL.
ADMINISTER_JOBS, ugi));
assertTrue("User Job Submission failed.",
queueManager.hasAccess("q2", QueueACL.
ADMINISTER_JOBS, ugi));
} finally {
//Cleanup the configuration files in all cases
if(hadoopConfigFile.exists()) {
hadoopConfigFile.delete();
}
}
}
private void verifyQueues(Set<String> expectedQueues,
Set<String> actualQueues) {
assertEquals(expectedQueues.size(), actualQueues.size());
for (String queue : expectedQueues) {
assertTrue(actualQueues.contains(queue));
}
}
}
|
package com.oxycab.provider.ui.activity.change_password;
import com.oxycab.provider.base.MvpView;
public interface ChangePasswordIView extends MvpView {
void onSuccess(Object object);
void onError(Throwable e);
}
|
/**
* Created by jettc on 6/13/2017.
*/
public class FunctionExample {
// Function Prototype/Declaration
// Function Definition
// Function Calling
public void demo(){
System.out.println("I'm a default function.");
}
public void demo(int a ){
System.out.println("I'm a default function with one arg a = " + a);
}
public void demo(char ch ){
System.out.println("I'm a default function with one arg ch = " + ch);
}
public void demo(int a, char ch){
System.out.println("a = " + a + " ch = " + ch);
}
public static void main(String[] args){
FunctionExample fc = new FunctionExample();
fc.demo();
fc.demo(3);
fc.demo('a');
fc.demo(3, 'a');
}
}
|
package com.espendwise.manta.web.validator;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.validation.CodeValidationResult;
import com.espendwise.manta.util.validation.IntegerValidator;
import com.espendwise.manta.util.validation.TextValidator;
import com.espendwise.manta.util.validation.ValidationResult;
import com.espendwise.manta.util.validation.Validators;
import com.espendwise.manta.web.forms.DistributorFilterForm;
import com.espendwise.manta.web.resolver.SearchByIdErrorResolver;
import com.espendwise.manta.web.resolver.TextErrorWebResolver;
import com.espendwise.manta.web.util.WebErrors;
public class DistributorFilterFormValidator extends AbstractFormValidator {
public DistributorFilterFormValidator() {
super();
}
@Override
public ValidationResult validate(Object obj) {
DistributorFilterForm form = (DistributorFilterForm) obj;
WebErrors errors = new WebErrors();
if (Utility.isSet(form.getDistributorId())) {
IntegerValidator validator = Validators.getIntegerValidator();
CodeValidationResult vr = validator.validate(form.getDistributorId(), new SearchByIdErrorResolver("admin.global.filter.label.distributorId", null));
if (vr != null) {
errors.putErrors(vr.getResult());
}
}
if (Utility.isSet(form.getDistributorName())) {
TextValidator validator = Validators.getTextValidator(Constants.VALIDATION_FIELD_CRITERIA.SHORT_DESC_LENGTH);
CodeValidationResult vr = validator.validate(form.getDistributorName(), new TextErrorWebResolver("admin.global.filter.label.distributorName", null));
if (vr != null) {
errors.putErrors(vr.getResult());
}
}
return new MessageValidationResult(errors.get());
}
}
|
package com.tencent.mm.plugin.wxcredit.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class WalletWXCreditChangeAmountResultUI$1 implements OnMenuItemClickListener {
final /* synthetic */ WalletWXCreditChangeAmountResultUI qwP;
WalletWXCreditChangeAmountResultUI$1(WalletWXCreditChangeAmountResultUI walletWXCreditChangeAmountResultUI) {
this.qwP = walletWXCreditChangeAmountResultUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
this.qwP.cDK().a(this.qwP.mController.tml, 0, this.qwP.sy);
return true;
}
}
|
package mah.da357a.io;
import java.awt.image.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* IO class for reading and writing Megatron files
*
* @author Jesper Larsson & Albert Kaaman
*
*/
public class MegatronIO {
/** Magic start string to signify Megatron file format. */
private final static byte[] MAGIC = "mEgaMADNZ!".getBytes(StandardCharsets.US_ASCII);
@SuppressWarnings("serial")
public final static class InvalidMegatronFileException extends IOException { }
/**
* Writes an image to disk
* @param img Image to write
* @param outputFile File to write image to
* @throws IOException
* @return True if success
*/
public static boolean write(BufferedImage img, File outputFile) throws IOException {
int width = img.getWidth();
int height = img.getHeight();
int[] pxl = new int[3];
Raster imgRaster = img.getRaster();
try (OutputStream out = new FileOutputStream(outputFile)) {
// Write megatron header
out.write(MAGIC);
// Write width and length
write4bytes(width, out);
write4bytes(height, out);
// Write pixel data
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
imgRaster.getPixel(i, j, pxl);
out.write(pxl[0]);
out.write(pxl[1]);
out.write(pxl[2]);
}
}
}
return true;
}
/**
* Reads an image from file on disk
*
* @param inputFile File to read image from
* @return Image read from file
* @throws IOException
*/
public static BufferedImage read(File inputFile) throws IOException {
BufferedImage img = null;
try (InputStream in = new FileInputStream(inputFile)) {
// Check magic value.
for (int i = 0; i < MAGIC.length; i++) {
if (in.read() != MAGIC[i]) { throw new InvalidMegatronFileException(); }
}
// Read width and height
int width = read4bytes(in);
int height = read4bytes(in);
img = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
byte[] pxlBytes = new byte[3];
int[] pxl = new int[3];
WritableRaster imgRaster = img.getRaster();
// Read pixel data
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (in.read(pxlBytes) != 3) { throw new EOFException(); }
pxl[0] = pxlBytes[0];
pxl[1] = pxlBytes[1];
pxl[2] = pxlBytes[2];
imgRaster.setPixel(i, j, pxl);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return img;
}
/**
* Writes an int as 4 bytes, big endian.
*
* @param v Int to write
* @param out Stream to write int to
* @throws IOException
*/
private static void write4bytes(int v, OutputStream out) throws IOException {
out.write((v >>> 3*8));
out.write((v >>> 2*8) & 0xFF);
out.write((v >>> 1*8) & 0xFF);
out.write((v >>> 0*8) & 0xFF);
}
/**
* Reads an int as 4 bytes, big endian.
*
* @param in Stream to read from
* @return Int read from stream
* @throws IOException
*/
private static int read4bytes(InputStream in) throws IOException {
int b, v = 0;
/*
b = in.read(); if (b < 0) { throw new EOFException(); }
v = b << 3*8;
b = in.read(); if (b < 0) { throw new EOFException(); }
v |= b << 2*8;
b = in.read(); if (b < 0) { throw new EOFException(); }
v |= b << 1*8;
b = in.read(); if (b < 0) { throw new EOFException(); }
v |= b;
*/
for (int i = 3; i >= 0; i--) {
b = in.read();
if (b < 0) { throw new EOFException(); }
v |= b << i*8;
}
return v;
}
}
|
package online;
import Util.R;
import com.restfb.*;
import com.restfb.types.FacebookType;
import com.restfb.types.User;
import org.jetbrains.annotations.Nullable;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* using restfb library for interact with facebook api
* Created by cuong on 11/21/2015.
*/
public class OnlineGameService {
private FBPlayer currentPlayer;
private StringBuffer redirectUrl;
private FacebookClient client;
public OnlineGameService() {
currentPlayer = new FBPlayer();
redirectUrl = new StringBuffer();
}
/**
* Thread browser for user to login and authorize
*/
private final Runnable doLogin = new Runnable() {
@Override
public void run() {
Browser browser = new Browser(redirectUrl);
browser.setVisible(true);
browser.loadURL(String.format(R.AUTHORIZATE_URL, R.APP_ID, R.REDIRECT_URL));
}
};
/**
* login thread execution
*/
public void login() throws IllegalArgumentException {
Thread t = new Thread() {
@Override
public void run() {
SwingUtilities.invokeLater(doLogin);
synchronized (redirectUrl) {
try { redirectUrl.wait();}
catch (InterruptedException e) { e.printStackTrace(); }
}
}
};
t.start();
try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); }
// after finish login thread, get user access token and initializeClient
try {
currentPlayer.setAccessToken(getAccessTokenFromUrl(redirectUrl));
} catch (IllegalArgumentException e) {
throw e;
}
}
/**
* initialize client connection to facebook api
* after getting user's access token
*/
public void initializeClient() {
client = new DefaultFacebookClient(currentPlayer.getAccessToken());
}
/**
* get name and the Facebook ID of player
*/
public FBPlayer getCurrentPlayer() throws IllegalArgumentException {
System.out.println("Load current player information...");
try {
login();
} catch (IllegalArgumentException e) {
throw e;
}
initializeClient();
User user = client.fetchObject("me", User.class);
currentPlayer.setName(user.getName());
currentPlayer.setFbID(Long.parseLong(user.getId()));
currentPlayer.setPfPicture(getProfileImage(currentPlayer.getFbID()));
return currentPlayer;
}
/**
* publish a photo to user wall
* @param path path to the photo file
* @param caption caption of photo which to publish
*/
public void publishPhoto(String path, String caption) {
FacebookType publishPhotoResponse = client.publish("me/photos", FacebookType.class,
BinaryAttachment.with(path.substring(path.lastIndexOf("//")+1), toByteArray(path)),
Parameter.with("message", caption));
System.out.println("Event publishing ID: " + publishPhotoResponse);
}
/**
* get access token which Facebook response
* and put in the redirect redirectUrl (our server)
* @param url the whole redirect redirectUrl
* @return access token in redirectUrl
*/
private String getAccessTokenFromUrl(StringBuffer url) throws IllegalArgumentException {
int start = url.indexOf("access_token=") + "access_token=".length();
int end = url.indexOf("&expires_in");
if (start == 12) { //not found "access_token" in redirectUrl
throw new IllegalArgumentException("Wrong redirect url format for getting access token");
}
return url.substring(start, end);
}
/**
* convert file to byte array, for publishing photo
* @param fileName path to file
* @return byte array of input file
*/
@Nullable
public static byte[] toByteArray(String fileName) {
File file = new File(fileName);
byte[] data = new byte[(int)file.length()];
FileInputStream stream = null;
try {
stream = new FileInputStream(file);
stream.read(data);
stream.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return data;
}
/**
* get best player information from tetris server
* use Thread for executing
* @return bestPlayer the best player which is fetched
*/
public FBPlayer getBestPlayer() {
FBPlayer bestPlayer = new FBPlayer();
GetBestPlayerThread t = new GetBestPlayerThread(bestPlayer);
t.start();
synchronized (bestPlayer) {
try {
System.out.println("Loading best player information...");
bestPlayer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return bestPlayer;
}
public void postBestPlayer(FBPlayer newBestPlayer) {
PostBestPlayerThread t = new PostBestPlayerThread(newBestPlayer);
t.start();
synchronized (newBestPlayer) {
System.out.println("Posting best player information to server...");
try {
newBestPlayer.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void publishPost(String message) {
FacebookType publishMessageResponse =
client.publish("me/feed", FacebookType.class,
Parameter.with("message", message));
System.out.println("Published message ID: " + publishMessageResponse.getId());
}
public static Image getProfileImage(long fbid) {
try {
URL url = new URL(String.format(R.PROFILE_PICTURE_URL, fbid));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
String pfPicUrl = con.getHeaderField("Location"); //get redirect url
return ImageIO.read(new URL(pfPicUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/*public static void main(String args[]) {
OnlineGameService service = new OnlineGameService();
service.postBestPlayer(new FBPlayer("Cuong", (long) 12412412, "fafqwf", 20));
getProfileImage(100010325041187l);
service.client = new DefaultFacebookClient("CAAHv9TAOA7cBAMh7oKzauEu8BxLntS3yCE1cyzKGkfDbVEIbR7ARFbSFMhmKy1VhGEkZBWjeCUkP5aMt26a9wrOMskmBsO2p9ZC0xCZChgrTQp4YYzab7K0WRuZCvGZCZBCewkFeV9DQRjbRu8ZBXTDwvYqDR8a6bbPahT6lrlIMhEUUgaMHKnug3Fsj02IJocNvD2ewS712gZDZD");
service.publishPhoto("./img/demo.png", "Bùi Quang Cường is now leading the top" +
" board in our Tetris game\n" +
"Kick him by replacing your name in our honor board :)\n" +
"Join game here: http://www.dailyheroes.ga/tetris/");
}*/
}
|
package commandline.command;
import commandline.exception.ArgumentNullException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
public class CommandList implements Iterable<Command> {
@NotNull
private final HashMap<String, Command> commands;
public CommandList() {
super();
this.commands = new HashMap<>(50);
}
@NotNull
private HashMap<String, Command> getCommands() {
return this.commands;
}
@NotNull
public Collection<Command> getCollection() {
return Collections.unmodifiableCollection(getCommands().values());
}
@Nullable
public Command get(@NotNull String commandName) {
if (commandName == null) {
throw new ArgumentNullException();
}
if (commandName.trim().isEmpty()) {
throw new IllegalArgumentException(
"The command could not been retrieved, because the passed command name doesn't contain any character.");
}
return getCommands().get(commandName.trim());
}
public void add(@NotNull Command command) {
if (command == null) {
throw new ArgumentNullException();
}
getCommands().put(command.getName(), command);
}
public void addAll(@NotNull Collection<Command> commands) {
if (commands == null) {
throw new ArgumentNullException();
}
for (Command command : commands) {
add(command);
}
}
@Nullable
public Command remove(@NotNull String commandName) {
if (commandName == null) {
throw new ArgumentNullException();
}
if (commandName.trim().isEmpty()) {
throw new IllegalArgumentException(
"The command could not been removed, because the passed command name doesn't contain any character.");
}
return getCommands().remove(commandName.trim());
}
@Nullable
public Command remove(@NotNull Command command) {
if (command == null) {
throw new ArgumentNullException();
}
return getCommands().remove(command.getName());
}
public int getSize() {
return getCommands().size();
}
public boolean isEmpty() {
return getCommands().isEmpty();
}
public boolean contains(@NotNull String commandName) {
if (commandName == null) {
throw new ArgumentNullException();
}
if (commandName.trim().isEmpty()) {
throw new IllegalArgumentException(
"The command existence could not been tested, because the passed command name doesn't contain any character.");
}
return getCommands().containsKey(commandName.trim());
}
public boolean contains(@NotNull Command command) {
if (command == null) {
throw new ArgumentNullException();
}
return getCommands().containsKey(command.getName());
}
public void clear() {
getCommands().clear();
}
@NotNull
@Override
public String toString() {
return "CommandList{" +
"commands=" + this.commands +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CommandList)) {
return false;
}
CommandList that = (CommandList) o;
if (!this.commands.equals(that.commands)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return this.commands.hashCode();
}
@NotNull
@Override
public Iterator<Command> iterator() {
return getCommands().values().iterator();
}
}
|
package script.groovy.servlets;
import groovy.lang.GroovyObject;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import script.groovy.runtime.GroovyRuntime;
public abstract class GroovyServlet implements GroovyObject{
public static final String DELETE = "DELETE";
public static final String GET = "GET";
public static final String PUT = "PUT";
public static final String POST = "POST";
public static final String HEAD = "HEAD";
public static final String OPTIONS = "OPTIONS";
public static final String TRACE = "TRACE";
protected GroovyRuntime groovyRuntime;
public GroovyRuntime getGroovyRuntime() {
return groovyRuntime;
}
public void setGroovyRuntime(GroovyRuntime groovyRuntime) {
this.groovyRuntime = groovyRuntime;
}
}
|
package com.hk.xia.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author wang.yubin
* @date 2019/9/24
* @description 纯Java配置SpringMVC的控制器测试
*/
@Controller
public class ConfigController {
@RequestMapping("/start")
public String start(){
System.out.println("purity Java Config Success.....");
return "start";
}
}
|
package com.tencent.mm.plugin.clean.c;
class f$2 implements Runnable {
final /* synthetic */ f hRm;
final /* synthetic */ long hRn;
f$2(f fVar, long j) {
this.hRm = fVar;
this.hRn = j;
}
public final void run() {
if (f.a(this.hRm) != null) {
f.a(this.hRm).ck(this.hRn);
}
}
}
|
package com.example.test.ndk;
/**
* Created by Guo Shaobing on 2016/10/17.
*/
public class NdkJniUtils {
static {
System.loadLibrary("TestJniLibName"); //defaultConfig.ndk.moduleName
}
public native String getCLanguageString();
}
|
package com.cooksys.teamOneSocialMedia.dtos;
import java.util.List;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@Data
public class ContextDto {
public TweetResponseDto target;
public List<TweetResponseDto> before;
public List<TweetResponseDto> after;
}
|
package com.hit.neuruimall.service.impl;
import com.hit.neuruimall.service.IImgService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class ImgServiceImplTest {
@Autowired
IImgService imgService;
@Test
void getImgUrl() {
System.out.println(imgService.getImgUrl());
}
@Test
void uploadImg() {
}
}
|
package com.zitiger.plugin.xdkt.tomap.action;
import com.zitiger.plugin.xdkt.tomap.generator.AbstractTransformationGenerator;
import com.zitiger.plugin.xdkt.tomap.generator.impl.GuavaToListGenerator;
/**
* @author zitiger
*/
public class GuavaToListGeneratorAction extends TransformationGeneratorAction {
@Override
protected AbstractTransformationGenerator getGenerator() {
return new GuavaToListGenerator();
}
}
|
package com.wlc.ds.sort;
/**
* 选择排序<br>
* 每次选择最小的元素
* 时间复杂度: 平均情况与最差情况都是O(n^2)<br>
* 空间复杂度: O(1)
*
* @author lanchun
*
*/
public class SelectionSort implements ISort {
public void sort(int[] array) {
for(int i = 0;i < array.length-1;i++){
int min = array[i];
int indexOfMin=i;
for(int j = i+1;j < array.length;j++){
if(min > array[j]){
min = array[j];
indexOfMin=j;
}
}
if(indexOfMin != i){
array[indexOfMin] = array[i];
array[i] = min;
}
}
}
}
|
package com.example.cbt.jsondemo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by CBT on 18-07-2017.
*/
public class PlayerAdapter extends RecyclerView.Adapter {
Context ctx;
public PlayerAdapter(Context ctx)
{
this.ctx=ctx;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
//Converting row.xml to java object
View v1=LayoutInflater.from(ctx).inflate(R.layout.row,null,false);
PlayerViewHolder pv=new PlayerViewHolder(v1);
return pv;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 20;
}
class PlayerViewHolder extends RecyclerView.ViewHolder
{
ImageView playerImage;
TextView playerName,playerRuns;
public PlayerViewHolder(View itemView) {
super(itemView);
playerImage=(ImageView)itemView.findViewById(R.id.row_playerimg_iv);
playerName=(TextView)itemView.findViewById(R.id.row_playername_tv);
playerRuns=(TextView)itemView.findViewById(R.id.row_playerruns_tv);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.