text
stringlengths
10
2.72M
package firstTest; import com.company.page.pages.BootstrapAlertMessagesPage; import org.junit.Test; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Before; import org.junit.AfterClass; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class TestBootstrapAlertMessages { private static BootstrapAlertMessagesPage webPage; private static final WebDriver webDriver = new ChromeDriver(); @BeforeClass public static void runPage() { webPage = new BootstrapAlertMessagesPage(webDriver); webPage.openPage(); } @Before public void waitForNext() throws InterruptedException { Thread.sleep(2000); } @Test public void autoSuccessMessage() throws InterruptedException { webPage.clickOnAutoSuccessMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowAutoSuccessMessage())); Thread.sleep(6000); Assert.assertFalse(webPage.isActive(webPage.getShowAutoSuccessMessage())); } @Test public void normalSuccessMessage() { webPage.clickOnNormalSuccessMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowNormalSuccessMessage())); webPage.closeNormalMessage(); } @Test public void autoWarningMessage() throws InterruptedException { webPage.clickOnAutoWarningMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowAutoWarningMessage())); Thread.sleep(6000); Assert.assertFalse(webPage.isActive(webPage.getShowAutoWarningMessage())); } @Test public void normalWarningMessage() { webPage.clickOnNormalWarningMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowNormalWarningMessage())); webPage.closeWarningMessage(); } @Test public void autoDangerMessage() throws InterruptedException { webPage.clickOnAutoDangerMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowAutoDangerMessage())); Thread.sleep(6000); Assert.assertFalse(webPage.isActive(webPage.getShowAutoDangerMessage())); } @Test public void normalDangerMessage() { webPage.clickOnNormalDangerMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowNormalDangerMessage())); webPage.closeDangerMessage(); } @Test public void autoInfoMessage() throws InterruptedException { webPage.clickOnAutoInfoMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowAutoInfoMessage())); Thread.sleep(7000); Assert.assertFalse(webPage.isActive(webPage.getShowAutoInfoMessage())); } @Test public void normalInfoMessage() throws InterruptedException { webPage.clickOnNormalInfoMessageButton(); Assert.assertTrue(webPage.isActive(webPage.getShowNormalInfoMessage())); Thread.sleep(1000); webPage.closeInfoMessage(); } @AfterClass public static void closePage() { webPage.closePage(); } }
package bartender.bardatabase; import java.util.HashMap; import bartender.protocol.EchoProtocol; public class Table { public String TableNumber=""; private HashMap<String, EchoProtocol> Users_=new HashMap<String, EchoProtocol>(); public boolean free=true; public Table(String TableNumber){ this.TableNumber=TableNumber; } public void join (EchoProtocol incoming){ Users_.put(incoming.myName, incoming); } }
package com.example.spotifyauthentication.Activities; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ProgressBar; import android.widget.TextView; import com.example.spotifyauthentication.R; import com.spotify.sdk.android.authentication.AuthenticationClient; import com.spotify.sdk.android.authentication.AuthenticationRequest; import com.spotify.sdk.android.authentication.AuthenticationResponse; import java.util.Objects; public class AuthenticationActivity extends AppCompatActivity { // declare constants public static final String CLIENT_ID = "cd58168e38d84c43b7433d471d1c5942"; public static final int AUTH_TOKEN_REQUEST_CODE = 0x10; private String mAccessToken; // declare UI widgets private CheckBox checkbox; private Button buttonAuthenticate; private ProgressBar progressBar; private TextView progressMessage; private Toolbar toolbar; // key for access token private final String TOKEN_KEY = "token"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_authentication); // add custom toolbar to the activity toolbar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false); // instantiate agreement checkbox, authentication button, and status bar/message checkbox = (CheckBox) findViewById(R.id.checkbox); buttonAuthenticate = (Button) findViewById(R.id.authentication_button); progressBar = (ProgressBar) findViewById(R.id.progressBar); progressMessage = (TextView) findViewById(R.id.progressMessage); // by default, button state is off because the user hasn't clicked the checkbox buttonAuthenticate.setVisibility(View.INVISIBLE); // by default, progress bar/message is invisible because the user hasn't clicked authenticate progressBar.setVisibility(ProgressBar.INVISIBLE); progressMessage.setVisibility(TextView.INVISIBLE); // create click listener for checkbox state changes checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // checks checkbox state, used to toggle authentication button state on and off public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // if user has agreed to authentication statement, enable authentication button if (isChecked) { buttonAuthenticate.setVisibility(View.VISIBLE); } // if user has not agreed to authentication statement, disable authentication button else { buttonAuthenticate.setVisibility(View.INVISIBLE);; } } }); // create click listener for authentication button clicks buttonAuthenticate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // request access token requestToken(); // run a background task in webview, display progress bar and progress message progressBar.setVisibility(ProgressBar.VISIBLE); progressMessage.setVisibility(TextView.VISIBLE); } }); } @Override protected void onPause(){ super.onPause(); } public void requestToken() { final AuthenticationRequest request = getAuthenticationRequest(AuthenticationResponse.Type.TOKEN); AuthenticationClient.openLoginActivity(this, AUTH_TOKEN_REQUEST_CODE, request); } private AuthenticationRequest getAuthenticationRequest(AuthenticationResponse.Type type) { return new AuthenticationRequest.Builder(CLIENT_ID, type, getRedirectUri().toString()) .setShowDialog(false) .setScopes(new String[]{"user-read-email", "user-top-read"}) .setCampaign("your-campaign-token") .build(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); final AuthenticationResponse response = AuthenticationClient.getResponse(resultCode, data); // get access token from authentication client response if (AUTH_TOKEN_REQUEST_CODE == requestCode) { mAccessToken = response.getAccessToken(); // if access token is not received, show snackbar message and exit if (mAccessToken == null) { final Snackbar snackbar = Snackbar.make(findViewById(R.id.activity_main), R.string.warning_need_token, Snackbar.LENGTH_LONG); snackbar.getView().setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)); snackbar.show(); return; } } // store access token in shared preferences and navigate to MostPopularActivity setDefaults(TOKEN_KEY, mAccessToken, this); Intent intent = new Intent(getApplicationContext(), MostPopularActivity.class); startActivity(intent); finish(); } // set default shared preferences for app public static void setDefaults(String key, String value, Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = preferences.edit(); editor.putString(key, value); editor.apply(); } // get redirect uri using redirect scheme and host private Uri getRedirectUri() { return new Uri.Builder() .scheme(getString(R.string.com_spotify_sdk_redirect_scheme)) .authority(getString(R.string.com_spotify_sdk_redirect_host)) .build(); } }
/* * 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 Entidades; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * * @author rosemary */ public class entRecepcion { private int id_recepcion; private int id_dia_recepcion; private entDireccionLlegada objDireccionLlegada; private entChofer objChofer; private String num_guia; private String placa; private String modelo; private Date fecha_recepcion; private String precinto; private int estado; private String usuario_responsable; private Date fecha_modificacion; private List<entDetalleRecepcion> lista; private List<entCategoria> listaCategoria; private List<entJaba> listaJaba; private List<entParihuela> listaParihuela; public entRecepcion (){ this.lista=new ArrayList<entDetalleRecepcion>(); } public int getId_dia_recepcion() { return id_dia_recepcion; } public void setId_dia_recepcion(int id_dia_recepcion) { this.id_dia_recepcion = id_dia_recepcion; } public Date getFecha_recepcion() { return fecha_recepcion; } public void setFecha_recepcion(Date fecha_recepcion) { this.fecha_recepcion = fecha_recepcion; } public String getPrecinto() { return precinto; } public void setPrecinto(String precinto) { this.precinto = precinto; } public int getId_recepcion() { return id_recepcion; } public int getEstado() { return estado; } public void setEstado(int estado) { this.estado = estado; } public String getUsuario_responsable() { return usuario_responsable; } public void setUsuario_responsable(String usuario_responsable) { this.usuario_responsable = usuario_responsable; } public Date getFecha_modificacion() { return fecha_modificacion; } public void setFecha_modificacion(Date fecha_modificacion) { this.fecha_modificacion = fecha_modificacion; } public void setId_recepcion(int id_recepcion) { this.id_recepcion = id_recepcion; } public entDireccionLlegada getObjDireccionLlegada() { return objDireccionLlegada; } public void setObjDireccionLlegada(entDireccionLlegada objDireccionLlegada) { this.objDireccionLlegada = objDireccionLlegada; } public entChofer getObjChofer() { return objChofer; } public void setObjChofer(entChofer objChofer) { this.objChofer = objChofer; } public String getNum_guia() { return num_guia; } public void setNum_guia(String num_guia) { this.num_guia = num_guia; } public String getPlaca() { return placa; } public void setPlaca(String placa) { this.placa = placa; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public List<entDetalleRecepcion> getLista() { return lista; } public void setLista(List<entDetalleRecepcion> lista) { this.lista = lista; } public List<entCategoria> getListaCategoria() { return listaCategoria; } public void setListaCategoria(List<entCategoria> listaCategoria) { this.listaCategoria = listaCategoria; } public List<entJaba> getListaJaba() { return listaJaba; } public void setListaJaba(List<entJaba> listaJaba) { this.listaJaba = listaJaba; } public List<entParihuela> getListaParihuela() { return listaParihuela; } public void setListaParihuela(List<entParihuela> listaParihuela) { this.listaParihuela = listaParihuela; } }
package LC0_200.LC100_150; import LeetCodeUtils.MyMatrix; import LeetCodeUtils.MyPrint; import org.junit.Test; import java.util.HashMap; public class LC149_Max_Points_On_A_Line { @Test public void test() { System.out.println(maxPoints(MyMatrix. IntMatrixAdapter("[[4,0],[4,1],[4,5]]",3, 2))); } public int maxPoints(int[][] points) { HashMap<Double, Integer> map = new HashMap<>(); int max_count = 0, same = 1, same_y = 1; for (int i = 0; i < points.length; ++i) { same = 1; same_y = 1; for (int j = i + 1; j < points.length; ++j) { if (points[i][1] == points[j][1]) { ++same_y; // y is same, find the number of nodes that on the same y if (points[i][0] == points[j][0]) ++same; } else { Double dx = Double.valueOf(points[i][0] - points[j][0]), dy = Double.valueOf(points[i][1] - points[j][1]); if (map.containsKey(dx / dy)) map.put(dx / dy, map.get(dx / dy) + 1); else map.put(dx / dy, 1); } } max_count = Math.max(max_count, same_y); for (Integer d : map.values()) max_count = Math.max(max_count, same + d); map.clear(); } return max_count; } }
package it.polimi.ingsw.GC_21.VIEW; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.SocketException; import it.polimi.ingsw.GC_21.CLIENT.MessageToClient; public class SocketAdapter implements AdapterConnection{ private RemoteView remoteView; private Socket socket; private ObjectOutputStream oos; private ObjectInputStream ois; public SocketAdapter(Socket socket, RemoteView remoteView) throws IOException { this.socket = socket; ois = new ObjectInputStream(socket.getInputStream()); oos = new ObjectOutputStream(socket.getOutputStream()); this.remoteView = remoteView; } public SocketAdapter(Socket socket) throws IOException { this.socket = socket; ois = new ObjectInputStream(socket.getInputStream()); oos = new ObjectOutputStream(socket.getOutputStream()); } @Override public void close() throws IOException { try { socket.close(); } catch(SocketException e){ return; } } @Override public void sendObject(MessageToClient message) { try { oos.writeObject(message); oos.flush(); oos.reset(); } catch (IOException e) { return; } } @Override public InputForm receiveObject() { try { InputForm inputForm = (InputForm) ois.readObject(); if (inputForm == null) { return receiveObject(); } return inputForm; } catch (IOException | ClassNotFoundException e) { if (!remoteView.isDisconnected()){ remoteView.setDisconnected(true); MessageToClient disconnectionMessage = new MessageToClient(true, remoteView.getUsername() + " disconnected!"); if (remoteView.getGame()!=null) { remoteView.getGame().notifyBroadcast(disconnectionMessage); } } return new PassInput();//if client is disconnected, do a default pass action } catch (Exception e2) { return new InputForm(); } } public Socket getSocket() { return socket; } public void setSocket(Socket socket) { this.socket = socket; } public RemoteView getRemoteView() { return remoteView; } public void setRemoteView(RemoteView remoteView) { this.remoteView = remoteView; } }
package com.mygdx.factory; import level.AmountMonster; import level.LevelInfo; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.utils.IntMap; import com.badlogic.gdx.utils.Json; import com.mygdx.jsonHelper.IntMapSerializer; public class LevelInfoFactory { private static IntMap<LevelInfo> levelInfoMap = new IntMap<LevelInfo>() ; public LevelInfoFactory(){} @SuppressWarnings({ "unchecked" }) public static void instantiate(){ Json json = new Json(); json.addClassTag("levelInfo", LevelInfo.class); json.setElementType(LevelInfo.class, "monsterArray", AmountMonster.class);//Array Einträge von monsterArray sind vom Typ AmountMonster json.setSerializer(IntMap.class, new IntMapSerializer()); levelInfoMap = json.fromJson(IntMap.class,Gdx.files.internal("json/LevelInformation.json")); } public static LevelInfo getLevelInfo(int level){ return levelInfoMap.get(level); } }
package lowOfDeteter.instance; import java.util.Random; /** * @Author:Jack * @Date: 2021/8/21 - 22:35 * @Description: lowOfDeteter.instance * @Version: 1.0 */ public class Wizard { private Random random = new Random(System.currentTimeMillis()); private int first(){ System.out.println("first methos"); return random.nextInt(100); } private int second(){ System.out.println("second methos"); return random.nextInt(100); } private int third(){ System.out.println("third methos"); return random.nextInt(100); } public void install(){ int first = this.first(); if (first > 50){ int second = this.second(); if (second > 50){ int third = this.third(); if (third > 50){ System.out.println("安装成功"); } } } } }
package onlinerealestateproject.util; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Connection; import java.sql.SQLException; import onlinerealestateproject.datasource.DataMapperException; import onlinerealestateproject.domain.Administrator; /** * @author Junjie Huang * */ public class ToolDelete { public static void main(String[] argv) { System.out.println("-------- MySQL JDBC Connection Testing ------------"); deleteOrder(1,"inspection_order"); } public static boolean deleteOrder(int oid, String tablename) throws DataMapperException{ try { String statement = "delete from "+tablename+ " where oid=?"; MySQLConnection.getSingleMySQLConnection().establishDBConnection(); PreparedStatement dbStatement = MySQLConnection.getSingleMySQLConnection().getConnection().prepareStatement(statement); dbStatement.setInt(1, oid); dbStatement.executeUpdate(); MySQLConnection.getSingleMySQLConnection().closeConnection(); return true; } catch (SQLException e) { e.printStackTrace(); //throw new DataMapperException( e); return false; } } public static boolean deleteApartment(int apid) throws DataMapperException{ try { String statement = "delete from inspection_order where apid=?"; MySQLConnection.getSingleMySQLConnection().establishDBConnection(); PreparedStatement dbStatement = MySQLConnection.getSingleMySQLConnection().getConnection().prepareStatement(statement); dbStatement.setInt(1, apid); dbStatement.executeUpdate(); MySQLConnection.getSingleMySQLConnection().closeConnection(); String statement_1 = "delete from apartment where apid=?"; MySQLConnection.getSingleMySQLConnection().establishDBConnection(); PreparedStatement dbStatement_1 = MySQLConnection.getSingleMySQLConnection().getConnection().prepareStatement(statement_1); dbStatement_1.setInt(1, apid); dbStatement_1.executeUpdate(); MySQLConnection.getSingleMySQLConnection().closeConnection(); return true; } catch (SQLException e) { e.printStackTrace(); //throw new DataMapperException( e); return false; } } public static boolean delete(int id, String tablename) throws DataMapperException { // TODO Auto-generated method stub try { String statement = "delete from "+tablename+ " where id=?"; MySQLConnection.getSingleMySQLConnection().establishDBConnection(); PreparedStatement dbStatement = MySQLConnection.getSingleMySQLConnection().getConnection().prepareStatement(statement); dbStatement.setInt(1, id); dbStatement.executeUpdate(); MySQLConnection.getSingleMySQLConnection().closeConnection(); return true; } catch (SQLException e) { e.printStackTrace(); //throw new DataMapperException( e); return false; } } }
/******************************************************************************* * Copyright 2021 Danny Kunz * * 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.omnaest.genomics.ensembl.domain; import java.util.Arrays; import java.util.Optional; import org.apache.commons.lang3.StringUtils; /** * <a href="https://m.ensembl.org/info/genome/variation/prediction/predicted_data.html">Ensembl documentation</a> * * @author omnaest */ public enum VariantConsequence { MISSENSE("missense_variant", VariantSeverity.MEDIUM), PROTEIN_ALTERING_VARIANT("protein_altering_variant", VariantSeverity.MEDIUM), _3_PRIME_UTR("3_prime_UTR_variant", VariantSeverity.LOW), _5_PRIME_UTR("5_prime_UTR_variant", VariantSeverity.LOW), INTRON("intron_variant", VariantSeverity.LOW), STOP_GAINED("stop_gained", VariantSeverity.HIGH), START_LOST("start_lost", VariantSeverity.HIGH), STOP_LOST("stop_lost", VariantSeverity.HIGH), FRAME_SHIFT_VARIANT("frameshift_variant", VariantSeverity.HIGH), INFRAME_INSERTION("inframe_insertion", VariantSeverity.MEDIUM), INFRAME_DELETION("inframe_deletion", VariantSeverity.MEDIUM), REGULATORY_REGION("regulatory_region_variant", VariantSeverity.HIGH), REGULATORY_REGION_ABLATION("regulatory_region_ablation", VariantSeverity.HIGH), TRANSCRIPTION_FACTOR_BINDING_SITE("TF_binding_site_variant", VariantSeverity.HIGH), TRANSCRIPT_ABLATION("transcript_ablation", VariantSeverity.HIGH), TRANSCRIPT_AMPLIFICATION("transcript_amplification", VariantSeverity.HIGH), SPLICE_ACCEPTOR_VARIANT("splice_acceptor_variant", VariantSeverity.HIGH), UPSTREAM_GENE("upstream_gene_variant", VariantSeverity.LOW), DOWNSTREAM_GENE("downstream_gene_variant", VariantSeverity.LOW), SYNONYMOUS("synonymous_variant", VariantSeverity.NONE), UNKNOWN("", VariantSeverity.LOW); private String matchStr; private VariantSeverity severity; private VariantConsequence(String matchStr, VariantSeverity severity) { this.matchStr = matchStr; this.severity = severity; } /** * Returns true, if the raw input from the rest api matches the current consequence * * @param input * @return */ public boolean matches(String input) { return StringUtils.equalsIgnoreCase(input, this.matchStr); } public VariantSeverity getSeverity() { return this.severity; } public String getMatchStr() { return this.matchStr; } public static Optional<VariantConsequence> of(String matchStr) { return Arrays.asList(values()) .stream() .filter(consequence -> consequence.matches(matchStr)) .findFirst(); } }
package com.pkjiao.friends.mm.dialog; import com.pkjiao.friends.mm.R; import android.app.Dialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; public class ExitAppDialog extends Dialog implements android.view.View.OnClickListener { private Context mContext; private Button mCancelBtn; private Button mConfirmBtn; private OnConfirmBtnClickListener mConfirmClickistener; public ExitAppDialog(Context context) { this(context, R.style.TranslucentDialog); } private ExitAppDialog(Context context, int style) { super(context, style); this.mContext = context; initView(); } private void initView() { LayoutInflater inflater = LayoutInflater.from(mContext); View view = inflater.inflate(R.layout.dialog_exit_app_layout, null); setContentView(view); mCancelBtn = (Button) view.findViewById(R.id.exit_app_confirm_btn); mConfirmBtn = (Button) view.findViewById(R.id.exit_app_cancel_btn); mCancelBtn.setOnClickListener(this); mConfirmBtn.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.exit_app_cancel_btn: this.dismiss(); break; case R.id.exit_app_confirm_btn: if (mConfirmClickistener != null) { mConfirmClickistener.onConfirmBtnClick(); } break; } } public void setOnConfirmBtnClickListener(OnConfirmBtnClickListener listener) { this.mConfirmClickistener = listener; } public interface OnConfirmBtnClickListener { public void onConfirmBtnClick(); } @Override public void show() { super.show(); } @Override public void dismiss() { super.dismiss(); } }
package com.kevinkuai.worm; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import com.kevinkuai.framework.FileIO; public class Settings { public static boolean soundEnabled = true; public static int[] highscores = new int[]{100,80,50,30,10}; public static void load(FileIO files){ BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( files.readFile(".worm"))); soundEnabled = Boolean.parseBoolean(in.readLine()); for (int i = 0; i < 5; i++){ highscores[i] = Integer.parseInt(in.readLine()); } } catch (IOException e) { // TODO Auto-generated catch block }catch (NumberFormatException e){ }finally{ try { in.close(); } catch (IOException e) { } } } public static void save(FileIO files){ BufferedWriter out = null; try { out = new BufferedWriter (new OutputStreamWriter( files.writeFile(".worm"))); out.write(Boolean.toString(soundEnabled)); out.write("\n"); for (int i=0; i<5; i++){ out.write(Integer.toString(highscores[i])); out.write("\n"); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if (out!=null) try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block } } } public static void addScore(int score){ for (int i=0; i<5; i++){ if (highscores[i]<score){ for (int j=4; j>i; j--){ highscores[j]=highscores[j-1]; } highscores[i]=score; break; } } } }
package com.fleet.batch.config; import com.fleet.batch.entity.User; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.core.launch.support.SimpleJobLauncher; import org.springframework.batch.core.repository.JobRepository; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider; import org.springframework.batch.item.database.JdbcBatchItemWriter; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper; import org.springframework.batch.item.file.mapping.DefaultLineMapper; import org.springframework.batch.item.file.transform.DelimitedLineTokenizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import javax.annotation.Resource; import javax.sql.DataSource; @Configuration @EnableBatchProcessing public class CsvBatchConfig { @Resource private DataSource dataSource; @Resource private JobRepository jobRepository; /** * simpleJobLauncher bean */ @Bean public SimpleJobLauncher simpleJobLauncher() { SimpleJobLauncher simpleJobLauncher = new SimpleJobLauncher(); // 设置 jobRepository simpleJobLauncher.setJobRepository(jobRepository); return simpleJobLauncher; } /** * job bean */ @Bean public Job job(JobBuilderFactory jobs, Step step) { return jobs.get("csv_job") .incrementer(new RunIdIncrementer()) .flow(step) .end() .listener(csvJobExecutionListener()) .build(); } /** * 注册 job 监听器 */ @Bean public CsvJobExecutionListener csvJobExecutionListener() { return new CsvJobExecutionListener(); } /** * step bean 步骤包括 ItemReader->ItemProcessor->ItemWriter 即读取数据->处理校验数据->写入数据 */ @Bean public Step step(StepBuilderFactory stepBuilderFactory, ItemReader<User> reader, ItemProcessor<User, User> processor, ItemWriter<User> writer) { return stepBuilderFactory.get("step").<User, User>chunk(65000) .reader(reader) .processor(processor) .writer(writer) .build(); } /** * reader 定义:读取文件数据 + entity 映射 */ @Bean public ItemReader<User> reader() { FlatFileItemReader<User> reader = new FlatFileItemReader<>(); reader.setResource(new ClassPathResource("user.csv")); reader.setLineMapper(new DefaultLineMapper<User>() { { setLineTokenizer(new DelimitedLineTokenizer() { { setNames("id", "name", "gender"); } }); setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() { { setTargetType(User.class); } }); } }); return reader; } /** * processor bean 处理数据 + 校验数据 */ @Bean public ItemProcessor<User, User> processor() { CsvItemProcessor processor = new CsvItemProcessor(); // 设置校验器 processor.setValidator(new CsvValidator<>()); return processor; } /** * writer bean 设置批量插入sql语句,写入数据库 */ @Bean public ItemWriter<User> writer() { JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<>(); writer.setDataSource(dataSource); // 设置有参数的sql语句 writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()); writer.setSql("insert into `user` values(:id,:name,:gender)"); return writer; } }
package com.DoAn.HairStyle.api; import com.DoAn.HairStyle.dto.*; import com.DoAn.HairStyle.entity.UserEntity; import com.DoAn.HairStyle.respositiry.UserRespository; import com.DoAn.HairStyle.service.UserService; import net.bytebuddy.asm.Advice; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.lang.NonNull; import org.springframework.web.bind.annotation.*; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("api/v1/user") @CrossOrigin(origins = "*") public class UserController { private final UserService userService; @Autowired private UserRespository userRespository; @Autowired public UserController(UserService userService) { this.userService = userService; } @PostMapping public AuthResponse addUser(@Valid @NonNull @RequestBody UserEntity user){ return userService.insertUser(user); } @GetMapping public List<UserEntity> getAllUser(){ return userRespository.findAll(); } @PostMapping(path = "/login") public AuthResponse login(@Valid @NonNull @RequestBody LoginRequest loginRequest){ return userService.login(loginRequest); } @GetMapping(path = "{token}") public UserEntity getUserByToken(@PathVariable("token") String token){ return userRespository.findByToken(token); } @PutMapping(path = "/update/{token}") public Response updateUser( @Valid @NonNull @RequestBody UpdateUserRequest updateUserRequest ,@PathVariable("token") String token){ return userService.updateUser(token,updateUserRequest); } @DeleteMapping(path = "/delete/{token}") public Response deleteUser(@PathVariable("token") String token){ return userService.deleteByToken(token); } @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*").allowedHeaders("*").allowedMethods("*"); } }; } @PostMapping(path = "/forgot") public Response forgot(@Valid @NonNull @RequestBody forgotRequest forgotRequest){ return userService.forgotUser(forgotRequest); } @PostMapping(path = "/changePassword") public Response changePassword(@Valid @NonNull @RequestBody changePassword changePassword){ return userService.changePassword(changePassword); } // protected void configure(HttpSecurity httpSecurity) throws Exception { // httpSecurity.cors(); // } }
package br.org.funcate.glue.model.canvas; import java.awt.Graphics; public interface GraphicsPainter { public void paint(Graphics g); }
package br.bispojr.mastermind.jogo.models; import javax.swing.*; import java.io.Serializable; public class EsferaModel extends JComponent implements Serializable { public static String[] IMAGES = {"/jogo/vazio.png", "/jogo/azul.png", "/jogo/amarelo.png", "/jogo/rosa.png", "/jogo/roxo.png", "/jogo/laranja.png", "/jogo/marrom.png"}; private static final String[] SONS = {"vazio.mp3", "azul.mp3", "amarelo.mp3", "rosa.mp3", "roxo.mp3", "laranja.mp3", "marrom.mp3"}; private static final int VAZIO = 0; private static final int AZUL = 1; private static final int AMARELO = 2; private static final int ROSA = 3; private static final int ROXO = 4; private static final int LARANJA = 5; private static final int MARROM = 6; private int cor; private String img; private String som; public EsferaModel(int cor) { if ((cor >= 0) && (cor <= 6)) { this.cor = cor; som = SONS[cor]; img = IMAGES[cor]; } else { throw new NumberFormatException("Cor inexistente!: " + cor); } } /** * @deprecated */ public EsferaModel() { this(0); } public void setCor(int cor) { img = IMAGES[cor]; som = SONS[cor]; this.cor = cor; } public int getCor() { return cor; } public String[] getCores() { return IMAGES; } public String getPachImg() { return img; } public String getPachSom() { return som; } public int hashCode() { int hash = 7; return hash; } public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } EsferaModel other = (EsferaModel) obj; if (cor != cor) { return false; } return true; } public String toString() { if (cor == 0) { return cor + " - Vazio"; } if (cor == 1) { return cor + " - Azul"; } if (cor == 2) { return cor + " - Amarelo"; } if (cor == 3) { return cor + " - Rosa"; } if (cor == 4) { return cor + " - Roxo"; } if (cor == 5) { return cor + " - Laranja"; } if (cor == 6) { return cor + " - Cinza"; } return cor + "ERRO DE COR"; } public static void main(String[] a) { EsferaModel esf0 = new EsferaModel(0); EsferaModel esf1 = new EsferaModel(1); EsferaModel esf2 = new EsferaModel(2); EsferaModel esf3 = new EsferaModel(3); EsferaModel esf4 = new EsferaModel(4); EsferaModel esf5 = new EsferaModel(5); EsferaModel esf6 = new EsferaModel(6); System.out.println(esf0.getPachImg()); } }
package com.doit.net.scan.udp.base; import com.doit.net.scan.udp.constants.ScanFreqConstants; import com.doit.net.scan.udp.server.ScanWorkThread; import com.doit.net.scan.udp.utils.StringUtils; import java.util.ArrayList; import java.util.List; /** * Created by wly on 2019/7/21. * 串口消息 */ public class SerialMessage extends BaseHeader{ private String msg; private String reg; public int waitTimes; public boolean isSend; private String head; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getReg() { return reg; } public void setReg(String reg) { this.reg = reg; } public int getWaitTimes() { return waitTimes; } public void setWaitTimes(int waitTimes) { this.waitTimes = waitTimes; } public boolean isSend() { return isSend; } public void setSend(boolean send) { isSend = send; } public String getHead() { return head; } public void setHead(String head) { this.head = head; } /** * 解码 * @param data * @param message * @return */ public SerialMessage decode(byte[] data, SerialMessage message) { return null; } private static String dataStr = ""; private static RemMacroItem item = null; private static List<RemNeighbourItem> gsmList = new ArrayList( ); private static List<RemNeighbourItem> wcdmaList = new ArrayList( ); /** * 码流解码 * @param data */ public synchronized static void decodeByte(byte[] data) { String content = new String( data ); if (content.startsWith( ScanFreqConstants.PRE_EEMGINFO )) { String[] arr = content.split( "\r\n" ); for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMGINFOSVC )) { //GSM当前小区解码 pushInfoSvcToWorkThread( str, ScanFreqConstants.POST_EEMGINFOSVC ); ReportResult( "【======GSM扫频结果上报======】", "【======GSM邻区长度======】" ); } else if (str.startsWith( ScanFreqConstants.POST_EEMUMTSSVC )) { //UMTS本小区 String[] val = str.replace( "+EEMUMTSSVC:", "" ).split( "," ); if (val.length < 10) { continue; } pushUmtsToWorkThread( val, ScanFreqConstants.POST_EEMUMTSSVC ); ReportResult( "【======WCDMA扫频结果上报======】", "【======WCDMA邻区长度======】" ); }else if(str.startsWith( ScanFreqConstants.POST_EEMGINFONC )){ //GSM邻区 pushInfocToWorkThread( str, ScanFreqConstants.POST_EEMGINFONC ); ReportResult( "【======GSM扫频结果上报======】", "【======GSM邻区长度======】" ); } } } else if (content.startsWith( ScanFreqConstants.POST_EEMGINFONC )) { String[] arr = content.split( "\r\n" ); //GSM邻区信息解码 for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMGINFONC )) { pushInfocToWorkThread( str, ScanFreqConstants.POST_EEMGINFONC ); } } ReportResult( "【======GSM扫频结果上报======】", "【======GSM邻区长度======】" ); } else if (content.contains( ScanFreqConstants.POST_EEMGINFONC )) { String[] arr = content.split( "\r\n" ); //GSM邻区信息解码 for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMGINFONC )) { pushInfocToWorkThread( str, ScanFreqConstants.POST_EEMGINFONC ); } else if (str.startsWith( ScanFreqConstants.POST_EEMGINBFTM )) { pushinBfTmToWorkThread( str, ScanFreqConstants.POST_EEMGINBFTM ); } } ReportResult( "【======GSM扫频结果上报======】", "【======GSM邻区长度======】" ); } else if (content.startsWith( ScanFreqConstants.PRE_EEMUMTSINTER )) { String[] arr = content.split( "\r\n" ); for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMUMTSINTER )) { //添加umts异网邻区到工作线程 System.out.println("添加umts异网邻区到工作线程"); pushUmtsInterToWorkThread( str, ScanFreqConstants.POST_EEMUMTSINTER ); } } ReportResult( "【======WCDMA扫频结果上报======】", "【======WCDMA邻区长度======】" ); } else if (content.contains( ScanFreqConstants.POST_EEMUMTSINTER )) { String[] arr = content.split( "\r\n" ); for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMUMTSINTER )) { //添加umts异网邻区到工作线程 System.out.println("添加umts异网邻区到工作线程"); pushUmtsInterToWorkThread( str, ScanFreqConstants.POST_EEMUMTSINTER ); } } ReportResult( "【======WCDMA扫频结果上报======】", "【======WCDMA邻区长度======】" ); } else if (content.startsWith( ScanFreqConstants.PRE_EEMUMTSINTRA )) { String[] arr = content.split( "\r\n" ); for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMUMTSINTRA )) { //添加umts同网邻区到工作线程 String[] val = str.replace("+EEMUMTSINTRA:", "").split(","); if (val.length < 10) { continue; } System.out.println("添加umts同网邻区到工作线程"); pushUmtsIntraToWorkThread(val,ScanFreqConstants.POST_EEMUMTSINTRA ); } } ReportResult( "【======WCDMA扫频结果上报======】", "【======WCDMA邻区长度======】" ); } else if (content.contains( ScanFreqConstants.POST_EEMUMTSINTRA )) { String[] arr = content.split( "\r\n" ); for (String str : arr) { if (str.startsWith( ScanFreqConstants.POST_EEMUMTSINTRA )) { //添加umts同网邻区到工作线程 System.out.println("添加umts同网邻区到工作线程"); String[] val = str.replace("+EEMUMTSINTRA:", "").split(","); if (val.length < 10) { continue; } pushUmtsIntraToWorkThread(val,ScanFreqConstants.POST_EEMUMTSINTRA ); } } ReportResult( "【======WCDMA扫频结果上报======】", "【======WCDMA邻区长度======】" ); } } public static void ReportResult(String msg,String msg2){ //将扫频结果添加到工作线程 if(item!=null && StringUtils.isNotBlank( item.getHead() )){ System.out.println(msg); if(ScanFreqConstants.GSM_SCAN_RESULT.equals( item.getHead() )){ item.setList( gsmList ); }else { item.setList( wcdmaList ); } ScanWorkThread.push( item ); System.out.println(msg2+item.getList().size()); System.out.println("==================item====="+item); System.out.println("==================List====="+item.getList()); if(item.getList().size()>0){ for (RemNeighbourItem it : item.getList()){ System.out.println(msg+"==============fcn:"+it.getFcn()+",plmn:"+it.getPlmn()+",rxLevel:"+it.getRxLevel()+",psc:"+it.getPci()); } } dataStr = ""; //list.clear(); item = null; } } /** * 解码 * @param data * @return */ public void decodeRemMacroItem(byte[] data) { String content = new String( data ); if(content.startsWith( ScanFreqConstants.PRE_EEMGINFO)){ String[] arr = content.split( "\r\n" ); for (String str : arr){ if(str.startsWith( ScanFreqConstants.POST_EEMLTESVC )){ //LTE pushLTEtoWorkThread(str,ScanFreqConstants.POST_EEMLTESVC ); }else if(str.startsWith( ScanFreqConstants.POST_EEMUMTSSVC )){ //UMTS String[] val = str.replace("+EEMLTESVC:", "").split(","); if (val.length < 10) { continue; } pushUmtsToWorkThread(val,ScanFreqConstants.POST_EEMUMTSSVC); }else if(str.startsWith( ScanFreqConstants.POST_EEMGINFOSVC )){ //添加到工作线程 pushInfoSvcToWorkThread(str,ScanFreqConstants.POST_EEMGINFOSVC ); }else if(str.startsWith( ScanFreqConstants.POST_EEMGINBFTM )){ //添加到工作线程 pushinBfTmToWorkThread(str,ScanFreqConstants.POST_EEMGINBFTM ); }else if(str.startsWith( ScanFreqConstants.POST_EEMGINFONC )){ //添加到工作线程 pushInfocToWorkThread(str,ScanFreqConstants.POST_EEMGINFONC ); } } }else if(content.startsWith( ScanFreqConstants.PRE_EEMLTEINTER ) || content.startsWith( ScanFreqConstants.PRE_EEMLTEINTRA ) || content.startsWith( ScanFreqConstants.PRE_EEMUMTSINTER ) || content.startsWith( ScanFreqConstants.PRE_EEMUMTSINTRA )){ String[] arr = content.split( "\r\n" ); for (String str : arr){ if(str.startsWith( ScanFreqConstants.POST_EEMLTEINTER )){ //添加到工作线程 pushLTEInterToWorkThread(str,ScanFreqConstants.POST_EEMLTEINTER ); }else if(str.startsWith( ScanFreqConstants.POST_EEMLTEINTRA )){ //添加到工作线程 pushLTEIntraToWorkThread(str,ScanFreqConstants.POST_EEMLTEINTRA ); }else if(str.startsWith( ScanFreqConstants.POST_EEMUMTSINTER )){ //添加到工作线程 pushUmtsInterToWorkThread(str,ScanFreqConstants.POST_EEMUMTSINTER ); }else if(str.startsWith( ScanFreqConstants.POST_EEMUMTSINTRA )){ //添加到工作线程 String[] val = str.replace("+EEMUMTSINTRA:", "").split(","); if (val.length < 10) { continue; } pushUmtsIntraToWorkThread(val,ScanFreqConstants.POST_EEMUMTSINTRA ); } } } } /** * 添加到工作线程 * @param val * @param head */ private static void pushUmtsIntraToWorkThread(String[] val, String head) { //+EEMUMTSINTER:\ 0,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 0,\ 10713,\ 29\r\n\r\n\+EEMUMTSINTER:\ 1,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 1,\ 10713,\ 327\r\n\r\n\+EEMUMTSINTER:\ 2,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 2,\ 10713,\ 182\r\n\r\n\+EEMUMTSINTER:\ 3,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 3,\ 10713,\ 336\r\n\r\n\+EEMUMTSINTER:\ 4,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 4,\ 10713,\ 230\r\n\r\n\+EEMUMTSINTER:\ 5,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 5,\ 10713,\ 72\r\n\r\n\+EEMUMTSINTER:\ 6,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 6,\ 10713,\ 221\r\n\r\n\+EEMUMTSINTER:\ 7,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 7,\ 10713,\ 378\r\n\r\n\+EEMUMTSINTRA:\ 0,\ -32768,\ -1,\ -115,\ 0,\ 0,\ 65534,\ 1,\ 10663,\ 478\r\n //+EEMUMTSINTER: 0, -32768, 0, -115, 0, 0, 65534, 0, 10713, 29 //pccpchRSCP,utraRssi,sRxLev,mcc,mnc,lac,ci,arfcn,cellParameterId //+EEMUMTSINTRA:\ 0,\ -32768,\ -1,\ -115,\ 0,\ 0,\ 65534,\ 1,\ 10663,\ 478\r\n System.out.println("===pushUmtsIntraToWorkThread==="); String rxLevel = val[3].trim(); String lac = val[6].trim(); String ci = val[7]; String mcc = Integer.toHexString( Integer.parseInt( val[4].trim() ) ); String _mnc = Integer.toHexString( Integer.parseInt( val[5].trim() ) ); String mnc = _mnc.length() == 2 ? _mnc : "0" + _mnc; String plmn = mcc+mnc; if (StringUtils.isNotBlank( ci ) && !"0".equals( ci )) { ci = ci.trim(); } String arfcn = val[8].trim(); String psc = val[9].trim(); if(item==null){ item = new RemMacroItem(); item.setHead( ScanFreqConstants.UMTS_SCAN_RESULT ); } RemNeighbourItem ritem = new RemNeighbourItem(); ritem.setCi( ci ); ritem.setPci( psc ); ritem.setFcn( arfcn ); ritem.setLac( lac ); ritem.setRxLevel( rxLevel ); ritem.setPlmn( plmn ); wcdmaList.add( ritem ); } /** * 添加到工作线程 * @param l * @param head */ private static void pushUmtsInterToWorkThread(String l, String head) { //+EEMUMTSINTER:\ 0,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 0,\ 10713,\ 29\r\n\r\n\+EEMUMTSINTER:\ 1,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 1,\ 10713,\ 327\r\n\r\n\+EEMUMTSINTER:\ 2,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 2,\ 10713,\ 182\r\n\r\n\+EEMUMTSINTER:\ 3,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 3,\ 10713,\ 336\r\n\r\n\+EEMUMTSINTER:\ 4,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 4,\ 10713,\ 230\r\n\r\n\+EEMUMTSINTER:\ 5,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 5,\ 10713,\ 72\r\n\r\n\+EEMUMTSINTER:\ 6,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 6,\ 10713,\ 221\r\n\r\n\+EEMUMTSINTER:\ 7,\ -32768,\ 0,\ -115,\ 0,\ 0,\ 65534,\ 7,\ 10713,\ 378\r\n\r\n\+EEMUMTSINTRA:\ 0,\ -32768,\ -1,\ -115,\ 0,\ 0,\ 65534,\ 1,\ 10663,\ 478\r\n //+EEMUMTSINTER: 0, -32768, 0, -115, 0, 0, 65534, 0, 10713, 29 //pccpchRSCP,utraRssi,sRxLev,mcc,mnc,lac,ci,arfcn,cellParameterId //+EEMUMTSINTRA:\ 0,\ -32768,\ -1,\ -115,\ 0,\ 0,\ 65534,\ 1,\ 10663,\ 478\r\n String[] val = l.replace("+EEMUMTSINTER:", "").split(","); if(val.length<10){ return; } String rxLevel = val[3].trim(); String lac = val[6].trim(); String ci = val[7]; if (StringUtils.isNotBlank( ci ) && !"0".equals( ci ) ) { ci = ci.trim(); } String arfcn = val[8]; if (StringUtils.isNotBlank( arfcn ) && !"0".equals( arfcn ) ) { arfcn = arfcn.trim(); } String psc= val[9]; if (StringUtils.isNotBlank( psc ) && !"0".equals( psc )) { psc = psc.trim(); } if(item==null){ item = new RemMacroItem(); item.setHead( ScanFreqConstants.UMTS_SCAN_RESULT ); } RemNeighbourItem ritem = new RemNeighbourItem(); ritem.setCi( ci ); ritem.setPci( psc ); ritem.setFcn( arfcn ); ritem.setLac( lac ); ritem.setRxLevel( rxLevel ); wcdmaList.add( ritem ); System.out.println("===pushUmtsInterToWorkThread==="); } /** * 添加到工作线程 * @param l * @param head */ private void pushLTEIntraToWorkThread(String l, String head) { String[] val = l.replace("+EEMLTEINTER:", "").split(","); String pci = val[1].trim(); String fcn = val[2].trim(); RemMacroItem item = new RemMacroItem(); item.setHead( head ); RemNeighbourItem ritem = new RemNeighbourItem(); ritem.setPci( pci ); ritem.setFcn( fcn ); List<RemNeighbourItem> list = new ArrayList( ); list.add( ritem ); item.setList( list ); System.out.println("===pushLTEIntraToWorkThread==="); ScanWorkThread.push( item ); } /** * 添加到工作线程 * @param l * @param head */ private void pushLTEInterToWorkThread(String l, String head) { String[] val = l.replace("+EEMLTEINTER:", "").split(","); String pci = val[1].trim(); String fcn = val[2].trim(); RemMacroItem item = new RemMacroItem(); item.setHead( head ); RemNeighbourItem ritem = new RemNeighbourItem(); ritem.setPci( pci ); ritem.setFcn( fcn ); List<RemNeighbourItem> list = new ArrayList( ); list.add( ritem ); item.setList( list ); ScanWorkThread.push( item ); System.out.println("===pushLTEInterToWorkThread==="); } /** * 添加到工作线程 * @param l * @param head */ private static void pushInfocToWorkThread(String l, String head) { System.out.println("===pushInfocToWorkThread==="); //+EEMGINFONC:\ 1,\ 0,\ 0,\ 0,\ 0,\ 0,20,\ 255,\ 0,\ 0,\ 99,\ 0,\ 0\r\n\r\n\ String[] val = l.replace("+EEMGINFONC:", "").split(","); if(l.length()<10){ return; } RemNeighbourItem ritem = new RemNeighbourItem(); String mcc = Integer.toHexString( Integer.parseInt( val[1].trim() ) ); String ss = val[2]; String _mnc = Integer.toHexString( Integer.parseInt( val[2].trim() ) ); String mnc = _mnc.length() == 2 ? _mnc : "0" + _mnc; String tac = val[3].trim(); String ci = val[5].trim(); //String rx_lev = Integer.toHexString( Integer.parseInt( val[6].trim() ) ); String fcn = val[10].trim(); String fcn2= Integer.toHexString( Integer.parseInt( val[10].trim() ) ); ritem.setPlmn( mcc + mnc ); ritem.setLac( tac ); ritem.setCi( ci ); ritem.setRxLevel( val[6].trim() ); ritem.setFcn( fcn ); if(item==null){ item = new RemMacroItem(); item.setHead( ScanFreqConstants.GSM_SCAN_RESULT ); } if(!ritem.getPlmn().startsWith( "0" )){ gsmList.add( ritem ); } } /** * 添加到工作线程 * @param l * @param head */ private static void pushinBfTmToWorkThread(String l, String head) { System.out.println("===pushinBfTmToWorkThread==="); if(l.length()<15){ return; } //+EEMGINBFTM:\ 1,\ 1120,\ 1,\ 4188,\ 52884,\ 0,\ 17,\ 7,\ 0,\ 0,\ 37,\ 0,\ 0,0,\ 0,\ 0,\ 0,\ 0,\ 0\r\n String[] val = l.replace("+EEMGINBFTM:", "").split(","); String mcc = Integer.toHexString( Integer.parseInt( val[1].trim() ) ); String _mnc = Integer.toHexString( Integer.parseInt( val[2].trim() ) ); String mnc = _mnc.length() == 2 ? _mnc : "0" + _mnc; String tac = Integer.toHexString( Integer.parseInt( val[3].trim() ) ); String ci = Integer.toHexString( Integer.parseInt( val[4].trim() ) ); String rx_lev = Integer.toHexString( Integer.parseInt( val[5].trim() ) ); String dlEuarfcn = val[15].trim(); RemNeighbourItem ritem = new RemNeighbourItem(); ritem.setFcn( dlEuarfcn ); ritem.setCi( ci ); ritem.setLac( tac ); ritem.setRxLevel( rx_lev ); ritem.setPlmn( mcc+mnc ); if(item==null){ item = new RemMacroItem(); item.setHead( ScanFreqConstants.GSM_SCAN_RESULT ); } if(!ritem.getPlmn().startsWith( "0" )){ gsmList.add( ritem ); } } /** * GSM当前小区工程信息 * @param l * @param head */ private static void pushInfoSvcToWorkThread(String l, String head) { System.out.println("===pushInfoSvcToWorkThread==="); //+EEMGINFOSVC:\ 1120,\ 1,\ 55064,\ 8,\ 0,\ 0,\ 25,\ 38,\ 58,\ 0,\ 0,\ \ 38,\ 0,\ 0,\ 0,\ 0,\ \ 0,\ 0,\ 0,\ 0,\ 0,\ 0,\ 100,\ \ 2,\ 100,\ 36,\ 6,\ 54,\ 0,\ 0,\ \ 0,\ 0,\ 0,\ 0,\ 0,\ 0\r\n\r\n\ String[] val = l.replace("+EEMGINFOSVC:", "").split(","); if(val.length<21){ return; } String mcc = Integer.toHexString( Integer.parseInt( val[0].trim() ) ); String _mnc = Integer.toHexString( Integer.parseInt( val[1].trim() ) ); String mnc = _mnc.length() == 2 ? _mnc : "0" + _mnc; //String tac = Integer.toHexString( Integer.parseInt( val[2].trim() ) ); //String ci = Integer.toHexString( Integer.parseInt( val[3].trim() ) ); String dlEuarfcn = val[22].trim(); item = new RemMacroItem(); item.setPlmn( mcc + mnc ); item.setFcn( dlEuarfcn ); item.setCi( val[3].trim() ); item.setLac( val[2].trim() ); item.setHead( ScanFreqConstants.GSM_SCAN_RESULT ); item.setSvc( true ); if("0".equals( item.getPlmn() )){ item = null; } } /** * 把UMTS消息添加到工作线程 * @param val */ private static void pushUmtsToWorkThread(String[] val,String head) { //+EEMUMTSSVC:3, 1, 1, 1,-88, 16, -3, -19, -115, -32768, 43, 1, 1120, 1, 43051, 14005560, 43, 480, 10663, 60, 0, 0, 1, 128, 128, 65535, 0, 0, 2, 255, 65535, -1, 0, 0, 0, 0, 0, 0,0, 0, 0, 0, -1, -1, 1, 1,28672, 255, 194, 24, 0, 65535, 0, 0, 0 //+EEMUMTSSVC:3,\ 1,\ 1,\ 1,-78,\ 27,\ -3,\ -19,\ -115,\ -32768,\ 43,\ 1,\ 1120,\ 1,\ 43051,\ 14005560,\ 43,\ 480,\ 10663,\ 60,\ 0,\ 0,\ 1,\ 128,\ 128,\ 65535,\ 0,\ 0,\ 2,\ 255,\ 65535,\ -1,\ 0,\ 0,\ 0,\ 0,\ 0,\ 0,0,\ 0,\ 0,\ 0,\ -1,\ -1,\ 1,\ 1,28672,\ 255,\ 194,\ 24,\ 0,\ 65535,\ 0,\ 0,\ 0\r\n System.out.println("===pushUmtsToWorkThread==="); String rxLevel = ""; String ci = ""; String arfcn = ""; String rac = ""; String mcc = ""; String _mnc = ""; String mnc = ""; String lac = ""; String psc = ""; String rscp = ""; String s = val[12].trim(); mcc = Integer.toHexString( Integer.parseInt( s ) ); _mnc = Integer.toHexString( Integer.parseInt( val[13].trim() ) ); mnc = _mnc.length() == 2 ? _mnc : "0" + _mnc; lac = val[14].trim(); psc = val[17].trim(); arfcn = val[18].trim(); ci = val[15].trim(); rac = val[10].trim(); rxLevel = val[8].trim(); rscp = val[4].trim(); //-36 item = new RemMacroItem(); item.setPlmn( mcc + mnc ); item.setPci(psc); item.setFcn( arfcn ); item.setCi( ci ); item.setRac( rac ); item.setLac( lac ); item.setRxLevl( rxLevel ); item.setRscp( rscp ); item.setHead( ScanFreqConstants.UMTS_SCAN_RESULT ); } /**l * 把LTE消息添加到工作线程 * @param l */ private void pushLTEtoWorkThread(String l,String head) { //+EEMLTESVC:1120, 2, 17, 23079, 70, 100, 18100, 1, 5, 94497282, 0, 50, 14, 1, 51, 20, 20, 127, 68, 0, 0, 0, 1, 24, 2, 1, 0, 65535, 255, -1 String[] val = l.replace("+EEMLTESVC:", "").split(","); String mcc = Integer.toHexString( Integer.parseInt( val[0].trim() ) ); int lenMnc = Integer.parseInt( val[1].trim() ); String _mnc = Integer.toHexString( Integer.parseInt( val[2].trim() ) ); String mnc = _mnc.length() == 2 ? _mnc : "0" + _mnc; String tac =val[3].trim(); String pci = val[4].trim(); String dlEuarfcn = val[5].trim(); String ulEuarfcn = val[6].trim(); String band = Integer.toHexString( Integer.parseInt( val[7].trim() ) ); String dlbandWidth = Integer.toHexString( Integer.parseInt( val[8].trim() ) ); String ci = Integer.toHexString( Integer.parseInt( val[9].trim() ) ); String rsrp = Integer.toHexString( Integer.parseInt( val[10].trim() ) ); String rsrq = Integer.toHexString( Integer.parseInt( val[11].trim() ) ); RemMacroItem item = new RemMacroItem(); item.setPlmn( mcc + mnc ); item.setPci( pci ); item.setFcn(dlEuarfcn); item.setCi( val[9].trim()); item.setLac( tac ); item.setHead( head ); ScanWorkThread.push( item ); System.out.println("===pushLTEtoWorkThread==="); } }
package flaxbeard.cyberware.api; import java.util.List; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; public interface ICyberware { public EnumSlot getSlot(ItemStack stack); public int installedStackSize(ItemStack stack); public ItemStack[][] required(ItemStack stack); public boolean isIncompatible(ItemStack stack, ItemStack comparison); boolean isEssential(ItemStack stack); public List<String> getInfo(ItemStack stack); public int getCapacity(ItemStack wareStack); public enum EnumSlot { EYES(12, "eyes"), CRANIUM(11, "cranium"), HEART(14, "heart"), LUNGS(15, "lungs"), LOWER_ORGANS(17, "lowerOrgans"), SKIN(18, "skin"), MUSCLE(19, "muscle"), BONE(20, "bone"), ARM(21, "arm", true, true), HAND(22, "hand", true, false), LEG(23, "leg", true, true), FOOT(24, "foot", true, false); private final int slotNumber; private final String name; private final boolean sidedSlot; private final boolean hasEssential; private EnumSlot(int slot, String name, boolean sidedSlot, boolean hasEssential) { this.slotNumber = slot; this.name = name; this.sidedSlot = sidedSlot; this.hasEssential = hasEssential; } private EnumSlot(int slot, String name) { this(slot, name, false, true); } public int getSlotNumber() { return slotNumber; } public static EnumSlot getSlotByPage(int page) { for (EnumSlot slot : values()) { if (slot.getSlotNumber() == page) { return slot; } } return null; } public String getName() { return name; } public boolean isSided() { return sidedSlot; } public boolean hasEssential() { return hasEssential; } } public void onAdded(EntityLivingBase entity, ItemStack stack); public void onRemoved(EntityLivingBase entity, ItemStack stack); public interface ISidedLimb { public EnumSide getSide(ItemStack stack); public enum EnumSide { LEFT, RIGHT; } } public int getEssenceCost(ItemStack stack); }
import java.awt.event.*; import javax.swing.*; import java.util.List; public class ControleurChamp implements ActionListener { private AfficherReservation reservation; private JTextField champ1; private JTextField champ2; private BaseDeDonnee db; private boolean unSeulChamp; public ControleurChamp(AfficherReservation afficherReservation, JTextField reference) { this.reservation = afficherReservation; this.champ1 = reference; this.champ2 = null; this.db = BaseDeDonnee.getInstance(); this.unSeulChamp = true; } public ControleurChamp(AfficherReservation afficherReservation, JTextField prenom, JTextField nom) { this.reservation = afficherReservation; this.champ1 = prenom; this.champ2 = nom; this.db = BaseDeDonnee.getInstance(); this.unSeulChamp = false; } @Override public void actionPerformed(ActionEvent e) { e = (ActionEvent) e; Effacer effacer = Effacer.getInstance(); effacer.cleanAll(); if(unSeulChamp == true) { String entrer = champ1.getText().trim(); if(entrer != null && entrer.length()>9 && entrer.charAt(4) == '-' && entrer.charAt(9) == '-') { List<Reservation> listReservation = db.chercherReservation(entrer); if(listReservation.size() != 0) { reservation.setValeur(listReservation); } } else { // sinon mauvais format MessageErreur erreur = new MessageErreur(MessageErreur.MAUVAIS_FORMAT); } } else {//nom presentation String prenom = champ1.getText().trim(); String nom = champ2.getText().trim(); if( ! nom.equals("") && ! prenom.equals("")) { List<Reservation> listReservation = db.chercherReservation(prenom, nom); if(listReservation.size() != 0) { reservation.setValeur(listReservation); } } } } }
package com.makethingshum.fantasy; import java.util.concurrent.ThreadLocalRandom; /** * Created by jwells on 14/02/2017. */ public class RandomSelection { public static <E extends Enum<E>> E getRandom(Class<E> enumClass) { int pick = ThreadLocalRandom.current().nextInt(enumClass.getEnumConstants().length); return enumClass.getEnumConstants()[pick]; } public static <E extends Enum<E>> E getRandomExcluding(Class<E> enumClass, E exclude) { E choice = getRandom(enumClass); if (enumClass.getEnumConstants().length > 1) { while (choice == null || choice == exclude) { choice = getRandom(enumClass); } } return choice; } }
package br.com.pcmaker.spring.view.validation.collection; import java.util.Collection; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; @SuppressWarnings("rawtypes") public class NotEmptyCollectionValidator implements ConstraintValidator<NotEmptyCollection, Collection> { @Override public void initialize(NotEmptyCollection constraintAnnotation) { } @Override public boolean isValid(Collection lista, ConstraintValidatorContext constraintContext) { if(lista == null || lista.isEmpty() ){ return false; } return true; } }
package com.example.controllers; import com.example.dao.CategoryDao; import com.example.dao.OrderDao; import com.example.dao.ProductDao; import com.example.entities.Category; import com.example.entities.Order; import com.example.entities.Product; import com.google.gson.JsonObject; import org.apache.commons.io.FileUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletContext; import java.io.File; import java.io.IOException; /** * Created by Andros on 04.02.2017. */ @Controller public class AdminPageController implements ServletContextAware { @Autowired private CategoryDao catDao; @Autowired private ProductDao productDao; @Autowired private OrderDao orderDao; ServletContext servletContext; //редактирует товар @RequestMapping(value="/edit" , method = RequestMethod.POST) public ModelAndView edit(@RequestParam(value = "id") long id) { ModelAndView editMV = new ModelAndView("edit"); JsonObject j = getJSONProduct(id); editMV.addObject("prod", j); return editMV; } //удалить заказ @RequestMapping(value = "/delete_order", method = RequestMethod.POST) public String delOrder(Long id) { orderDao.delete(id); return "aorders"; } //подтвердить заказ @RequestMapping(value = "/confirm_order", method = RequestMethod.POST) public String confOrder(Long id) { Order order = orderDao.findOne(id); order.setConfirmed(1); orderDao.saveAndFlush(order); return "aorders"; } /* @RequestMapping("/get_order0") public ModelAndView getOrder0() { ModelAndView mw = new ModelAndView("aorders"); return mw; }*/ //возвращает страницу с новыми заказами @RequestMapping("/aorders") public ModelAndView orders() { ModelAndView mw = new ModelAndView("aorders"); return mw; } //удалить продукт @RequestMapping(value="/delete" , method = RequestMethod.POST) public String delete(@RequestParam(value = "id") long id) { productDao.delete(id); return "admin"; } //добавить новую категорию товаров @RequestMapping(value="/addcat" , method = RequestMethod.POST) public ModelAndView index(@RequestParam(value = "name") String name) { Category cat = new Category(); cat.setName(name); catDao.saveAndFlush(cat); ModelAndView mw = new ModelAndView("admin"); return mw; } //добавить новый товар @RequestMapping(value="/addgoods" , method = RequestMethod.POST) public ModelAndView addGoods(@RequestParam(value = "name") String name, @RequestParam(value = "cat") long cat, @RequestParam(value = "price") double price, @RequestParam(value = "comment") String desc, @RequestParam(value = "photo") MultipartFile photo, @RequestParam(value = "id", required = false) Long id ) { ModelAndView mw = new ModelAndView("admin"); try { File file = new File(""); String path=""; if (photo.isEmpty()){ path = productDao.getOne(id).getPhoto(); } else { file = new File(servletContext.getRealPath("/")+"WEB-INF/classes/public/img/goods/"+ System.currentTimeMillis()+photo.getOriginalFilename()); FileUtils.writeByteArrayToFile(file, photo.getBytes()); path = file.getAbsolutePath().replace(servletContext.getRealPath("/")+"WEB-INF\\classes\\public", "").replace("\\","/"); } Category category = catDao.getOne(cat); Product p = new Product(id, name, category, price, path, desc); productDao.saveAndFlush(p); } catch (IOException e) { e.printStackTrace(); } return mw; } @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } //метод отдающий продукт как JSON объект public JsonObject getJSONProduct(long id){ Product product = productDao.getOne(id); JsonObject j = new JsonObject(); j.addProperty("id", product.getId()); j.addProperty("name",product.getName()); j.addProperty("desc", product.getDescription()); j.addProperty("photo",product.getPhoto()); j.addProperty("price", product.getPrice()); j.addProperty("cat", product.getCategory().getId()); j.addProperty("photo", product.getPhoto().replace(servletContext.getRealPath("/")+"WEB-INF\\classes\\public", "").replace("\\","/")); return j; } }
package HW190612; public class ScoreMath { private int math; public ScoreMath(int math) { this.math = math; } public void print() { System.out.println("수학 점수는 "+math+"점입니다."); } }
package com.giraldo.parqueo.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.giraldo.parqueo.model.TipoDocumento; import com.giraldo.parqueo.model.TipoTiempo; import com.giraldo.parqueo.model.TipoUsuario; import com.giraldo.parqueo.model.TipoVehiculo; import com.giraldo.parqueo.model.Tipologia; @Repository public interface TipologiaRepository extends JpaRepository<Tipologia, Long>{ @Query("select u from TipoDocumento u") public List<TipoDocumento> consultarTiposDocumentos(); @Query("select u from TipoVehiculo u") public List<TipoVehiculo> consultarTiposVehiculos(); @Query("select u from TipoTiempo u") public List<TipoTiempo> consultarTiposTiempos(); @Query("select u from TipoUsuario u") public List<TipoUsuario> consultarTiposUsuarios(); }
package sorting; public class ShellSort { public static void main(String[] args) { int arr[] = { 5, 4, 3, 2, 1 }; shellSort(arr); for (int e : arr) { System.out.print(e + " "); } System.out.println(); } static void shellSort(int arr[]) { int n = arr.length; for (int gap = n / 2; gap > 0; gap /= 2) { for (int i = gap; i < n; i++) { int temp = arr[i]; int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { arr[j] = arr[j - gap]; } arr[j] = temp; } } } }
package com.cjava.spring.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.cjava.spring.entity.Cliente; import com.cjava.spring.util.HibernateBaseDao; @Repository public class ClienteDao { @Autowired private HibernateBaseDao hibernateBaseDao; public void registrar(Cliente cliente) { hibernateBaseDao.grabar(cliente); } public void actualizar(Cliente cliente) { hibernateBaseDao.modificar(cliente); } public Cliente obtener(Long id) { return (Cliente) hibernateBaseDao.buscarPorId(Cliente.class, id); } public void eliminar(Long id) { hibernateBaseDao.eliminarPorId(Cliente.class, id); } public List<Cliente> listar() { return hibernateBaseDao.buscarTodos(Cliente.class); } }
package com.innavathon; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; @SpringBootApplication public class InnavathonApplication { public static void main(String[] args) { SpringApplication.run(InnavathonApplication.class, args); } }
package org.houstondragonacademy.archer.services; import org.houstondragonacademy.archer.dao.AccountRepository; import org.houstondragonacademy.archer.dao.entity.Account; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.ClientRegistrationException; import org.springframework.security.oauth2.provider.client.BaseClientDetails; import org.springframework.stereotype.Service; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import java.util.stream.Collectors; @Service public class AccountServiceImpl implements AccountService { @Autowired private AccountRepository repo; @Override public Mono<Account> createAccount(Account account) { return repo.insert(account); } @Override public Mono<Account> updateAccount(Account account, String id) { return findOne(id) .doOnSuccess(accountDoc -> { accountDoc.setImageUrl(account.getImageUrl()); accountDoc.setProvider(account.getProvider()); accountDoc.setProviderId(account.getProviderId()); accountDoc.setRoles(account.getRoles()); accountDoc.setAccountType(account.getAccountType()); accountDoc.setEmail(account.getEmail()); accountDoc.setHomeAddress(account.getHomeAddress()); accountDoc.setPhone(account.getPhone()); accountDoc.setName(account.getName()); accountDoc.setStudentIds(account.getStudentIds()); accountDoc.setNotes(account.getNotes()); accountDoc.setId(id); repo.save(accountDoc).subscribe(); }); } @Override public Flux<Account> findAll() { return repo.findAll(); } @Override public Mono<Account> findOne(String id) { return repo.findById(id); } @Override public Mono<Account> findByEmailAddress(String email) { return repo.findByEmail(email); //.switchIfEmpty(Mono.error(new AccountServiceException("User not exist with email containing" + email))); } @Override public Mono<Boolean> delete(String id) { return findOne(id) .doOnSuccess(accountDoc -> { accountDoc.setDeleted(true); repo.save(accountDoc).subscribe(); }) .flatMap(accountDoc -> Mono.just(accountDoc.getDeleted())); } @Override public ClientDetails loadClientByClientId(String email) throws ClientRegistrationException { return findByEmailAddress(email) .flatMap(account -> { BaseClientDetails resClient = new BaseClientDetails(); resClient.setClientId(account.getEmail()); resClient.setClientSecret(account.getPhone()); resClient.setAuthorities(account.getRoles() .stream() .map(role -> new SimpleGrantedAuthority(role.getAuthority())) .collect(Collectors.toSet())); return Mono.just(resClient); }) .block(); } }
package com.mimi.mimigroup.ui.main; import android.Manifest; import android.app.ActivityManager; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.mimi.mimigroup.R; import com.mimi.mimigroup.api.APIGPSTrack; import com.mimi.mimigroup.api.APINet; import com.mimi.mimigroup.api.APINetCallBack; import com.mimi.mimigroup.api.SyncGet; import com.mimi.mimigroup.app.AppSetting; import com.mimi.mimigroup.base.BaseActivity; import com.mimi.mimigroup.db.DBGimsHelper; import com.mimi.mimigroup.model.HT_PARA; import com.mimi.mimigroup.model.SystemParam; import com.mimi.mimigroup.ui.custom.CustomBoldTextView; import com.mimi.mimigroup.ui.custom.CustomTextView; import com.mimi.mimigroup.ui.login.LoginActivity; import com.mimi.mimigroup.ui.order.OrderFragment; import com.mimi.mimigroup.ui.services.mimiService; import com.mimi.mimigroup.ui.setting.SettingFragment; import com.mimi.mimigroup.ui.utility.UtilityFragment; import com.mimi.mimigroup.ui.visitcard.VisitCardFragment; import com.mimi.mimigroup.utils.AppUtils; import java.lang.reflect.Type; import java.util.Collection; import java.util.HashMap; import butterknife.BindView; public class MainActivity extends BaseActivity implements TabLayout.OnTabSelectedListener { @BindView(R.id.tabLayout) TabLayout tabLayout; private DBGimsHelper mDB; APIGPSTrack locationTrack; //SERVICES //private IntentFilter mIntentFilter; //private mimiBroadcastReceiver mReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 50); }else{ tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(0))); tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(1))); tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(2))); tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(3))); tabLayout.addOnTabSelectedListener(this); replaceFragment(new OrderFragment(), R.id.flContain); } mDB = DBGimsHelper.getInstance(this); if(APINet.isNetworkAvailable(this)) { if(!mDB.getParam("PAR_REG").contains("1")) { onSyncPARA(); } } //[11022019] locationTrack = new APIGPSTrack(MainActivity.this); if(!locationTrack.canGetLocation()){ locationTrack.showSettingsAlert(); }else{ locationTrack.getLocation(); } try{ String mParScope=mDB.getParam("PAR_SCOPE"); AppSetting.getInstance().setParscope(mParScope); }catch (Exception ex){} try { String mSERVER_IP=mDB.getParam("PAR_SERVER_IP"); String mSERVER_PORT=mDB.getParam("PAR_SERVER_PORT"); if(mSERVER_IP!=null && !mSERVER_IP.isEmpty() && !mSERVER_IP.equalsIgnoreCase(AppSetting.getInstance().getServerIP())){ AppSetting.getInstance().setServerIP(mSERVER_IP); }else if(mSERVER_IP.isEmpty() || mSERVER_IP==null){ HT_PARA oPar=new HT_PARA(); oPar.setParaCode("PAR_SERVER_IP"); oPar.setParaValue(AppSetting.getInstance().getServerIP()); mDB.addHTPara(oPar); } if(mSERVER_PORT!=null && !mSERVER_PORT.isEmpty() && !mSERVER_PORT.equalsIgnoreCase(AppSetting.getInstance().getPort())) { AppSetting.getInstance().setPort(mSERVER_PORT); }else if(mSERVER_PORT==null || mSERVER_PORT.isEmpty() ){ HT_PARA oPar=new HT_PARA(); oPar.setParaCode("PAR_SERVER_PORT"); oPar.setParaValue(AppSetting.getInstance().getPort()); mDB.addHTPara(oPar); } }catch (Exception ex){} //CALL SERVICE //stopService(new Intent(this,APILocationServices.class)); //Start MyService cùng với IntentFilter if(!isMyServiceRunning(mimiService.class)) { //mReceiver = new mimiBroadcastReceiver(); //mIntentFilter = new IntentFilter(); //mIntentFilter.addAction("ORDER_STATUS"); Intent serviceIntent = new Intent(getApplicationContext(), mimiService.class); startService(serviceIntent); } } @Override protected void onResume() { super.onResume(); if (tabLayout.getSelectedTabPosition() == 0){ replaceFragment(new OrderFragment(), R.id.flContain); } //service //registerReceiver(mReceiver, mIntentFilter); } //services @Override protected void onPause() { //unregisterReceiver(mReceiver); super.onPause(); } @Override protected void onStop(){ //stopService(new Intent(this,APILocationServices.class)); super.onStop(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 50 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED && grantResults[3] == PackageManager.PERMISSION_GRANTED){ tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(0))); tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(1))); tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(2))); tabLayout.addTab(tabLayout.newTab().setCustomView(getTabView(3))); tabLayout.addOnTabSelectedListener(this); replaceFragment(new OrderFragment(), R.id.flContain); }else{ Toast.makeText(this, "Ứng dụng không đủ quyền để tiếp tục", Toast.LENGTH_LONG).show(); } } //private String tabTitles[] = new String[] { "Quét", "Lịch sử","Vào Ra", "Cài đặt" }; private String tabTitles[] = new String[] { "Đơn Hàng", "Chấm Công","Tiện ích","Thiết Lập" }; private int[] imageResId = { R.drawable.tiva_order_w,R.drawable.tiva_timekeeping_w,R.drawable.tiva_utiliti_w, R.drawable.tiva_setting_w}; public View getTabView(int position) { //View v = LayoutInflater.from(App.getContext()).inflate(R.layout.custom_tab, null); View v = LayoutInflater.from(getApplicationContext()).inflate(R.layout.custom_tab, null); CustomBoldTextView tv = v.findViewById(R.id.tvTab); tv.setText(tabTitles[position]); ImageView img = v.findViewById(R.id.ivTab); img.setImageResource(imageResId[position]); return v; } @Override public void onTabSelected(TabLayout.Tab tab) { /*if (tab.getPosition() == 0){ replaceFragment(new ScanFragment(), R.id.flContain); replaceFragment(new ScanFragment(), R.id.flContain); }else if (tab.getPosition() == 1){ replaceFragment(new HistoryFragment(), R.id.flContain); }else if (tab.getPosition() == 2){ replaceFragment(new VisitCardFragment(), R.id.flContain); } else if (tab.getPosition() == 3){ replaceFragment(new SettingFragment(), R.id.flContain); }*/ if (tab.getPosition() == 0){ replaceFragment(new OrderFragment(), R.id.flContain); }else if (tab.getPosition() == 1){ replaceFragment(new VisitCardFragment(), R.id.flContain); }else if (tab.getPosition() == 2){ replaceFragment(new UtilityFragment(), R.id.flContain); }else if (tab.getPosition() == 3){ replaceFragment(new SettingFragment(), R.id.flContain); } } @Override public void onTabUnselected(TabLayout.Tab tab) {} @Override public void onTabReselected(TabLayout.Tab tab) {} //[11022019] private void turnGPSOn(){ try { String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if (!provider.contains("gps")) { //if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); Toast.makeText(this,"Đã bật GPS",Toast.LENGTH_SHORT).show(); } }catch (Exception ex){} } //SYNC-GETPARA private void onSyncPARA(){ final String Imei=AppUtils.getImeil(this); final String ImeiSim=AppUtils.getImeilsim(this ); final String mUrlGetPara = AppSetting.getInstance().URL_SyncHTPARA(Imei, ImeiSim); new SyncGet(new APINetCallBack() { @Override public void onHttpStart() { Toast oToast=Toast.makeText(MainActivity.this,"Đang tại lại tham số",Toast.LENGTH_LONG); oToast.setGravity(Gravity.CENTER,0,0); oToast.show(); } @Override public void onHttpSuccess(final String ResPonseRs) { if(ResPonseRs!=null && ResPonseRs!="" && ResPonseRs!="[]" && !ResPonseRs.isEmpty()){ MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { HashMap<String, String> map = new HashMap<>(); Gson gson = new Gson(); Type type = new TypeToken<Collection<HT_PARA>>() {}.getType(); Collection<HT_PARA> enums = gson.fromJson(ResPonseRs, type); HT_PARA[] ArrPARA = enums.toArray(new HT_PARA[enums.size()]); for(HT_PARA oPar:ArrPARA){ mDB.addHTPara(oPar); map.put(oPar.getParaCode(), oPar.getParaValue()); } mDB.addHTPara(new HT_PARA("PAR_IMEI",Imei)); mDB.addHTPara(new HT_PARA("PAR_IMEISIM",ImeiSim)); try { String PAR_TIME_SYNC="0",PAR_KEY_ENCRYPT="",PAR_SCOPE="0",PAR_DAY_CLEAR="",PAR_ADMIN_PASS="",PAR_ISACTIVE="",PAR_SYMBOL="AA"; if (map.containsKey("PAR_TIMER_SYNC")){ PAR_TIME_SYNC=map.get("PAR_TIMER_SYNC").toString(); } if (map.containsKey("PAR_KEY_ENCRYPT")){ PAR_KEY_ENCRYPT=map.get("PAR_KEY_ENCRYPT").toString(); } if (map.containsKey("PAR_SCOPE")){ PAR_SCOPE=map.get("PAR_SCOPE").toString(); } if (map.containsKey("PAR_DAY_CLEAR")){ PAR_DAY_CLEAR=map.get("PAR_DAY_CLEAR").toString(); } if (map.containsKey("PAR_ADMIN_PASS")){ PAR_ADMIN_PASS=map.get("PAR_ADMIN_PASS").toString(); } if (map.containsKey("PAR_ISACTIVE")){ PAR_ISACTIVE=map.get("PAR_ISACTIVE").toString(); } SystemParam param = new SystemParam(Integer.valueOf(PAR_TIME_SYNC), PAR_KEY_ENCRYPT, Integer.valueOf(PAR_SCOPE), Integer.valueOf(PAR_DAY_CLEAR),PAR_ADMIN_PASS, Integer.valueOf(PAR_ISACTIVE)); AppSetting.getInstance().setParam(param); }catch (Exception ex){} //NEÚ ĐÃ ĐĂNG KÝ THÌ VÔ MAIN,ELSE LOGIN PAR_REG=1 Đăng ký, 0:Ko dk if (mDB.getParam("PAR_REG").toString().equalsIgnoreCase("1")){ if(mDB.getParam("PAR_ISACTIVE").toString().contains("0")) { Toast oToast=Toast.makeText(MainActivity.this,"Thiết bị của bạn chưa Xác nhận",Toast.LENGTH_LONG); oToast.setGravity(Gravity.CENTER,0,0); oToast.show(); } }else{ final Dialog oDlg=new Dialog(MainActivity.this); oDlg.getWindow().setBackgroundDrawableResource(android.R.color.transparent); oDlg.setContentView(R.layout.dialog_yesno); oDlg.setTitle(""); CustomTextView dlgTitle=(CustomTextView) oDlg.findViewById(R.id.dlgTitle); dlgTitle.setText("XÁC NHẬN"); CustomTextView dlgContent=(CustomTextView) oDlg.findViewById(R.id.dlgContent); dlgContent.setText("Thiết bị này chưa đăng ký. Bạn có muốn gửi thông tin đăng ký ?"); CustomBoldTextView btnYes=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonYes); CustomBoldTextView btnNo=(CustomBoldTextView) oDlg.findViewById(R.id.dlgButtonNo); btnYes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, LoginActivity.class)); MainActivity.this.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); oDlg.dismiss(); } }); btnNo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { oDlg.dismiss(); return; } }); oDlg.show(); } } catch (Exception e) { e.printStackTrace(); } } }); } } @Override public void onHttpFailer(Exception e) {} },mUrlGetPara,"HT_PARA").execute(); } //SERVICE private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); if (manager != null) { for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { Log.i ("isMyServiceRunning?", true+""); return true; } } } //Log.i ("isMyServiceRunning?", false+""); return false; } /* //BROADCAST RECEIVER FOR SERVICE //Tạo một BroadcastReceiver lắng nghe service private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(mBroadcastAction)) { String msg=intent.getStringExtra("Data").toString(); //Intent stopIntent = new Intent(MainActivity.this,mimiService.class); //stopService(stopIntent); Toast.makeText(MainActivity.this,msg,Toast.LENGTH_SHORT).show(); } } }; */ }
package RestAssuredKeycloak; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import MyFileUtils.MyFileUtils; import static io.restassured.RestAssured.given; public class KeycloakExtension { private Properties p = null; private static final String PROPERTIES_RESOURCEPATH_DEFAULT = "keycloak.properties"; private static KeyValueStore authData = new KeyValueStore(); private static RequestSpecification originalRequestSpec; public KeycloakExtension setProperties(String propertiesResourcePath) throws RuntimeException { this.p = new Properties(); try { // InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propertiesResourcePath); InputStream inputStream = MyFileUtils.getTestResourceAsStream(propertiesResourcePath); this.p.load(inputStream); inputStream.close(); } catch(IOException e) { e.printStackTrace(); throw new RuntimeException(e); } return this; } public void login() { if (p == null) { setProperties(PROPERTIES_RESOURCEPATH_DEFAULT); } RestAssured.baseURI = p.getProperty("baseurl"); Response response = given(). header("Content-Type", "application/x-www-form-urlencoded"). formParam("client_id",p.get("client_id")). formParam("grant_type",p.get("grant_type")). formParam("username",p.get("username")). formParam("password",p.get("password")). when(). post(p.getProperty("endpoint.login")). then(). assertThat(). statusCode(200). extract(). response(); authData.set(response.getBody().asString()); // backup current RestAssured RequestSpecification originalRequestSpec = RestAssured.requestSpecification; // add bearer token to header of each request that RestAssured sends RequestSpecification bearerTokenRequestSpecification = new RequestSpecBuilder(). addHeader("Authorization", "Bearer " + authData.getValue("access_token")). build(); RestAssured.requestSpecification = bearerTokenRequestSpecification; // // to have every response logged to disk, add log().body() to the this Response Specification // ResponseSpecification alwaysLogResponseSpec = new ResponseSpecBuilder(). // log(LogDetail.BODY). // build(); // // // add it to RestAssured's global responseSpecification to have effect on all responses // RestAssured.responseSpecification = alwaysLogResponseSpec; } public void logout() { given(). formParam("client_id",p.get("client_id")). formParam("refresh_token", authData.getValue("refresh_token")). when(). post(p.getProperty("endpoint.logout")). then(). assertThat(). statusCode(204); if (originalRequestSpec != null) { RestAssured.requestSpecification = originalRequestSpec; } RestAssured.reset(); } public String get(String key) { return p.getProperty(key); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.common.service.impl; import de.hybris.platform.cms2.servicelayer.data.RestrictionData; import de.hybris.platform.cmsfacades.rendering.RestrictionContextProvider; import de.hybris.platform.cmsfacades.common.service.RestrictionAwareService; import org.springframework.beans.factory.annotation.Required; import java.util.function.Supplier; /** * Default implementation of {@link RestrictionAwareService}. Sets restriction information in the session during the execution of a * supplier. */ public class DefaultRestrictionAwareService implements RestrictionAwareService { // -------------------------------------------------------------------------- // Variables // -------------------------------------------------------------------------- private RestrictionContextProvider restrictionContextProvider; // -------------------------------------------------------------------------- // Public API // -------------------------------------------------------------------------- @Override public <T> T execute(RestrictionData restrictionData, Supplier<T> supplier) { try { getRestrictionContextProvider().setRestrictionInContext(restrictionData); return supplier.get(); } finally { getRestrictionContextProvider().removeRestrictionFromContext(); } } // -------------------------------------------------------------------------- // Getters/Setters // -------------------------------------------------------------------------- protected RestrictionContextProvider getRestrictionContextProvider() { return restrictionContextProvider; } @Required public void setRestrictionContextProvider(RestrictionContextProvider restrictionContextProvider) { this.restrictionContextProvider = restrictionContextProvider; } }
package Practical6GUI; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import javax.swing.JTextArea; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class properties extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { properties frame = new properties(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public properties() { setTitle("Visualisation Properties"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); setResizable(false); JButton button = new JButton("< Back"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { main main = new main(); setVisible(false); main.setVisible(true); dispose(); } }); button.setBounds(10, 11, 89, 23); contentPane.add(button); JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setBounds(10, 66, 414, 184); textArea.setText("Cylinders=5000\nCurrent Position=143\nPrevious Position=152\nSequence=86,1470,913,1774,948,1509,1022,1750,130"); contentPane.add(textArea); JLabel lblVisualisationProperties = new JLabel("Visualisation Properties"); lblVisualisationProperties.setHorizontalAlignment(SwingConstants.CENTER); lblVisualisationProperties.setBounds(129, 15, 283, 23); contentPane.add(lblVisualisationProperties); } }
package com.ibeiliao.pay.idgen.impl.entity; import java.io.Serializable; import java.util.Date; /** * 表:t_id_serial ID序列记录 * @author linyi 2016/7/7. */ public class IdSerialPO implements Serializable { private static final long serialVersionUID = 1; /** * ID名称 */ private String idName; /** * 当前值 */ private long value; /** * 步长 */ private long step; /** * ID说明,比如id是做什么用的 */ private String remark; /** * 平台ID */ private int platformId; /** * 创建时间 */ private Date createTime; /** * 更新时间 */ private Date updateTime; public String getIdName() { return idName; } public void setIdName(String idName) { this.idName = idName; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } public long getStep() { return step; } public void setStep(long step) { this.step = step; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public int getPlatformId() { return platformId; } public void setPlatformId(int platformId) { this.platformId = platformId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
package Building; // Ошибка выхода за границы номеров этажей public class FloorIndexOutOfBoundsException extends IndexOutOfBoundsException{ private int detail; public FloorIndexOutOfBoundsException(int a) { detail = a; } public String toString() { return "Введеный номер <" + detail + "> находится вне границы номеров этажей"; } }
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.authentication_controller; import java.security.Principal; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/app") @CrossOrigin public class UsernameSecurityController { @RequestMapping(value = "/username", method = RequestMethod.GET) @ResponseBody public String getUsernameFromToken(Principal principal) { return principal.getName(); } }
package collage; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.nio.ByteBuffer; import com.xuggle.xuggler.IPacket; public class IPacketDatagramOutputStream extends IPacketOutputStream { private InetAddress destAddress; private int destPort; private DatagramSocket socket; private DatagramPacket oPacket; private byte[] buf; int buf_length; private long iPacketNum; /** * Creates an <code>IPacketDatagramOutputStream</code> that will send data to IP * <code>destAddress</code> on port <code>destPort</code> * @param destAddress destination IP address * @param destPort destination port * @throws SocketException if failed to make <code>DatagramSocket</code> */ public IPacketDatagramOutputStream(InetAddress destAddress, int destPort) throws SocketException { this.destAddress = destAddress; this.destPort = destPort; socket = new DatagramSocket(); iPacketNum = 0; } @Override public void close() { if (!socket.isClosed()) socket.close(); } @Override public void write(IPacket packet) throws IOException { IPacketFlat flat = IPacketFlat.encode(packet); ByteBuffer packetBuf = ByteBuffer.wrap(flat.flatData()); SequenceFrameDatagramPacket frame; int iPacketFrameIndex = 0, iPacketNumFrames, iPacketFrameLength; iPacketNumFrames = (int) Math.ceil((double)packetBuf.remaining()/(CollageGlobal.DATAGRAM_PACKET_BUFFER_SIZE - SequenceFrameDatagramPacket.HEADER_SIZE)); while (packetBuf.hasRemaining()) { buf_length = Math.min(CollageGlobal.DATAGRAM_PACKET_BUFFER_SIZE - SequenceFrameDatagramPacket.HEADER_SIZE, packetBuf.remaining()); buf = new byte[buf_length]; packetBuf.get(buf); iPacketFrameLength = buf_length; frame = SequenceFrameDatagramPacket.encode(iPacketNum, iPacketFrameIndex, iPacketNumFrames, iPacketFrameLength, buf); oPacket = new DatagramPacket(frame.frameBytes(), frame.frameBytes().length, destAddress, destPort); socket.send(oPacket); iPacketFrameIndex++; } iPacketNum++; } }
package com.knoldus; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class ReadFileTransformation { String datafile; public static void main(String[] args) { ReadFileTransformation readFileTransformation = new ReadFileTransformation(); System.out.println(readFileTransformation.frequency()); } public Map<String, Integer> frequency() { try { datafile = Files.lines(Paths.get("src/com/knoldus/DataFile.csv")) .collect(Collectors.joining()); } catch (IOException ioException) { ioException.printStackTrace(); } List<String> strings = Stream.of(datafile) .map(w -> w.split("[^\\w]")) .flatMap(Arrays::stream) .collect(Collectors.toList()); Map<String, Integer> frequency = new HashMap<>(); strings.forEach(count -> { frequency.putIfAbsent(count, 0); frequency.put(count, frequency .get(count) + 1); }); return frequency; } }
package org.corbin.client.vo.search; import lombok.Data; import org.corbin.common.base.vo.BaseVo; @Data public class SearchSongVo extends BaseVo { private String searchValue; }
import org.apache.commons.lang.SystemUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.io.*; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.sql.DriverManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; class HdfsReadWrite { FileSystem fs = null; //download from https://github.com/srccodes/hadoop-common-2.2.0-bin/tree/master/bin String home_dir = "C:\\winutils"; HdfsReadWrite(String hdfsUrl, String hdfsUser) throws IOException, URISyntaxException { //disable warning and info message Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.ERROR); if(SystemUtils.IS_OS_WINDOWS) { System.setProperty("hadoop.home.dir", home_dir); } System.setProperty("HADOOP_USER_NAME", hdfsUser); Configuration configuration = new Configuration(); fs = FileSystem.get(new URI(hdfsUrl), configuration); } //HdfsReadwrite String readTextFile(String file, Integer lines) throws IOException { String str = ""; Path srcPath = new Path(file); BufferedReader br = null; br = new BufferedReader(new InputStreamReader(fs.open(srcPath))); String line; int ln = 0; while ((line= br.readLine()) != null) { str = str + line + "\n"; ln++; if(lines > 0 && ln >= lines) { break; } } br.close(); return str; } //readTextFile void writeText(String text, String hdfs_file) throws IOException { Path hdfswritepath = new Path(hdfs_file); FSDataOutputStream outputStream = fs.create(hdfswritepath); outputStream.writeBytes(text); //outputStream.writeUTF(text); outputStream.close(); } //writeText void writeFile(String local_file, String hdfs_file, String local_encode) throws IOException { Path hdfswritepath = new Path(hdfs_file); FSDataOutputStream outputStream = fs.create(hdfswritepath); //BufferedReader br = new BufferedReader(new FileReader(local_file)); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(local_file), local_encode)); String line; long lines = 0; long divide = 10; System.out.println("Copying..."); while ((line = br.readLine()) != null) { outputStream.write(line.getBytes(StandardCharsets.UTF_8)); outputStream.writeBytes("\n"); lines++; if(lines % divide == 0) { System.out.println(lines); divide = divide * 10; } } System.out.println("Total lines: " + lines); outputStream.close(); br.close(); } //writeFile void mkDir(String dir) throws IOException { Path newFolderPath = new Path(dir); if(!fs.exists(newFolderPath)) { fs.mkdirs(newFolderPath); } } //mkDir void rmDir(String dir) throws IOException { Path newFolderPath = new Path(dir); if(fs.exists(newFolderPath)) { fs.delete(newFolderPath, true); } } //rmDir } //HdfsReadWrite class HiveSql { FileSystem fs = null; String home_dir = "C:\\winutils"; Connection dbcon; Statement stmt; HiveSql(String con, String login, String pasw) throws IOException, URISyntaxException, SQLException { //disable warning and info message Logger rootLogger = Logger.getRootLogger(); rootLogger.setLevel(Level.ERROR); if(SystemUtils.IS_OS_WINDOWS) { System.setProperty("hadoop.home.dir", home_dir); } try { Class.forName("org.apache.hive.jdbc.HiveDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); System.exit(1); } dbcon = DriverManager.getConnection(con, login, pasw); } //HiveSql void exec(String sql) throws SQLException { if(stmt != null && !stmt.isClosed()) stmt.close(); stmt = dbcon.createStatement(); stmt.execute(sql); if(stmt != null && !stmt.isClosed()) stmt.close(); } //exec ResultSet select(String sql) throws SQLException { if(stmt != null && !stmt.isClosed()) stmt.close(); stmt = dbcon.createStatement(); return stmt.executeQuery(sql); } //select protected void finalize() { try { stmt.close(); dbcon.close(); } catch (SQLException e) { e.printStackTrace(); } } } //HiveSql
class ExeTest{ public static void main(String[] args) { System.out.println("자바는 내 인생....."); } }
package com.ssgl.service; import com.ssgl.bean.Page; import com.ssgl.bean.Result; import com.ssgl.bean.StudentStatus; import javax.servlet.http.HttpServletRequest; public interface StateService { Page<StudentStatus> selectStatesPage(Integer currentPage, Integer pageSize, HttpServletRequest request) throws Exception; Result addStatus(StudentStatus studentStatus) throws Exception; }
package com.smxknife.java.ex31; import com.smxknife.java2.unsafe.UnsafeWrapper; import sun.misc.Unsafe; /** * @author smxknife * 2020/7/22 */ public class Test { static int a = 3, b; static int e, d = 5; public static void main(String[] args) { String binaryString = Integer.toBinaryString(0x7fffffff); System.out.println(binaryString); System.out.println(binaryString.length()); System.out.println(Integer.toBinaryString(Integer.MIN_VALUE)); System.out.println(0x7fffffff & 0x80000000); Class<int[]> aClass = int[].class; Unsafe unsafe = UnsafeWrapper.unsafe(); int i = unsafe.arrayBaseOffset(aClass); System.out.println("arrayBaseOffset = " + i); int scale = unsafe.arrayIndexScale(aClass); System.out.println("arrayIndexScale = " + scale); Class<long[]> longClass = long[].class; unsafe = UnsafeWrapper.unsafe(); int baseOffset = unsafe.arrayBaseOffset(longClass); System.out.println("arrayBaseOffset = " + baseOffset); int longScale = unsafe.arrayIndexScale(longClass); System.out.println("arrayIndexScale = " + longScale); int i1 = Integer.numberOfLeadingZeros(scale); int i2 = Integer.numberOfTrailingZeros(scale); System.out.println(i1); System.out.println(i2); System.out.println(1 << 15); System.out.println(Integer.toBinaryString(1 << 15)); System.out.println("----------------"); int c = 8; int numZeros = Integer.numberOfLeadingZeros(c); System.out.println(numZeros); int newC = numZeros | (1 << 15); System.out.println(newC); System.out.println(Integer.toBinaryString(c)); System.out.println(Integer.toBinaryString(newC)); System.out.println(a); System.out.println(b); System.out.println(e); System.out.println(d); System.out.println(8 >>> 3); int qwe = 1; System.out.println(qwe <<=1 ); int sshift = 0; int ssize = 1; while (ssize < 16) { ++sshift; ssize <<= 1; } System.out.println("sshift = " + sshift); System.out.println("ssize = " + ssize); } }
package gdu.mall.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import gdu.mall.util.DBUtil; import gdu.mall.vo.Manager; public class ManagerDao { // 승인 대기중인 매니저 목록 public static ArrayList<Manager> selectManagerListByZero() throws Exception { // 1. sql String sql = "SELECT manager_id managerId, manager_date managerDate from manager where manager_level = 0"; // 2. 객체 생성 ArrayList<Manager> list = new ArrayList<>(); // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); // 4. 리턴 while (rs.next()) { Manager m = new Manager(); m.setManagerId(rs.getString("managerId")); m.setManagerDate(rs.getString("managerDate")); list.add(m); } return list; } // 전체 행의 수 public static int totalCount() throws Exception { // 1. sql문 - 클라이언트 테이블에서 전체 데이터 개수를 가져온다. String sql = "select count(*) from manager"; // 2. 초기화 int totalRow = 0; // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); System.out.println(stmt + " <--login() sql"); // stmt 디버깅 ResultSet rs = stmt.executeQuery(); while(rs.next()) { // 데이터 값이 존재한다면 총 개수를 입력해준다. totalRow = rs.getInt("count(*)"); } // 4. 리턴 return totalRow; // 총 데이터 개수 반환 } // 전체 행의 수 public static int totalCount(String searchId) throws Exception { String sql = ""; Connection conn = DBUtil.getConnection(); PreparedStatement stmt = null; int totalRow = 0; if(searchId.equals("")) { sql = "select count(*) from manager"; stmt = conn.prepareStatement(sql); System.out.println(stmt + " <--login() sql"); // stmt 디버깅 } else { sql = "select count(*) from manager where manager_id = ?"; stmt = conn.prepareStatement(sql); System.out.println(stmt + " <--login() sql"); // stmt 디버깅 stmt.setString(1, searchId); } ResultSet rs = stmt.executeQuery(); while(rs.next()) { // 데이터 값이 존재한다면 총 개수를 입력해준다. totalRow = rs.getInt("count(*)"); } // 4. 리턴 return totalRow; // 총 데이터 개수 반환 } // 수정 메서드 public static int updateManagerLevel(int managerNo, int managerLevel) throws Exception { // 1. sql String sql = "UPDATE manager SET manager_level= ? WHERE manager_no = ?"; // 2. 초기화 int rowCnt = 0; // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, managerLevel); stmt.setInt(2, managerNo); System.out.println(stmt + " <--login() sql"); // 디버깅 rowCnt = stmt.executeUpdate(); // 4. 리턴 return rowCnt; } // 삭제 메서드 public static int deleteManager(int managerNo) throws Exception { // 1. sql String sql = "DELETE FROM manager where manager_no = ?"; // 2. 초기화 int rowCnt = 0; // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, managerNo); System.out.println(stmt + " <--login() sql"); // 디버깅 rowCnt = stmt.executeUpdate(); // 4. 리턴 return rowCnt; } // 목록 메서드 public static ArrayList<Manager> selectManagerList() throws Exception { // 1. sql String sql = "SELECT manager_no managerNo, manager_id managerId, manager_name managerName, manager_date managerDate, manager_level managerLevel from manager order by manager_level desc, manager_date asc"; // 2. 객체 생성 ArrayList<Manager> list = new ArrayList<>(); // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); // 4. 리턴 while (rs.next()) { Manager m = new Manager(); m.setManagerNo(rs.getInt("managerNo")); m.setManagerId(rs.getString("managerId")); m.setManagerName(rs.getString("managerName")); m.setManagerDate(rs.getString("managerDate")); m.setManagerLevel(rs.getInt("managerLevel")); list.add(m); } return list; } // 목록 메서드 public static ArrayList<Manager> selectManagerListByPage(int rowPerPage, int beginRow) throws Exception { // 1. sql String sql = "SELECT manager_no managerNo, manager_id managerId, manager_name managerName, manager_date managerDate, manager_level managerLevel from manager order by manager_level desc, manager_date asc limit ?,?"; // 2. 객체 생성 ArrayList<Manager> list = new ArrayList<>(); // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); System.out.println(stmt + "<-- stmt 디버깅"); // sql문 실행 디버깅 stmt.setInt(1, beginRow); stmt.setInt(2, rowPerPage); ResultSet rs = stmt.executeQuery(); // 4. 리턴 while (rs.next()) { Manager m = new Manager(); m.setManagerNo(rs.getInt("managerNo")); m.setManagerId(rs.getString("managerId")); m.setManagerName(rs.getString("managerName")); m.setManagerDate(rs.getString("managerDate")); m.setManagerLevel(rs.getInt("managerLevel")); list.add(m); } return list; } // 목록 메서드 public static ArrayList<Manager> selectManagerListByPage(int rowPerPage, int beginRow, String searchId) throws Exception { ArrayList<Manager> list = new ArrayList<>(); Connection conn = DBUtil.getConnection(); PreparedStatement stmt = null; String sql = ""; if(searchId.equals("")) { sql = "SELECT manager_no managerNo, manager_id managerId, manager_name managerName, manager_date managerDate, manager_level managerLevel from manager order by manager_level desc, manager_date desc limit ?,?"; stmt = conn.prepareStatement(sql); System.out.println(stmt + "<-- stmt 디버깅"); // sql문 실행 디버깅 stmt.setInt(1, beginRow); stmt.setInt(2, rowPerPage); } else { sql = "SELECT manager_no managerNo, manager_id managerId, manager_name managerName, manager_date managerDate, manager_level managerLevel from manager where manager_id = ? order by manager_level desc, manager_date desc limit ?,?"; stmt = conn.prepareStatement(sql); System.out.println(stmt + "<-- stmt 디버깅"); // sql문 실행 디버깅 stmt.setString(1, searchId); stmt.setInt(2, beginRow); stmt.setInt(3, rowPerPage); } ResultSet rs = stmt.executeQuery(); while (rs.next()) { Manager m = new Manager(); m.setManagerNo(rs.getInt("managerNo")); m.setManagerId(rs.getString("managerId")); m.setManagerName(rs.getString("managerName")); m.setManagerDate(rs.getString("managerDate")); m.setManagerLevel(rs.getInt("managerLevel")); list.add(m); } return list; } // 입력 메서드 public static int insertManager(String managerId, String managerPw, String managerName) throws Exception { // 1. sql String sql = "INSERT INTO manager(manager_id, manager_pw, manager_name, manager_date, manager_level) values(?,?,?,now(),0)"; // 2. 초기화 int rowCnt = 0; // 입력 성공시 1, 실패 0 // 3. 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, managerId); stmt.setString(2, managerPw); stmt.setString(3, managerName); System.out.println(stmt + " <--login() sql"); // 디버깅 rowCnt = stmt.executeUpdate(); // 4. 리턴 return rowCnt; } // id 사용가능여부 public static String selectManagerId(String managerId) throws Exception { // 1. sql문 String sql = "SELECT manager_id FROM manager WHERE manager_id = ?"; // 2. 리턴타입 초기화 String returnManagerId = null; // 3. DB 처리 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, managerId); System.out.println(stmt + " <--login() sql"); // 디버깅 ResultSet rs = stmt.executeQuery(); if (rs.next()) { returnManagerId = rs.getString("manager_id"); } return returnManagerId; } // 로그인 메서드 public static Manager login(String managerId, String managerPw) throws Exception { String sql = "SELECT manager_id, manager_name, manager_level FROM manager WHERE manager_id=? AND manager_pw=? AND manager_level>0"; Manager manager = null; Connection conn = DBUtil.getConnection(); // DB 처리 PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, managerId); stmt.setString(2, managerPw); System.out.println(stmt + " <--login() sql"); // 디버깅 ResultSet rs = stmt.executeQuery(); if (rs.next()) { manager = new Manager(); manager.setManagerId(rs.getString("manager_id")); manager.setManagerName(rs.getString("manager_name")); manager.setManagerLevel(rs.getInt("manager_level")); } return manager; } // 카테고리 네임 리스트 메서드 public static ArrayList<String> managerIdList() throws Exception { // 1. sql 문 String sql = "select manager_id managerId from manager order by manager_level desc"; // 2. list 객체 생성 ArrayList<String> list = new ArrayList<>(); // 3. DB 연결 및 SQL문 실행 Connection conn = DBUtil.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); System.out.println(stmt + " <-- sql 디버깅"); // sql 디버깅 ResultSet rs = stmt.executeQuery(); while(rs.next()) { String cn = rs.getString("managerId"); list.add(cn); } return list; } }
package com.test.xiaojian.simple_reader.utils; import android.widget.Toast; import com.test.xiaojian.simple_reader.App; /** * Created by xiaojian on 17-5-11. */ public class ToastUtils { public static void show(String msg){ Toast.makeText(App.getContext(), msg, Toast.LENGTH_SHORT).show(); } }
package com.tenforwardconsulting.bgloc; import android.location.Location; import com.marianhello.bgloc.Config; public class DistanceScore { private Location location; private double am, bm, cm; private double al, bl, cl; private double ah, bh, ch; private double homeLat; private double homeLong; private int score; private double distance; DistanceScore(Config mConfig, Location location){ this.location = location; double homeRadius = mConfig.getHomeRadius(); double csRadius = Math.sqrt(mConfig.getCensusArea())/2; al = -10; bl = 0; cl = 2*homeRadius; am = homeRadius; bm = homeRadius/2; cm = csRadius; ah = csRadius/2; bh = 2*csRadius; ch = Integer.MAX_VALUE; homeLat = mConfig.getHomeLatitude(); homeLong = mConfig.getHomeLatitude(); calculateScore(location); } public void calculateScore(Location location) { double max = 0; distance = distance(location.getLatitude(), location.getLongitude(), homeLat, homeLong); score = scoreExposure(distance, max); } public double distance(double lat1, double lon1, double lat2, double lon2) { double theta, dist; if ((lat1 == lat2) && (lon1 == lon2)) { return 0; } else { theta = lon1 - lon2; dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta)); dist = Math.acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; dist = dist * 1.609344; } return dist*1000; } public double deg2rad(double deg) { return (deg * Math.PI / 180); } public double rad2deg(double rad) { return (rad * 180 / Math.PI); } public double trimf(double x, double a, double b, double c) { // menor que a -> cero, b posicion de pico, mayor que c ->cero return (Math.max(Math.min((x-a)/(b-a), (c-x)/(c-b)), 0)); } public double lowExposure(double x) { return (trimf(x, al, bl, cl)); } public double mediumExposure(double x){ return (trimf(x, am, bm, cm)); } public double highExposure(double x) { return (trimf(x, ah, bh, ch)); } public int scoreExposure(double x, double max) { double low = lowExposure(x); double mid = mediumExposure(x); double high = highExposure(x); max = Math.max(high, Math.max(mid, low)); if(max == low) return (1); if(max == mid) return (2); if(max == high) return (3); return 0; } public int getScore() { return score; } public double getDistance() { return distance; } }
package myproject.game.services.impl; import myproject.game.dao.GameRepository; import myproject.game.enums.GameStatus; import myproject.game.enums.Status; import myproject.game.mappers.GameMapper; import myproject.game.mappers.QuestionMapper; import myproject.game.mappers.UserMapper; import myproject.game.models.dto.GameDto; import myproject.game.models.dto.QuestionDto; import myproject.game.models.dto.SessionDto; import myproject.game.models.dto.UserDto; import myproject.game.models.entities.Game; import myproject.game.responses.GameResponse; import myproject.game.responses.GameResult; import myproject.game.services.GameService; import myproject.game.services.QuestionService; import myproject.game.services.SessionService; import myproject.game.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service public class GameServiceImpl implements GameService { @Autowired private GameRepository gameRepository; @Autowired private UserService userService; @Autowired private QuestionService questionService; @Autowired private SessionService sessionService; @Override public GameDto deleteGame(String auth, Long gameId) { SessionDto sessionDto = sessionService.getSessionInfo(auth); if(!sessionDto.getUser().isAdmin()){ throw new RuntimeException("Not Allowed!!!"); } Game game = gameRepository.findById(gameId).orElse(null); if (game != null) { game.setStatus(Status.NOT_ACTIVE); game = gameRepository.save(game); } return GameMapper.INSTANCE.gameToGameDto(game); } @Override public GameDto findById(Long id) { Game game = gameRepository.findById(id).orElse(null); if (game == null) { throw new RuntimeException("Data is not found"); } return GameMapper.INSTANCE.gameToGameDto(game); } @Override public GameDto updateVisibleWord(GameDto gameDto) { Game game = GameMapper.INSTANCE.gameDtoToGame(gameDto); game.setVisibleWord(gameDto.getVisibleWord()); game = gameRepository.save(game); return GameMapper.INSTANCE.gameToGameDto(game); } @Override public GameResponse newGame(String auth) { SessionDto sessionDto = sessionService.getSessionInfo(auth); GameResponse gameResponse = new GameResponse(); UserDto userDto = userService.findById(sessionDto.getUser().getId()); QuestionDto questionDto = questionService.getRandomQuestionFromList(); String visibleWord = String.join("", Collections.nCopies(questionDto.getAnswer().length(), "*")); Game game = new Game(); game.setUser(UserMapper.INSTANCE.userDtoToUser(userDto)); game.setQuestion(QuestionMapper.INSTANCE.qusetionDtoToQuestion(questionDto)); game.setVisibleWord(visibleWord); game.setStatus(Status.ACTIVE); game.setGameStatus(GameStatus.ACTIVE); game = gameRepository.save(game); gameResponse.setGameId(game.getId()); gameResponse.setQuestion(questionDto.getQuestn()); return gameResponse; } @Override public GameResult currentGame(String auth, String guess) { SessionDto sessionDto = sessionService.getSessionInfo(auth); GameResult result = new GameResult(); List<Game> games = gameRepository.findAllByUserIdAndGameStatus(sessionDto.getUser().getId(), GameStatus.ACTIVE); Game game = games.get(0); QuestionDto question = QuestionMapper.INSTANCE.questionToQuestionDto(game.getQuestion()); String word = question.getAnswer(); String clue = game.getVisibleWord(); char clueArray[] = clue.toCharArray(); if (guess.equals(word) || clue.equals(word)){ game.setVisibleWord(guess); game.setGameStatus(GameStatus.WON); updateVisibleWord(GameMapper.INSTANCE.gameToGameDto(game)); result.setQuestion(question.getQuestn()); result.setMessage("You Won"); result.setAnswer(word); } else { int index; if (!guess.equals(word)) { if (guess.length() == 1) { index = 0; index = word.indexOf(guess, index); if (index != -1) { clueArray[index] = guess.charAt(0); index++; } clue = String.valueOf(clueArray); guess = clue; game.setVisibleWord(guess); updateVisibleWord(GameMapper.INSTANCE.gameToGameDto(game)); result.setQuestion(question.getQuestn()); result.setMessage(guess); } } } return result; } @Override public List<GameDto> findAll() { List<Game> games = gameRepository.findAll(); return GameMapper.INSTANCE.gamesToGameDtos(games); } @Override public List<GameDto> findAllByUserIdAndGameStatus(Long id, GameStatus status) { List<Game> games = gameRepository.findAllByUserIdAndGameStatus(id, status); return GameMapper.INSTANCE.gamesToGameDtos(games); } @Override public List<GameDto> getUserWonGames(String auth) { SessionDto sessionDto = sessionService.getSessionInfo(auth); List<Game> games = gameRepository.findAllByUserIdAndGameStatus(sessionDto.getUser().getId(), GameStatus.WON); return GameMapper.INSTANCE.gamesToGameDtos(games); } }
package com.tencent.mm.ui.widget.a; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; class d$3 implements OnDismissListener { final /* synthetic */ d uKm; d$3(d dVar) { this.uKm = dVar; } public final void onDismiss(DialogInterface dialogInterface) { d.l(this.uKm); } }
package com.ifour.EmployeeManagement.Employee; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EmployeeServiceTest { @Test void getEmployee() { } @Test void getEmployeeById() { } @Test void addNewEmployee() { } @Test void deleteEmployee() { } @Test void updateEmployee() { } }
package com.kh.runLearn.admin.model.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kh.runLearn.admin.model.dao.AdminDAO; import com.kh.runLearn.board.model.dao.BoardDAO; import com.kh.runLearn.board.model.vo.Board; import com.kh.runLearn.board.model.vo.Board_Image; import com.kh.runLearn.common.PageInfo; import com.kh.runLearn.common.model.dao.SearchDAO; import com.kh.runLearn.lecture.model.dao.LectureDAO; import com.kh.runLearn.lecture.model.vo.Lecture; import com.kh.runLearn.member.model.dao.MemberDAO; import com.kh.runLearn.member.model.vo.Member; import com.kh.runLearn.payment.model.dao.PaymentDAO; import com.kh.runLearn.payment.model.service.PaymentService; import com.kh.runLearn.product.model.dao.ProductDAO; @Service("aService") public class AdminServiceImpl implements AdminService { @Autowired private AdminDAO aDAO; @Autowired private BoardDAO bDAO; @Autowired private LectureDAO lDAO; @Autowired private MemberDAO mDAO; @Autowired private PaymentDAO payDAO; @Autowired private ProductDAO pDAO; @Autowired private SearchDAO sDAO; @Override public int allUserCount() {//전체 회원수 조회 return aDAO.allUserCount(); } @Override public int tutorUserCount() {//튜터 회원수 조회 return aDAO.tutorUserCount(); }@Override public int tuteeUserCount() {//튜티 회원수 조회 return aDAO.tuteeUserCount(); }@Override public int blackUserCount() {//블랙회원수 조회 return aDAO.blackUserCount(); } @Override public int modifyUserCount() { // TODO Auto-generated method stub return aDAO.modifyUserCount(); } public int createUserCount() { // TODO Auto-generated method stub return aDAO.createUserCount(); } @Override public int leaveUserCount() {//탈퇴회원 return aDAO.leaveUserCount(); } @Override public int adminUserCount() {//관리자 return aDAO.adminUserCount(); } @Override public ArrayList<Member> adminUserSearchId(String search, PageInfo pi) { return aDAO.adminUserSearchId(search, pi); } @Override public int targetUserUpdate(Member m) {//타겟 회원 정보수정 return aDAO.targetUserUpdate(m); } @Override public ArrayList<Member> allUserList(PageInfo pi) { return aDAO.allUserList(pi); } @Override public ArrayList<Member> allUserListtee(PageInfo pi) { return aDAO.allUserListtee(pi); } @Override public ArrayList<Member> allUserListtor(PageInfo pi) { return aDAO.allUserListtor(pi); } @Override public ArrayList<Member> allUserListbl(PageInfo pi) { return aDAO.allUserListbl(pi); } @Override public ArrayList<Member> allUserListM(PageInfo pi) { return aDAO.allUserListM(pi); } @Override public ArrayList<Member> allUserListY(PageInfo pi) { return aDAO.allUserListY(pi); } @Override public ArrayList<Member> allUserListN(PageInfo pi) { return aDAO.allUserListN(pi); } @Override public ArrayList<Board> boardList(PageInfo pi) { return aDAO.boardList(pi); } @Override public int boardListCount() {//전체 보드 수 가져오기 return aDAO.boardListCount(); } @Override public int boardListCountNot() {//전체 보드 수 가져오기 return aDAO.boardListCountNot(); } @Override public int boardListCountQe() {//전체 보드 수 가져오기 return aDAO.boardListCountQe(); } @Override public int boardListCountSug() {//전체 보드 수 가져오기 return aDAO.boardListCountSug(); } @Override public int boardListCountDecl() {//전체 보드 수 가져오기 return aDAO.boardListCountDecl(); } @Override public int boardListCountA() {// 보드 튜터 신청 수 // TODO Auto-generated method stub return aDAO.boardListCountA(); } @Override public ArrayList<Board> boardListA(PageInfo blc) { // TODO Auto-generated method stub return aDAO.boardListA(blc); } @Override public int addReadCount(int bId) { // TODO Auto-generated method stub return aDAO.addReadCount(bId); } @Override public Board selectBoard(int bId) { // TODO Auto-generated method stub return aDAO.selectBoard(bId); } @Override public int insertBoard(Board b) { // TODO Auto-generated method stub return aDAO.insertBoard(b); } @Override public int targetTrBDelete(Board b) { // TODO Auto-generated method stub return aDAO.targetTrBDelete(b); } @Override public ArrayList applylectureList(PageInfo lpi) { return aDAO.applylectureList(lpi); } @Override public int applyLectureCount() { return aDAO.applyLectureCount(); } }
package spring4.aopdemo; import org.springframework.stereotype.Service; /** * 使用方法规则被拦截类 * @author yrz * */ @Service public class DemoMethodService { public void add() {} }
package com.sinata.rwxchina.basiclib.basic.basicComment; import java.util.List; /** * @author HRR * @datetime 2017/12/18 * @describe 所有分类评论实体类 * @modifyRecord */ public class CommentEntity { /** * id : 1 * createdate : 2017-12-06 16:05:40 * evaluation_score : 5 * evaluation_comment : 可以 * evaluation_comment_pic : ["/Uploads/User/2000028/b73954738020d9e101e9e8487a8819f2.jpg","/Uploads/User/2000028/6095a24210f5ed6134396b855f20341f.jpg","/Uploads/User/2000028/655d0acf4ef371218ec749d771ae31f3.jpg","/Uploads/User/2000028/d65933f6c5bb8a2f7264619fdc4ccbf7.jpg"] * uid : 4 * user_head : * user_name : 测试别删 */ private String id; private String createdate; private String evaluation_score; private String evaluation_comment; private String uid; private String user_head; private String user_name; private List<String> evaluation_comment_pic; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCreatedate() { return createdate; } public void setCreatedate(String createdate) { this.createdate = createdate; } public String getEvaluation_score() { return evaluation_score; } public void setEvaluation_score(String evaluation_score) { this.evaluation_score = evaluation_score; } public String getEvaluation_comment() { return evaluation_comment; } public void setEvaluation_comment(String evaluation_comment) { this.evaluation_comment = evaluation_comment; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUser_head() { return user_head; } public void setUser_head(String user_head) { this.user_head = user_head; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public List<String> getEvaluation_comment_pic() { return evaluation_comment_pic; } public void setEvaluation_comment_pic(List<String> evaluation_comment_pic) { this.evaluation_comment_pic = evaluation_comment_pic; } @Override public String toString() { return "CommentEntity{" + "id='" + id + '\'' + ", createdate='" + createdate + '\'' + ", evaluation_score='" + evaluation_score + '\'' + ", evaluation_comment='" + evaluation_comment + '\'' + ", uid='" + uid + '\'' + ", user_head='" + user_head + '\'' + ", user_name='" + user_name + '\'' + ", evaluation_comment_pic=" + evaluation_comment_pic + '}'; } }
package pl.agh.edu.dp.labirynth.builder; import pl.agh.edu.dp.util.Direction; import pl.agh.edu.dp.labirynth.Maze; import pl.agh.edu.dp.labirynth.elements.Door; import pl.agh.edu.dp.labirynth.elements.Room; import pl.agh.edu.dp.labirynth.elements.Wall; import pl.agh.edu.dp.util.Vector2D; public class StandardMazeBuilder implements MazeBuilder { private Maze currentMaze; public StandardMazeBuilder() { this.currentMaze = new Maze(); } public Maze getCurrentMaze() { return currentMaze; } private Direction commonWall(Vector2D from, Vector2D to) { Vector2D diff = to.subtract(from); return Direction.fromVector(diff); } @Override public void createRoom(Vector2D position) { Room room = new Room(position); for(Direction dir: Direction.values()) { Wall wall; Vector2D neighborPosition = position.add(dir.toVector()); Room neighborRoom = this.currentMaze.getRoom(neighborPosition); if(neighborRoom == null) { wall = new Wall(room); } else { wall = neighborRoom.getSide(dir.opposite()); wall.setRoom2(room); } room.setSide(dir, wall); } this.currentMaze.addRoom(room); } @Override public void createDoors(Vector2D position1, Vector2D position2) { Room room1 = currentMaze.getRoom(position1); Room room2 = currentMaze.getRoom(position2); Direction dir1 = this.commonWall(position1, position2); if(room1 != null && room2 != null && dir1 != null) { Direction dir2 = dir1.opposite(); Door door = new Door(room1, room2); room1.setSide(dir1, door); room2.setSide(dir2, door); } } }
package cn.tedu.jdbc.day02; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; public class PoolThread { public static void main(String[] args) { Thread t1 = new ThreadDemo(5000); Thread t2 = new ThreadDemo(6000); Thread t3 = new ThreadDemo(1000); t1.start(); t2.start(); t3.start(); } } class ThreadDemo extends Thread{ int wait; public ThreadDemo(int wait) { this.wait= wait; } public void run() { Connection conn = null; try { conn = DbUtils.getConnection(); System.out.println(this.getName()+"获得连接:"+conn); Thread.sleep(wait); String sql = "select 'Hello' as a from dual"; Statement stat = conn.createStatement(); ResultSet set = stat.executeQuery(sql); while(set.next()) { System.out.println(set.getString("a")); } System.out.println(wait+"结束"); /* set.close(); stat.close();*/ }catch(Exception ex) { ex.printStackTrace(); throw new RuntimeException(); }finally { DbUtils.close(conn); } } }
package com.hikki.sergey.montecarlo.component; import android.content.Context; import android.content.res.Resources; import android.graphics.Color; import android.support.v7.widget.LinearLayoutCompat; import android.util.AttributeSet; import android.view.Gravity; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.hikki.sergey.montecarlo.R; import static android.util.TypedValue.COMPLEX_UNIT_SP; public class DiscountRateView extends LinearLayout { private Resources mResources; private Context mContext; private InputStdLayout mInputLayout; private IsConstantView mIsConstant; public DiscountRateView(Context context) { super(context, null); mContext = context; mResources = getResources(); this.setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT)); this.setOrientation(LinearLayout.VERTICAL); this.setPadding(0, getDps(8),0,0); LinearLayout mainLayout = new LinearLayout(mContext); mainLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); mainLayout.setPadding(getDps(8),0, getDps(8),0); mainLayout.setOrientation(LinearLayout.HORIZONTAL); this.addView(mainLayout); mIsConstant = new IsConstantView(mContext); mIsConstant.getIsConstant().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mInputLayout.setConstantValue(!isChecked); mIsConstant.setConstant(isChecked); } }); mainLayout.addView(mIsConstant); LinearLayout titleLayout = new LinearLayout(mContext); titleLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); titleLayout.setOrientation(LinearLayout.VERTICAL); titleLayout.setPadding(getDps(8),0,0,0); titleLayout.setGravity(Gravity.TOP); mainLayout.addView(titleLayout); TextView titleTextView = new TextView(mContext); titleTextView.setTextSize(COMPLEX_UNIT_SP, 18); titleTextView.setTextColor(Color.BLACK); titleTextView.setText(mResources.getString(R.string.discount_rate)); titleTextView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); titleLayout.addView(titleTextView); mInputLayout = new InputStdLayout(mContext); titleLayout.addView(mInputLayout); Divider divider = new Divider(mContext, Divider.HORIZONTAL); this.addView(divider); } public DiscountRateView(Context context, AttributeSet attrs) { super(context, attrs); } private int getDps(int pixels){ float scale = mResources.getDisplayMetrics().density; int dpAsPixels = (int) (pixels*scale + 0.5f); return dpAsPixels; } public InputStdLayout getRate(){ return mInputLayout; } public Variable getDiskountRate(){ Variable var = new Variable(); if (mIsConstant.getConstant()){ var.setDevs(0, 0); } else { var.setDevs(mInputLayout.getMaxValue(),mInputLayout.getMinValue()); } var.setValue(mInputLayout.getMainValue()); return var; } }
/* * 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 UserBeans; import java.sql.Date; /** * * @author Yusuf */ public class Komentar { private String cid; private String pid; private String komentator; private String komen; private String email; private String commentDate; public Komentar() { cid=""; pid=""; komentator="guest"; komen=""; email=""; java.util.Date date = new java.util.Date(); commentDate = String.valueOf(date.getYear()+1900)+"-"+String.valueOf(date.getMonth()+1)+"-"+String.valueOf(date.getDate()); } public String getCid() { return cid; } public void setCid(String commentID) { cid = commentID; } public String getPid() { return pid; } public void setPid(String postID) { pid = postID; } public String getKomentator() { return komentator; } public void setKomentator(String komentator) { this.komentator = komentator; } public String getKomen() { return komen; } public void setKomen(String Komen) { komen = Komen; } public String getEmail() { return email; } public void setEmail(String Email) { email = Email; } public String getCommentDate() { return commentDate; } public void setCommentDate(String CommentDate) { commentDate = CommentDate; } }
package edu.mayo.cts2.framework.webapp.rest.query; import java.util.Set; import edu.mayo.cts2.framework.model.command.ResolvedFilter; import edu.mayo.cts2.framework.model.command.ResolvedReadContext; import edu.mayo.cts2.framework.model.service.core.Query; import edu.mayo.cts2.framework.service.command.restriction.MapQueryServiceRestrictions; import edu.mayo.cts2.framework.service.profile.BaseQueryService; import edu.mayo.cts2.framework.service.profile.map.MapQuery; import edu.mayo.cts2.framework.webapp.rest.resolver.FilterResolver; import edu.mayo.cts2.framework.webapp.rest.resolver.ReadContextResolver; public class MapQueryBuilder extends AbstractResourceQueryBuilder<MapQueryBuilder, MapQuery> { private MapQueryServiceRestrictions restrictions; public MapQueryBuilder( BaseQueryService baseQueryService, FilterResolver filterResolver, ReadContextResolver readContextResolver) { super(baseQueryService, filterResolver, readContextResolver); } public MapQueryBuilder addRestrictions(MapQueryServiceRestrictions restrictions){ this.restrictions = restrictions; return this.getThis(); } @Override protected MapQueryBuilder getThis() { return this; } @Override public MapQuery build() { final DefaultResourceQuery query = new DefaultResourceQuery(); return new MapQuery(){ @Override public Query getQuery() { return query.getQuery(); } @Override public Set<ResolvedFilter> getFilterComponent() { return query.getFilterComponent(); } @Override public ResolvedReadContext getReadContext() { return query.getReadContext(); } @Override public MapQueryServiceRestrictions getRestrictions() { return restrictions; } }; } }
package 线程; /* * main ------{} * Thread:线程类,线程有自己的任务,在定义线程类的时候,需要实现;?如run() * 一、继承Thread类来创建 * 1、继承 * 2、复写run():任务 子类 * 3、实例化:线程对象 * 4、启动线程:start * * */ class Monkey extends Thread{//1\继承thread String name; public Monkey(String name) { super(); this.name=name; } public void fight(){ for (int i = 0; i < 11; i++) { System.out.println(name+"打败第"+i+"个天兵天将"); } } public void run(){//复写run方法 fight(); } } public class NotThread { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Monkey m1=new Monkey("第一个孙悟空");//实例化对象 Monkey m2=new Monkey("第二个孙悟空"); Monkey m3=new Monkey("第三个孙悟空"); m1.setName("线程一");//? m1.start();//启动线程 m2.start(); m3.start(); System.out.println("============="); System.out.println(m1.getName()); } }
package com.itheima.service.impl; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.itheima.constant.MessageConstant; import com.itheima.dao.CheckItemDao; import com.itheima.dao.PermissionDao; import com.itheima.entity.PageResult; import com.itheima.entity.Result; import com.itheima.pojo.CheckItem; import com.itheima.pojo.Permission; import com.itheima.service.CheckItemService; import com.itheima.service.PermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 检查项业务层 具体实现 */ @Transactional @Service(interfaceClass = PermissionService.class) //指定创建服务的包 public class PermissionServiceImpl implements PermissionService { @Autowired private PermissionDao permissionDao; /** * 新增检查项 * * @param permission */ @Override public void add(Permission permission) { permissionDao.add(permission); } /** * 检查项分页查询 * Result: * { * flag:true * message:'xxxxx', * data:{ * total:100, * rows:[ * {xxxxxx}, * {yyyyyy} * ] * } * } */ @Override public Result findPage(String queryString, Integer currentPage, Integer pageSize) { //PageHelper分页对象 调用静态方法startPage实现分页 //传入两个参数 PageNum 当前页面 pageSize:每页显示记录数 PageHelper.startPage(currentPage, pageSize); //紧跟着第二行就是需要分页的查询语句 select * from t_checkitem limit 0,10 //pageHelper插件拦截查询表语句,动态为语句添加分页条件,查询分页数据 Page<Permission> permissionPage = permissionDao.selectByCondition(queryString);//返回结果的 插件定义Page<T> return new Result(true, MessageConstant.QUERY_CHECKITEM_SUCCESS, new PageResult(permissionPage.getTotal(), permissionPage.getResult())); } /** * 检查项删除 * * @return */ @Override public void deleteById(Integer itemId) { //1.根据检查项id查询检查项和检查组的中间表 int count = permissionDao.findCountByCheckItemId(itemId); //2.如果数据存入抛出异常 if (count > 0) { throw new RuntimeException("检查项和检查组已经关联,无法删除"); } //3.如果数据不存在直接删除 permissionDao.deleteById(itemId); } /** * 根据检查项id查询检查项数据 * * @return */ @Override public Permission findById(Integer id) { return permissionDao.findById(id); } /** * 编辑检查项数据 * * @return */ @Override public void edit(Permission permission) { permissionDao.edit(permission); } @Override public List<Permission> findAll() { return permissionDao.findAll(); } }
/* * 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.example.codetribe1.constructionappsuite.dto; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @author aubreyM */ public class ContractorClaimDTO implements Serializable { private static final long serialVersionUID = 1L; private Integer contractorClaimID, projectEngineerID, engineerID, projectID, taskID, siteCount; private String claimNumber, projectName, engineerName, taskName; private Date claimDate; private List<ContractorClaimSiteDTO> contractorClaimSiteList; public ContractorClaimDTO() { } public Integer getSiteCount() { return siteCount; } public void setSiteCount(Integer siteCount) { this.siteCount = siteCount; } public Integer getProjectEngineerID() { return projectEngineerID; } public void setProjectEngineerID(Integer projectEngineerID) { this.projectEngineerID = projectEngineerID; } public Integer getContractorClaimID() { return contractorClaimID; } public void setContractorClaimID(Integer contractorClaimID) { this.contractorClaimID = contractorClaimID; } public String getClaimNumber() { return claimNumber; } public void setClaimNumber(String claimNumber) { this.claimNumber = claimNumber; } public Date getClaimDate() { return claimDate; } public void setClaimDate(Date claimDate) { this.claimDate = claimDate; } public List<ContractorClaimSiteDTO> getContractorClaimSiteList() { return contractorClaimSiteList; } public void setContractorClaimSiteList(List<ContractorClaimSiteDTO> contractorClaimSiteList) { this.contractorClaimSiteList = contractorClaimSiteList; } public Integer getEngineerID() { return engineerID; } public void setEngineerID(Integer engineerID) { this.engineerID = engineerID; } public Integer getProjectID() { return projectID; } public void setProjectID(Integer projectID) { this.projectID = projectID; } public Integer getTaskID() { return taskID; } public void setTaskID(Integer taskID) { this.taskID = taskID; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getEngineerName() { return engineerName; } public void setEngineerName(String engineerName) { this.engineerName = engineerName; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } @Override public int hashCode() { int hash = 0; hash += (contractorClaimID != null ? contractorClaimID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof ContractorClaimDTO)) { return false; } ContractorClaimDTO other = (ContractorClaimDTO) object; if ((this.contractorClaimID == null && other.contractorClaimID != null) || (this.contractorClaimID != null && !this.contractorClaimID.equals(other.contractorClaimID))) { return false; } return true; } @Override public String toString() { return "com.boha.monitor.data.ContractorClaim[ contractorClaimID=" + contractorClaimID + " ]"; } }
package com.pfchoice.springboot.repositories; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; import com.pfchoice.springboot.model.HedisMeasureGroup; import com.pfchoice.springboot.repositories.intf.RecordDetailsAwareRepository; @Repository public interface HedisMeasureGroupRepository extends PagingAndSortingRepository<HedisMeasureGroup, Integer>, JpaSpecificationExecutor<HedisMeasureGroup>, RecordDetailsAwareRepository<HedisMeasureGroup, Integer> { public HedisMeasureGroup findById(Integer id); /** * * @param code * @return */ HedisMeasureGroup findByCode(String code); }
/* * Copyright (c) 2017. Universidad Politecnica de Madrid * * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es> * */ package org.librairy.modeler.dao; import es.cbadenes.lab.test.IntegrationTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.librairy.boot.storage.exception.DataNotFound; import org.librairy.modeler.lda.Application; import org.librairy.modeler.lda.dao.ClusterDao; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * Created by cbadenes on 13/01/16. */ @Category(IntegrationTest.class) @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = Application.class) public class ClusterDaoTest { private static final Logger LOG = LoggerFactory.getLogger(ClusterDaoTest.class); @Autowired ClusterDao clusterDao; @Test public void getClusters() throws InterruptedException, DataNotFound { String domainUri = "http://librairy.org/domains/user4"; String documentUri = "http://librairy.org/items/doc1"; List<Long> clusters = clusterDao.getClusters(domainUri, documentUri); LOG.info("Clusters: " + clusters); } }
package mobi.wrt.oreader.app.html; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.select.Elements; import org.jsoup.select.NodeTraversor; import org.jsoup.select.NodeVisitor; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import by.istin.android.xcore.utils.Holder; import by.istin.android.xcore.utils.StringUtil; import mobi.wrt.oreader.app.html.elements.MediaElement; import mobi.wrt.oreader.app.html.elements.PageElement; import mobi.wrt.oreader.app.html.elements.TextElement; import mobi.wrt.oreader.app.html.elements.UrlMediaElement; public class MediaContentRecognizer { public static final String YOUTUBE_REGEX = "https?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:youtu\\.be\\/|youtube\\.com\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w]*(?:['\"][^<>]*>|<\\/a>))[?=&+%\\w]*"; public static final String YOUTUBE_VIDEO_ID_REGEX = "^.*((youtu.be" + "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; public static final Pattern YOUTUBE_PATTERN = Pattern.compile(YOUTUBE_REGEX, Pattern.CASE_INSENSITIVE); public static final Pattern YOUTUBE_VIDEO_ID_PATTERN = Pattern.compile(YOUTUBE_VIDEO_ID_REGEX, Pattern.CASE_INSENSITIVE); public static final String URL_REGEX = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)"; public static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX, Pattern.CASE_INSENSITIVE); //public static final String IMAGE_SELECTOR = "[height][width][src],a>img"; public static final String IMAGE_SELECTOR = "[src],a>img"; public static List<PageElement> recognize(String html) { if (StringUtil.isEmpty(html)) { return Collections.emptyList(); } html = html.replaceAll("<p>","<br/>").replaceAll("<\\/p>","<br/>"); Document document = Jsoup.parseBodyFragment(html); Element body = document.body(); final Elements objs = document.select(IMAGE_SELECTOR); final List<PageElement> list = new ArrayList<PageElement>(); final StringBuilder builder = new StringBuilder(); final Holder<Integer> objPositionHolder = new Holder<Integer>(); final Holder<Element> objHolder = new Holder<Element>(); if (objs == null || objs.isEmpty()) { objPositionHolder.set(-1); } else { objPositionHolder.set(0); objHolder.set(objs.get(0)); } new NodeTraversor(new NodeVisitor() { private boolean isSkipNext = false; private List<Node> listIgnore = new ArrayList<Node>(); @Override public void head(Node node, int i) { if (listIgnore.contains(node)){ return; } if (node instanceof TextNode) { if (isSkipNext) { return; } if (builder.length() > 0) { builder.append(" "); } TextNode textNode = (TextNode) node; String wholeText = textNode.getWholeText(); builder.append(wholeText.trim()); } else if (node instanceof Element) { Element element = (Element)node; String tagName = element.tag().getName(); if (element.isBlock() || tagName.equals("br")) { builder.append("<br/>"); }; if (objHolder.get() != null && element.equals(objHolder.get())) { if (builder.length() > 0) { list.add(new TextElement(builder.toString())); builder.setLength(0); } if (element.parent().tag().getName().equalsIgnoreCase("a")) { list.add(new UrlMediaElement(element)); } else { list.add(new MediaElement(element)); } Integer position = objPositionHolder.get(); position = position + 1; if (position < objs.size()) { objHolder.set(objs.get(position)); objPositionHolder.set(position); } } else if (isSpannedCanHandleTag(tagName, element)) { if (builder.length() > 0) { builder.append(" "); } appendAndSkip(element); } } } public void appendAndSkip(Element element) { listIgnore.addAll(element.childNodes()); builder.append(element.toString()); isSkipNext = true; } @Override public void tail(Node node, int i) { isSkipNext = false; } }).traverse(body); if (builder.length() > 0) { list.add(new TextElement(builder.toString())); } return list; } public static boolean isSpannedCanHandleTag(String tagName, Element element) { return (tagName.equalsIgnoreCase("a") || tagName.equalsIgnoreCase("strong") || tagName.equalsIgnoreCase("b") || tagName.equalsIgnoreCase("em") || tagName.equalsIgnoreCase("cite") || tagName.equalsIgnoreCase("dfn") || tagName.equalsIgnoreCase("i") || tagName.equalsIgnoreCase("big") || tagName.equalsIgnoreCase("small") || tagName.equalsIgnoreCase("font") || tagName.equalsIgnoreCase("blockquote") || tagName.equalsIgnoreCase("tt") || tagName.equalsIgnoreCase("u") || tagName.equalsIgnoreCase("sup") || tagName.equalsIgnoreCase("sub") || (tagName.length() == 2 && Character.toLowerCase(tagName.charAt(0)) == 'h' && tagName.charAt(1) >= '1' && tagName.charAt(1) <= '6')) && !StringUtil.isEmpty(element.text().trim()) ; } public static String findAllImages(boolean withVideo, String... sources) { StringBuilder stringBuilder = new StringBuilder(); for (String source : sources) { if (!StringUtil.isEmpty(source)) { Document summaryDocument = Jsoup.parse(source); Elements imgs = summaryDocument.select("img[src]"); if (imgs != null && imgs.size() > 0) { for (Element element : imgs) { String src = element.attr("src"); if (src.endsWith(".png") || src.endsWith(".jpg") || src.endsWith(".jpeg") || src.endsWith(".gif")) { stringBuilder.append(element.toString()); } } } if (withVideo) { List<String> urls = extractUrls(source); if (urls != null) { for (String url : urls) { stringBuilder.append(findYouTubeImage(url)); } } } } } return stringBuilder.toString(); } public static List<String> extractUrls(String value) { if (StringUtil.isEmpty(value)) return null; List<String> result = new ArrayList<String>(); Matcher m = URL_PATTERN.matcher(value); while (m.find()) { result.add(value.substring(m.start(0), m.end(0))); } return result; } private static String findYouTubeImage(String youtubeUrl) { List<String> urls = new ArrayList<String>(); Matcher matcher = YOUTUBE_PATTERN.matcher(youtubeUrl); while (matcher.find()) { urls.add(matcher.group()); } if (urls != null && urls.size() > 0) { StringBuilder stringBuilder = new StringBuilder(); for (String url : urls) { String v = getYoutubeVideoId(url); if (!StringUtil.isEmpty(v)) { stringBuilder.append("<img src=\"http://img.youtube.com/vi/" + v + "/0.jpg\"></img>"); } } return stringBuilder.toString(); } return StringUtil.EMPTY; } public static String getYoutubeVideoId(String youtubeUrl) { String videoId = StringUtil.EMPTY; if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) { CharSequence input = youtubeUrl; Matcher matcher = YOUTUBE_VIDEO_ID_PATTERN.matcher(input); if (matcher.matches()) { String groupIndex1 = matcher.group(7); if (groupIndex1 != null && groupIndex1.length() == 11) videoId = groupIndex1; } } return videoId; } }
package demo.plagdetect.calfeature; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; public class TestCalNumSim { /** * @Author duanding * @Description 测试从文件提取数值常量 * @Date 5:30 PM 2019/9/24 * @Param [] * @return void **/ @Test public void testExtractNumFromFile(){ File file = new File("/Users/dd/Desktop/TryData/ALUTest1.java"); List<String> expectList = new ArrayList<>(); expectList.add("8"); expectList.add("8"); expectList.add("8"); expectList.add("4"); expectList.add("8"); expectList.add("8"); expectList.add("12"); expectList.add("8"); expectList.add("1200"); assertEquals(expectList,CalNumSim.extractNumFromFile(file)); } /** * @Author duanding * @Description 测试检测数值 * @Date 7:34 PM 2019/9/23 * @Param [] * @return void **/ @Test public void testDetectNum(){ String s1 = "12.5"; assertEquals(true,CalNumSim.detectNum(s1)); String s2 = "-0.423"; assertEquals(true,CalNumSim.detectNum(s2)); } /** * @Author duanding * @Description 测试根据两个选手数值常量列表计算相似度 * @Date 5:31 PM 2019/9/24 * @Param [] * @return void **/ @Test public void testCalNumSim(){ List<String> numList1 = new ArrayList(); numList1.add("8"); numList1.add("8"); numList1.add("-5.3"); numList1.add("12"); numList1.add("3.54"); numList1.add("-0.54"); numList1.add("0.54"); numList1.add("22.54"); List<String> numList2 = new ArrayList<>(); numList2.add("8"); numList2.add("8"); numList2.add("8"); numList2.add("-0.54"); numList2.add("-21"); assertEquals(0.375,CalNumSim.calNumSim(numList1,numList2),0.001); } }
package com.lingnet.vocs.service.baseinfo; import java.util.List; import com.lingnet.common.service.BaseService; import com.lingnet.vocs.entity.Dictionary; import com.lingnet.vocs.entity.DictionaryD; /** * 数据字典service * @ClassName: DataDictionaryService * @Description: TODO * @author 刘殿飞 * @date 2014-12-15 下午2:42:49 * */ public interface DataDictionaryService extends BaseService<Dictionary, String>{ /** * * @Title: getAllOrderBySort * @return * List<Dictionary> * @author fanxw * @since 2014-12-15 V 1.0 modify by 刘殿飞 */ public List<Dictionary> getAllOrderBySort(); /** * * @Title: getSearchDataByCode 根据Code数组 获取列表页的搜索筛选数据 * @param codes Code数组 * @return * String * @author adam * @since 2016-1-13 V 1.0 */ public String getSearchDataByCode(String[] codes); /** * * @Title: getSearchDataByCode 根据Code数组 获取列表页的搜索筛选数据 * @param codes Code数组 * @param codesName * @param codesId * @return * String * @author adam * @since 2016-1-28 V 1.0 */ public String getSearchDataByCode(String[] codes, String[] codesName,String[] codesId); /** * * @Title: getFormatterDataByCode 根据Code数组数据字典数据 用于jqGrid列表中的字段格式化 * @param codes * @return * String * @author adam * @since 2016-1-19 V 1.0 */ public String getFormatterDataByCode(String[] codes); /** * * @Title: getFormatterDataByCode 根据Code数组数据字典数据 用于jqGrid列表中的字段格式化 * @param codes * @param hasOther 是否有其他选项 * @return * String * @author adam * @since 2016-1-21 V 1.0 */ String getFormatterDataByCode(String[] codes, Boolean hasOther); /** * * @Title: getDictionary 根据code和value查询数据字典子表 * @param code * @param value * @return * DictionaryD * @author adam * @since 2016-2-17 V 1.0 */ public DictionaryD getDictionary(String code , String value ); }
package com.yinghai.a24divine_user.bean; import java.util.List; /** * @author Created by:fanson * Created Time: 2017/11/21 11:14 * Describe:商品详情Bean */ public class ProductDetailBean { /** * code : 1 * msg : 操作成功 * data : {"tfProduct":{"imgList":[{"imgTmpId":18,"itAbsolute":"","itAppPath":"","itCreateTime":"","itIsUser":false,"isCollection":true,"itKeyId":0,"itMasterId":0,"itType":1,"itUpdateTime":"","itUrl":"http://192.168.0.165:8080/file\\images/article/\\2\\Q6fZ7_fileName.jpg"}],"pAttribution":"浙江金华","pCreateTime":"2017-10-24 13:36:32","pDeals":0,"pDelete":false,"pFreeShipping":true,"pHot":0,"pImg":"","pIntroduction":"带金星小叶紫檀深紫发黑的色泽,苍老的沧桑质感浓厚。油脂充足,料质油润细腻,整体荧光质感强烈。","pMasterId":1,"pName":"名木香府老料小叶紫檀满金星手串20毫米男女款满金星老料紫檀手串手链 紫檀Q211款 编号Q211-05","pOffline":false,"pPrice":1800,"pSize":"18-25毫米(18-25mm)","pTotal":7,"pUpdateTime":"2017-11-09 18:40:20","productId":1}} */ private int code; private String msg; private DataBean data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { /** * tfProduct : {"imgList":[{"imgTmpId":18,"itAbsolute":"","itAppPath":"","itCreateTime":"","itIsUser":false,"isCollection":true,"itKeyId":0,"itMasterId":0,"itType":1,"itUpdateTime":"","itUrl":"http://192.168.0.165:8080/file\\images/article/\\2\\Q6fZ7_fileName.jpg"}],"pAttribution":"浙江金华","pCreateTime":"2017-10-24 13:36:32","pDeals":0,"pDelete":false,"pFreeShipping":true,"pHot":0,"pImg":"","pIntroduction":"带金星小叶紫檀深紫发黑的色泽,苍老的沧桑质感浓厚。油脂充足,料质油润细腻,整体荧光质感强烈。","pMasterId":1,"pName":"名木香府老料小叶紫檀满金星手串20毫米男女款满金星老料紫檀手串手链 紫檀Q211款 编号Q211-05","pOffline":false,"pPrice":1800,"pSize":"18-25毫米(18-25mm)","pTotal":7,"pUpdateTime":"2017-11-09 18:40:20","productId":1} */ private TfProductBean tfProduct; public TfProductBean getTfProduct() { return tfProduct; } public void setTfProduct(TfProductBean tfProduct) { this.tfProduct = tfProduct; } public static class TfProductBean { /** * imgList : [{"imgTmpId":18,"itAbsolute":"","itAppPath":"","itCreateTime":"","itIsUser":false,"isCollection":true,"itKeyId":0,"itMasterId":0,"itType":1,"itUpdateTime":"","itUrl":"http://192.168.0.165:8080/file\\images/article/\\2\\Q6fZ7_fileName.jpg"}] * pAttribution : 浙江金华 * pCreateTime : 2017-10-24 13:36:32 * pDeals : 0 * pDelete : false * pFreeShipping : true * pHot : 0 * pImg : * pIntroduction : 带金星小叶紫檀深紫发黑的色泽,苍老的沧桑质感浓厚。油脂充足,料质油润细腻,整体荧光质感强烈。 * pMasterId : 1 * pName : 名木香府老料小叶紫檀满金星手串20毫米男女款满金星老料紫檀手串手链 紫檀Q211款 编号Q211-05 * pOffline : false * pPrice : 1800 * pSize : 18-25毫米(18-25mm) * pTotal : 7 * pUpdateTime : 2017-11-09 18:40:20 * productId : 1 */ private String pAttribution; private String pCreateTime; private int pDeals; private boolean pDelete; private boolean pFreeShipping; private int pHot; private String pImg; private String pIntroduction; private int pMasterId; private String pName; private boolean pOffline; private int pPrice; private String pSize; private int pTotal; private String pUpdateTime; private int productId; private List<ImgListBean> imgList; public String getPAttribution() { return pAttribution; } public void setPAttribution(String pAttribution) { this.pAttribution = pAttribution; } public String getPCreateTime() { return pCreateTime; } public void setPCreateTime(String pCreateTime) { this.pCreateTime = pCreateTime; } public int getPDeals() { return pDeals; } public void setPDeals(int pDeals) { this.pDeals = pDeals; } public boolean isPDelete() { return pDelete; } public void setPDelete(boolean pDelete) { this.pDelete = pDelete; } public boolean isPFreeShipping() { return pFreeShipping; } public void setPFreeShipping(boolean pFreeShipping) { this.pFreeShipping = pFreeShipping; } public int getPHot() { return pHot; } public void setPHot(int pHot) { this.pHot = pHot; } public String getPImg() { return pImg; } public void setPImg(String pImg) { this.pImg = pImg; } public String getPIntroduction() { return pIntroduction; } public void setPIntroduction(String pIntroduction) { this.pIntroduction = pIntroduction; } public int getPMasterId() { return pMasterId; } public void setPMasterId(int pMasterId) { this.pMasterId = pMasterId; } public String getPName() { return pName; } public void setPName(String pName) { this.pName = pName; } public boolean isPOffline() { return pOffline; } public void setPOffline(boolean pOffline) { this.pOffline = pOffline; } public int getPPrice() { return pPrice; } public void setPPrice(int pPrice) { this.pPrice = pPrice; } public String getPSize() { return pSize; } public void setPSize(String pSize) { this.pSize = pSize; } public int getPTotal() { return pTotal; } public void setPTotal(int pTotal) { this.pTotal = pTotal; } public String getPUpdateTime() { return pUpdateTime; } public void setPUpdateTime(String pUpdateTime) { this.pUpdateTime = pUpdateTime; } public int getProductId() { return productId; } public void setProductId(int productId) { this.productId = productId; } public List<ImgListBean> getImgList() { return imgList; } public void setImgList(List<ImgListBean> imgList) { this.imgList = imgList; } public static class ImgListBean { /** * imgTmpId : 18 * itAbsolute : * itAppPath : * itCreateTime : * itIsUser : false * isCollection : true * itKeyId : 0 * itMasterId : 0 * itType : 1 * itUpdateTime : * itUrl : http://192.168.0.165:8080/file\images/article/\2\Q6fZ7_fileName.jpg */ private int imgTmpId; private String itAbsolute; private String itAppPath; private String itCreateTime; private boolean itIsUser; private boolean isCollection; private int itKeyId; private int itMasterId; private int itType; private String itUpdateTime; private String itUrl; public int getImgTmpId() { return imgTmpId; } public void setImgTmpId(int imgTmpId) { this.imgTmpId = imgTmpId; } public String getItAbsolute() { return itAbsolute; } public void setItAbsolute(String itAbsolute) { this.itAbsolute = itAbsolute; } public String getItAppPath() { return itAppPath; } public void setItAppPath(String itAppPath) { this.itAppPath = itAppPath; } public String getItCreateTime() { return itCreateTime; } public void setItCreateTime(String itCreateTime) { this.itCreateTime = itCreateTime; } public boolean isItIsUser() { return itIsUser; } public void setItIsUser(boolean itIsUser) { this.itIsUser = itIsUser; } public boolean isIsCollection() { return isCollection; } public void setIsCollection(boolean isCollection) { this.isCollection = isCollection; } public int getItKeyId() { return itKeyId; } public void setItKeyId(int itKeyId) { this.itKeyId = itKeyId; } public int getItMasterId() { return itMasterId; } public void setItMasterId(int itMasterId) { this.itMasterId = itMasterId; } public int getItType() { return itType; } public void setItType(int itType) { this.itType = itType; } public String getItUpdateTime() { return itUpdateTime; } public void setItUpdateTime(String itUpdateTime) { this.itUpdateTime = itUpdateTime; } public String getItUrl() { return itUrl; } public void setItUrl(String itUrl) { this.itUrl = itUrl; } } } } }
package com.beiyelin.messageportal.interceptor; import com.beiyelin.account.security.JwtTokenService; import com.beiyelin.common.utils.StrUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.server.ServerHttpRequest; import org.springframework.http.server.ServerHttpResponse; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor; import sun.security.acl.PrincipalImpl; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.security.Principal; import java.util.Map; import static java.lang.String.format; /** * @Description: 通常这个拦截器可以用来判断用户合法性等 * @Author: newmann * @Date: Created in 22:20 2018-01-23 */ @Slf4j public class CustomHandshakeInterceptor extends HttpSessionHandshakeInterceptor { private JwtTokenService jwtTokenService; public CustomHandshakeInterceptor(JwtTokenService tokenService){ this.jwtTokenService = tokenService; } @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { log.info("握手前"+request.getURI()); //http协议转换websoket协议进行前,通常这个拦截器可以用来判断用户合法性等 //鉴别用户 通过含在url中的token进行验证。 ServletServerHttpRequest req = (ServletServerHttpRequest) request; String token = req.getServletRequest().getParameter(jwtTokenService.getTokenHeader()); if (!StrUtils.isEmpty(token)) { // todo 这里只使用简单的token来判断是否已经登录 String username = token; //jwtTokenService.getUsernameFromToken(token); log.info(format("用户 %s 握手成功。",username)); Principal principal = new PrincipalImpl(username); //保存认证用户 attributes.put("user", principal); return true; }else { log.warn("用户未登录,握手失败!"); return false; } // Principal principal = request.getPrincipal(); // if (request instanceof HttpServletRequest) { // HttpServletRequest servletRequest = (HttpServletRequest) request; //这句话很重要如果getSession(true)会导致移动端无法握手成功 //request.getSession(true):若存在会话则返回该会话,否则新建一个会话。 //request.getSession(false):若存在会话则返回该会话,否则返回NULL //HttpSession session = servletRequest.getServletRequest().getSession(false); // HttpSession session = servletRequest.getServletRequest().getSession(); // String authHeader = servletRequest.getHeader(jwtTokenService.getTokenHeader()); // if (!StrUtils.isEmpty(authHeader)) { //这里只使用简单的token来判断是否已经登录 // return super.beforeHandshake(request, response, wsHandler, attributes); // }else { // log.warn("用户未登录,握手失败!"); // return false; // } // } // if (principal == null){ // log.warn("用户未登录,握手失败!"); // return false; // }else{ // return super.beforeHandshake(request, response, wsHandler, attributes); // } // return false; } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { //握手成功后,通常用来注册用户信息 log.info("握手结束"); super.afterHandshake(request, response, wsHandler, ex); } }
package com.tencent.mm.plugin.freewifi.ui; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.model.au; import com.tencent.mm.plugin.freewifi.d.a; import com.tencent.mm.plugin.freewifi.model.d; import com.tencent.mm.protocal.c.ep; import com.tencent.mm.sdk.platformtools.x; class FreewifiWeChatNoAuthStateUI$1 implements e { final /* synthetic */ FreewifiWeChatNoAuthStateUI jot; FreewifiWeChatNoAuthStateUI$1(FreewifiWeChatNoAuthStateUI freewifiWeChatNoAuthStateUI) { this.jot = freewifiWeChatNoAuthStateUI; } public final void a(int i, int i2, String str, l lVar) { au.DF().b(640, this); x.i("MicroMsg.FreeWifi.FreewifiWeChatNoAuthStateUI", "onSceneEnd, errType = %d, errCode = %d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)}); if (i == 0 && i2 == 0) { x.i("MicroMsg.FreeWifi.FreewifiWeChatNoAuthStateUI", "check ap ok"); ep aOY = ((a) lVar).aOY(); if (aOY != null) { x.i("MicroMsg.FreeWifi.FreewifiWeChatNoAuthStateUI", "backPageInfo appid: %s, nickName: %s, userName: %s, finishActionCode: %d, finishUrl: %s, signature: %s", new Object[]{aOY.rbW, aOY.hcS, aOY.hbL, Integer.valueOf(aOY.rfa), aOY.rfb, aOY.eJK}); this.jot.bPS = aOY.rbW; this.jot.jkJ = aOY.hcS; this.jot.bPg = aOY.hbL; this.jot.jnW = aOY.rfa; this.jot.jnX = aOY.rfb; this.jot.signature = aOY.eJK; this.jot.jnY = aOY.rfc; } d.a(this.jot.ssid, 2, this.jot.getIntent()); return; } x.e("MicroMsg.FreeWifi.FreewifiWeChatNoAuthStateUI", "check ap failed : rssi is : %d, mac : %s, ssid is : %s", new Object[]{Integer.valueOf(FreewifiWeChatNoAuthStateUI.a(this.jot)), FreewifiWeChatNoAuthStateUI.b(this.jot), FreewifiWeChatNoAuthStateUI.c(this.jot)}); d.a(this.jot.ssid, -2014, this.jot.getIntent()); d.Ca(FreewifiWeChatNoAuthStateUI.c(this.jot)); } }
package b; public class A { public static void main(String[] args) { test1(); test2(); test3(); test4(); } public static void test1() { System.out.println("print abc1"); } public static void test2() { System.out.println("print abc2"); } public static void test3() { System.out.println("print abc3"); } public static void test4() { System.out.println("this is for print testing"); } }
package com.ehootu.correct.service; import java.util.List; import java.util.Map; import com.ehootu.correct.model.IncontrollableDrugControlEntity; /** * 失控吸毒类重点人员动态管控工作记录 * * @author yinyujun * @email * @date 2017-09-21 14:42:32 */ public interface IncontrollableDrugControlService { IncontrollableDrugControlEntity queryObject(String id); List<IncontrollableDrugControlEntity> queryList(Map<String, Object> map); int queryTotal(Map<String, Object> map); void save(IncontrollableDrugControlEntity incontrollableDrugControl, String pageName); void update(IncontrollableDrugControlEntity incontrollableDrugControl); void delete(String id); void deleteBatch(Integer[] ids); }
package com.camas.irv.race; import com.camas.irv.candidate.Candidate; import com.camas.irv.voter.Voter; import java.util.List; public interface RaceService { List<Race> list(); Race get(Long id); Race save(Race race); void delete(Long id); List<Candidate> candidatesForRace(Race race); int candidateCountForRace(Race race); List<Voter> votersForRace(Race race); RaceResult tabulate(Race race); void revote(Race race); }
package great.dog.api.controller.api; import great.dog.api.domain.dto.DogFeedingDto; import great.dog.api.domain.response.DefaultRes; import great.dog.api.service.DogFeedingService; import great.dog.api.util.StatusCode; import great.dog.api.util.StatusMsg; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Objects; @RestController @AllArgsConstructor @RequestMapping("${spring.api}/dogFeeding") public class DogFeedingController { private final DogFeedingService dogFeedingService; @GetMapping("/{id}") public ResponseEntity<?> findById(@PathVariable("id") Long id) { DefaultRes<Object> defaultRes = new DefaultRes<>(); DogFeedingDto.Response res = dogFeedingService.findById(id); if(!Objects.isNull(res)) { defaultRes.setResCode(StatusCode.OK); defaultRes.setResMsg(StatusMsg.READ_SUCCESS); defaultRes.setData(res); } return new ResponseEntity<Object>(defaultRes, HttpStatus.OK); } @GetMapping("/dogId/{dogId}") public ResponseEntity<?> findByDogIdAndDelYn(@PathVariable("dogId") Long dogId) { DefaultRes<Object> defaultRes = new DefaultRes<>(); List<DogFeedingDto.Response> res = dogFeedingService.findByDogId(dogId); if(!Objects.isNull(res)) { defaultRes.setResCode(StatusCode.OK); defaultRes.setResMsg(StatusMsg.READ_SUCCESS); defaultRes.setData(res); } return new ResponseEntity<Object>(defaultRes, HttpStatus.OK); } @PostMapping("") public ResponseEntity save(@RequestBody DogFeedingDto.SaveRequest dto) { DefaultRes<Object> defaultRes = new DefaultRes<>(); int result = dogFeedingService.save(dto); if (result > 0) { defaultRes.setResCode(StatusCode.OK); defaultRes.setResMsg(StatusMsg.CREATED_SUCCESS); } else { defaultRes.setResMsg(StatusMsg.CREATED_FAIL); } return new ResponseEntity(defaultRes, HttpStatus.OK); } @PutMapping("/{id}") public ResponseEntity update(@PathVariable("id") Long id, @RequestBody DogFeedingDto.UpdateRequest dto) { int result = dogFeedingService.update(id, dto); DefaultRes defaultRes = new DefaultRes(StatusCode.BAD_REQUEST, StatusMsg.UPDATE_FAIL, dto); if (result > 0) { defaultRes.setResCode(StatusCode.OK); defaultRes.setResMsg(StatusMsg.UPDATE_SUCCESS); } else { defaultRes.setResMsg(StatusMsg.UPDATE_FAIL); } return new ResponseEntity(defaultRes, HttpStatus.OK); } }
package ru.aahzbrut.reciperestapi.services; import ru.aahzbrut.reciperestapi.dto.requests.IngredientRequest; import ru.aahzbrut.reciperestapi.dto.responses.ingredient.IngredientResponse; import java.util.List; public interface IngredientService { IngredientResponse getById(Long ingredientId); void deleteById(Long ingredientId); List<IngredientResponse> getAllCategories(); IngredientResponse update(Long ingredientId, IngredientRequest ingredientRequest); IngredientResponse create(IngredientRequest ingredientRequest); }
package com.diozero.util; /*- * #%L * Organisation: diozero * Project: diozero - Core * Filename: ByteTest.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * 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. * #L% */ import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @SuppressWarnings({ "static-method", "boxing" }) public class ByteTest { @Test public void test() { byte b = -125; // byte b = (byte) 0b11110000; int i = b; byte new_value = (byte) ((b >> 4) & 0x0f); new_value |= b << 4; byte b2 = (byte) i; int i2 = b2 & 0xff; /*- sun.misc.HexDumpEncoder enc = new sun.misc.HexDumpEncoder(); String s = enc.encode(new byte[] { b, b2, new_value, (byte) (b >> 1), (byte) (b >>> 1), (byte) (b >> 2), (byte) (b >> 3), (byte) (b >> 4), (byte) (b >> 5), (byte) (b >>> 5) }); */ System.out.format("b=%d, i=%d, b2=%d, i2=%d, new_value=%d%n", b, i, b2, i2, new_value); Hex.dumpByteArray(new byte[] { b, b2, new_value, (byte) (b >> 1), (byte) (b >>> 1), (byte) (b >> 2), (byte) (b >> 3), (byte) (b >> 4), (byte) (b >> 5), (byte) (b >>> 5) }); b = (byte) 0xff; byte bit = 0; Assertions.assertEquals(0, b & bit); Assertions.assertTrue(BitManipulation.isBitSet(b, bit)); int num_bytes = 35; byte[] bytes = new byte[num_bytes]; ThreadLocalRandom.current().nextBytes(bytes); // enc.encode(bytes, System.out); Hex.dumpByteArray(bytes); i = 208; b = (byte) i; b2 = (byte) (i & 0xff); Assertions.assertEquals(b, b2); System.out.println(b); i2 = i - 256; b2 = (byte) i2; Assertions.assertEquals(b, b2); System.out.println(b2); } @Test public void max30102IntUnpack() { byte[] b = { 0x15, (byte) 0xEC, (byte) 0xCD }; int val = readUnsignedInt(b, 0); Assertions.assertEquals(126157, val); b = new byte[] { 0x15, (byte) 0xdd, 0x67 }; val = readUnsignedInt(b, 0); Assertions.assertEquals(122215, val); } private static int readUnsignedInt(byte[] data, int pos) { // red_led = (d[0] << 16 | d[1] << 8 | d[2]) & 0x03FFFF // d[0]: 0x15 [21], d[1]: 0xEC [236], d[3]: 0xCD [205], red_led: 0x15ECCD = // 126157 // d[0]: 0x15, d[1]: 0xEC, d[3]: 0xCD (0x15ECCD), red_led: 0x1ECCD // 0x15 [21] 0xdd [221] 0x67 [103] (0x15dd67): return (((data[pos * 3] & 0xff) << 16) | ((data[pos * 3 + 1] & 0xff) << 8) | (data[pos * 3 + 2] & 0xff)) & 0x03FFFF; } }
package com.org.dao; import com.org.po.User; import org.springframework.data.jpa.repository.JpaRepository; /** * @author Create by MengXi on 2021/10/12 15:57. * * pring Data :提供了一整套数据访问层(DAO)的解决方案,致力于减少数据访问层(DAO)的开发量。它使用一个叫作Repository的接口类为基础,它被定义为访问底层数据模型的超级接口。 * 而对于某种具体的数据访问操作,则在其子接口中定义。 * public interface Repository<T, ID extends Serializable> { * } * 所有继承这个接口的interface都被spring所管理,此接口作为标识接口,功能就是用来控制domain模型的。 * Spring Data可以让我们只定义接口,只要遵循spring data的规范,就无需写实现类。 * * 什么是Repository? * Repository(资源库):通过用来访问领域对象的一个类似集合的接口,在领域与数据映射层之间进行协调。这个叫法就类似于我们通常所说的DAO,在这里,我们就按照这一习惯把数据访问层叫Repository * Spring Data给我们提供几个Repository,基础的Repository提供了最基本的数据访问功能,其几个子接口则扩展了一些功能。它们的继承关系如下: * Repository: 仅仅是一个标识,表明任何继承它的均为仓库接口类,方便Spring自动扫描识别 * CrudRepository: 继承Repository,实现了一组CRUD相关的方法 * PagingAndSortingRepository: 继承CrudRepository,实现了一组分页排序相关的方法 * JpaRepository: 继承PagingAndSortingRepository,实现一组JPA规范相关的方法 * JpaSpecificationExecutor: 比较特殊,不属于Repository体系,实现一组JPA Criteria查询相关的方法 * 我们自己定义的XxxxRepository需要继承JpaRepository,这样我们的XxxxRepository接口就具备了通用的数据访问控制层的能力。 * 接口必须继承类型参数化为实体类型和实体类中的Id类型的Repository public interface UserRepository extends JpaRepository<T, ID>, * T 需要类型化为实体类(Entity)User,ID需要实体类User中Id(我定义的Id类型是Long)的类型. * *@Query 注解,自定义查询 * * */ public interface UserRepository extends JpaRepository<User, Long> { /** * 遵循它的命名规则,就会查询数据库 * @param username * @param password * @return */ User findByUsernameAndPassword(String username, String password); }
package com.vilio.ppms.pojo.common; import java.math.BigDecimal; import java.util.Date; public class SubAccount { private Long id; private String code; private String sysSerno; private BigDecimal transAmount; private BigDecimal subAccAmount; private String subAccStatus; private String status; private Date createTime; private Date updateTime; private String remark1; public SubAccount(Long id, String code, String sysSerno, BigDecimal transAmount, BigDecimal subAccAmount, String subAccStatus, String status, Date createTime, Date updateTime, String remark1) { this.id = id; this.code = code; this.sysSerno = sysSerno; this.transAmount = transAmount; this.subAccAmount = subAccAmount; this.subAccStatus = subAccStatus; this.status = status; this.createTime = createTime; this.updateTime = updateTime; this.remark1 = remark1; } public SubAccount() { super(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getSysSerno() { return sysSerno; } public void setSysSerno(String sysSerno) { this.sysSerno = sysSerno == null ? null : sysSerno.trim(); } public BigDecimal getTransAmount() { return transAmount; } public void setTransAmount(BigDecimal transAmount) { this.transAmount = transAmount; } public BigDecimal getSubAccAmount() { return subAccAmount; } public void setSubAccAmount(BigDecimal subAccAmount) { this.subAccAmount = subAccAmount; } public String getSubAccStatus() { return subAccStatus; } public void setSubAccStatus(String subAccStatus) { this.subAccStatus = subAccStatus == null ? null : subAccStatus.trim(); } public String getStatus() { return status; } public void setStatus(String status) { this.status = status == null ? null : status.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1 == null ? null : remark1.trim(); } }
package com.daralisdan.test; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.daralisdan.bean.Employee; import com.daralisdan.dao.EmployeeMapper; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class EmployeeTest { @Resource EmployeeMapper empMapper; /** * * Title:Test02 <br> * spring的单元测试Junit * date:2019年9月15日 下午7:23:54 <br> * * @throws IOException <br> */ @Test public void Test02() { List<Employee> emps = empMapper.getEmps(); for (Employee emp : emps) { System.out.println(emp); } } }
package a8; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; public class ViewLife extends JPanel{ private GridPanel grid; private ControllerLife control; public ViewLife(int width, int height) { if (width < 1 || height < 1) { throw new IllegalArgumentException("Illegal board geometry"); } this.setLayout(new BorderLayout()); grid = new GridPanel(width, height); this.add(grid, BorderLayout.CENTER); JPanel north = new JPanel(); north.setLayout(new FlowLayout()); JLabel rows = new JLabel("Rows: "); north.add(rows); JSpinner rowtxt = new JSpinner(new SpinnerNumberModel(width, 1, 500, 1)); north.add(rowtxt); JLabel cols = new JLabel("Cols: "); north.add(cols); JSpinner coltxt = new JSpinner(new SpinnerNumberModel(height, 1, 500, 1)); north.add(coltxt); JButton resize = new JButton("Resize"); resize.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.resize((Integer)rowtxt.getValue(),(Integer)coltxt.getValue()); } }); north.add(resize); this.add(north, BorderLayout.NORTH); JPanel south = new JPanel(); south.setLayout(new FlowLayout()); JButton advance = new JButton("Advance"); advance.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.advance(); } }); south.add(advance); JButton reset = new JButton("Reset"); reset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.reset(); } }); south.add(reset); JButton random = new JButton("Random"); random.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.random(); } }); south.add(random); this.add(south, BorderLayout.SOUTH); JPanel west = new JPanel(); west.setLayout(new GridLayout(0,1)); JPanel weast = new JPanel(); JLabel birth = new JLabel("Birth Thresholds:"); west.add(birth); JLabel lowb = new JLabel("Low: "); weast.add(lowb); JSpinner lowbs = new JSpinner(new SpinnerNumberModel(3, 0, 8, 1)); weast.add(lowbs); west.add(weast); JPanel weast2 = new JPanel(); JLabel highb = new JLabel("High: "); weast2.add(highb); JSpinner highbs = new JSpinner(new SpinnerNumberModel(3, 0,8, 1)); weast2.add(highbs); west.add(weast2); JLabel surv = new JLabel("Survive Thresholds:"); west.add(surv); JPanel weast3 = new JPanel(); JLabel lows = new JLabel("Low: "); weast3.add(lows); JSpinner lowst = new JSpinner(new SpinnerNumberModel(2, 0, 8, 1)); weast3.add(lowst); west.add(weast3); JPanel weast4 = new JPanel(); JLabel highs = new JLabel("High: "); weast4.add(highs); JSpinner highst = new JSpinner(new SpinnerNumberModel(3, 0,8, 1)); weast4.add(highst); west.add(weast4); JButton set = new JButton("Set Bounds"); set.setMaximumSize(new Dimension(45, 40)); set.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.set((Integer)lowbs.getValue(),(Integer)highbs.getValue() , (Integer)lowst.getValue(), (Integer)highst.getValue()); } }); west.add(set); this.add(west, BorderLayout.WEST); JPanel east = new JPanel(); east.setLayout(new BoxLayout(east, BoxLayout.Y_AXIS)); JLabel torus = new JLabel("Torus"); east.add(torus); ButtonGroup g = new ButtonGroup(); JRadioButton torusOn = new JRadioButton("On"); JRadioButton torusOff = new JRadioButton("Off"); g.add(torusOn); g.add(torusOff); torusOn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.torus(); } }); torusOff.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.torus(); } }); torusOff.setSelected(true); east.add(torusOn); east.add(torusOff); JPanel east2 = new JPanel(); east2.setLayout(new GridLayout(0,1)); east2.setMaximumSize(new Dimension(100,100)); JLabel thrd = new JLabel("Time delay (ms): "); east2.add(thrd); JSpinner timeMS = new JSpinner(new SpinnerNumberModel(100, 10, 1000, 1)); //timeMS.setPreferredSize(new Dimension(43,34)); east2.add(timeMS); JButton stastop = new JButton("Start/Stop"); stastop.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { control.startStop((Integer)timeMS.getValue()); } }); east2.add(stastop); east.add(east2); this.add(east, BorderLayout.EAST); } public void updateGrid() { grid.repaint(); grid.revalidate(); } public GridPanel getGrid() { return grid; } public void setGrid(GridPanel b) { this.remove(grid); grid = b; this.add(grid,BorderLayout.CENTER); grid.addMouseListener(control); } public void setController(ControllerLife c) { control = c; grid.addMouseListener(control); } }
package com.example.v3.design.factory; /** * 发送功能 */ public interface Sender { void Send(); }
package com.spbsu.benchmark.flink.index.ops; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryonet.Client; import com.esotericsoftware.kryonet.Connection; import com.esotericsoftware.kryonet.Listener; import com.spbsu.benchmark.flink.index.Result; import com.spbsu.flamestream.example.bl.index.model.WordIndexAdd; import com.spbsu.flamestream.example.bl.index.model.WordIndexRemove; import com.spbsu.flamestream.runtime.utils.tracing.Tracing; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.sink.RichSinkFunction; import org.jetbrains.annotations.Nullable; import org.objenesis.strategy.StdInstantiatorStrategy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.nio.file.Paths; public class KryoSocketSink extends RichSinkFunction<Result> { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(KryoSocketSink.class); private static final int OUTPUT_BUFFER_SIZE = 1_000_000; private static final int CONNECTION_AWAIT_TIMEOUT = 5000; private final String hostName; private final int port; @Nullable private transient Client client = null; //private transient Tracing.Tracer tracer; public KryoSocketSink(String hostName, int port) { this.hostName = hostName; this.port = port; } @Override public void open(Configuration parameters) throws Exception { //tracer = Tracing.TRACING.forEvent("sink-receive"); client = new Client(OUTPUT_BUFFER_SIZE, 1234); client.getKryo().register(WordIndexAdd.class); client.getKryo().register(WordIndexRemove.class); client.getKryo().register(long[].class); ((Kryo.DefaultInstantiatorStrategy) client.getKryo() .getInstantiatorStrategy()).setFallbackInstantiatorStrategy(new StdInstantiatorStrategy()); client.addListener(new Listener() { @Override public void disconnected(Connection connection) { LOG.warn("Sink has been disconnected {}", connection); } }); LOG.info("Connecting to {}:{}", hostName, port); client.start(); client.connect(CONNECTION_AWAIT_TIMEOUT, hostName, port); LOG.info("Connected to {}:{}", hostName, port); } @Override public void invoke(Result value, Context context) { if (client != null && client.isConnected()) { //tracer.log(value.wordIndexAdd().hash()); client.sendTCP(value.wordIndexAdd()); if (value.wordIndexRemove() != null) { client.sendTCP(value.wordIndexRemove()); } } else { throw new RuntimeException("Writing to the closed log"); } } @Override public void close() { try { Tracing.TRACING.flush(Paths.get("/tmp/trace.csv")); } catch (IOException e) { e.printStackTrace(); } if (client != null) { LOG.info("Closing sink connection"); client.close(); client.stop(); } } }
package com.rcwang.seal.eval; import java.io.File; import java.util.List; import org.apache.log4j.Logger; import com.rcwang.seal.expand.Seal; import com.rcwang.seal.expand.SeedSelector; import com.rcwang.seal.translation.BilingualSeal; import com.rcwang.seal.util.GlobalVar; import com.rcwang.seal.util.Helper; //import com.rcwang.seal.util.Mailer; //wwc public class BilingualExperiment { public static Logger log = Logger.getLogger(BilingualExperiment.class); public static GlobalVar gv = GlobalVar.getGlobalVar(); public static final String FROM_EMAIL_ADDR = "Bilingual Results <exp.results@cmu.edu>"; public static final String TO_EMAIL_ADDR = "Richard Wang <rcwang@gmail.com>"; private static String sourceLangID = gv.getLangID(); private static String targetLangID = gv.getLangID2(); private static boolean useTranslation = true; public static void main(String args[]) { BilingualExperiment.run(); } public static void run() { if (sourceLangID == null || targetLangID == null) { log.fatal("Source and/or target language is not defined!"); return; } else if (sourceLangID.equals(targetLangID)) { log.fatal("Source and target languages (" + sourceLangID + ") must be different!"); return; } // get evaluation file File evalDir = Helper.createDir(gv.getEvalDir()); String evalFileName = getExperimentID() + "_" + Helper.getUniqueID() + Evaluator.EVAL_FILE_SUFFIX; File evalFile = new File(evalDir, evalFileName); // prepare output buffer StringBuffer buf = new StringBuffer("Dataset\t"); for (int i = 0; i < gv.getNumExpansions(); i++) buf.append("E").append(i+1).append("\t"); buf.setCharAt(buf.length()-1, '\n'); int bufStartIndex = buf.length(); // preparing experiment Helper.recursivelyRemove(gv.getResultDir()); Evaluator evaluator = new Evaluator(); double[] maps = new double[gv.getNumExpansions()]; long startTime = System.currentTimeMillis(); // load each dataset for (String dataName : gv.getExpDatasets()) { File sourceGoldFile = toGoldFile(dataName, sourceLangID); if (sourceGoldFile == null) continue; evaluator.loadGoldFile(sourceGoldFile); // conduct trials for (int trialID = 0; trialID < gv.getNumTrials(); trialID++) { log.info("-----------------------------------------------------"); log.info("Evaluating trial " + (trialID+1) + "/" + gv.getNumTrials() + " on " + dataName + " (" + sourceLangID + " <--> " + targetLangID + ")..."); List<EvalResult> evalResults = evaluate(evaluator, trialID); if (evalResults == null) continue; // process evaluation results buf.append(sourceLangID).append("/").append(targetLangID).append(".").append(dataName).append("\t"); double map = 0; for (int expansionID = 0; expansionID < gv.getNumExpansions(); expansionID++) { if (expansionID < evalResults.size()) map = evalResults.get(expansionID).meanAvgPrecision; maps[expansionID] += map; buf.append(map).append("\t"); } buf.setCharAt(buf.length()-1, '\n'); Helper.writeToFile(evalFile, buf.substring(bufStartIndex), true); bufStartIndex = buf.length(); } } // finishing the experiment buf.append("Average\t"); int totalTrials = gv.getExpDatasets().size() * gv.getNumTrials(); for (int i = 0; i < gv.getNumExpansions(); i++) buf.append(maps[i] / totalTrials).append("\t"); buf.setCharAt(buf.length()-1, '\n'); Helper.writeToFile(evalFile, buf.substring(bufStartIndex), true); mailResults(getExperimentID(), buf.toString()); Helper.printMemoryUsed(); Helper.printElapsedTime(startTime); } private static List<EvalResult> evaluate(Evaluator evaluator, int trialID) { SeedSelector selector = new SeedSelector(gv.getPolicy()); selector.setNumSeeds(gv.getNumTrueSeeds(), gv.getNumPossibleSeeds()); selector.setFeature(gv.getFeature()); selector.setTrueSeeds(evaluator.getFirstMentions()); selector.setRandomSeed(trialID); BilingualSeal biSeal = new BilingualSeal(); biSeal.setEval(evaluator); biSeal.setLangID(sourceLangID, targetLangID); biSeal.setNumExpansions(gv.getNumExpansions()); biSeal.setUseTranslation(useTranslation); biSeal.expand(new Seal(), selector); return biSeal.getEvalResultList(); } private static String getExperimentID() { String[] evalFileNameArr = new String[] { gv.getFeature().toString().toLowerCase(), gv.getLangID().toLowerCase(), gv.getLangID2().toLowerCase(), useTranslation ? Integer.toString(1) : Integer.toString(0), Integer.toString(gv.getNumResults()), }; return Helper.merge(evalFileNameArr, "."); } private static void mailResults(String experimentID, String content) { /* wwc String subject = Helper.extract(content, "Average", "\n"); if (subject == null) return; subject = experimentID + ": " + subject.replaceAll("\\s+", " ").trim(); Mailer.sendEmail(FROM_EMAIL_ADDR, TO_EMAIL_ADDR, subject, content); */ } private static File toGoldFile(String dataset, String langID) { File goldFile = new File(new File(gv.getDataDir(), langID), dataset + Evaluator.GOLD_FILE_SUFFIX); if (!goldFile.exists()) { log.fatal("Evaluation data " + goldFile + " could not be found!"); return null; } return goldFile; } }
package uk.gov.moj.util; import uk.gov.moj.DeadLetterQueueBrowser; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DLQUtil { private final static Logger LOGGER = LoggerFactory.getLogger(DLQUtil.class); public static void cleanDeadLetterQueue() { DeadLetterQueueBrowser deadLetterQueueBrowser = new DeadLetterQueueBrowser(); deadLetterQueueBrowser.removeMessages(); deadLetterQueueBrowser.close(); } public static void logMessagesInDeadletterQueue() { DeadLetterQueueBrowser deadLetterQueueBrowser = new DeadLetterQueueBrowser(); logMessages(deadLetterQueueBrowser); deadLetterQueueBrowser.close(); } public static int getDeadLetterQueueMessageCount() { try (DeadLetterQueueBrowser deadLetterQueueBrowser = new DeadLetterQueueBrowser()) { return deadLetterQueueBrowser.browseAsJson().size(); } } private static void logMessages(DeadLetterQueueBrowser deadLetterQueueBrowser) { LOGGER.info("Displaying messages in dead letter queue "); deadLetterQueueBrowser.browseFullMessages(); } public static void logMessagesAndCleanDeadLetterQueue() { DeadLetterQueueBrowser deadLetterQueueBrowser = new DeadLetterQueueBrowser(); logMessages(deadLetterQueueBrowser); deadLetterQueueBrowser.removeMessages(); deadLetterQueueBrowser.close(); } public static void downloadAllMessages() { DeadLetterQueueBrowser deadLetterQueueBrowser = new DeadLetterQueueBrowser(); deadLetterQueueBrowser.downloadFullMessages(); deadLetterQueueBrowser.close(); } }
public interface Maquina { String getTipo(); String getSistemaOperacional(); }
package com.yougou.merchant.api.supplier.vo; import java.io.Serializable; public class BrandCategoryVo implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private String brandNo;//品牌编码 private String rootCategory;//一级分类 private String secondCategory;//二级分类 private String threeCategory;//三级分类 public String getBrandNo() { return brandNo; } public void setBrandNo(String brandNo) { this.brandNo = brandNo; } public String getRootCategory() { return rootCategory; } public void setRootCategory(String rootCategory) { this.rootCategory = rootCategory; } public String getSecondCategory() { return secondCategory; } public void setSecondCategory(String secondCategory) { this.secondCategory = secondCategory; } public String getThreeCategory() { return threeCategory; } public void setThreeCategory(String threeCategory) { this.threeCategory = threeCategory; } }
package sp.designpatterns.DecoratorExample; public class JapanesePizzo extends Pizza{ JapanesePizzo(String description){ this.description=description; } @Override public double getCost() { // TODO Auto-generated method stub return 67; } }
package com.wentongwang.mysports.views.fragment.agenda; import android.content.Context; import com.wentongwang.mysports.constant.Constant; import com.wentongwang.mysports.custome.PersonInfoPopupWindow; import java.util.HashMap; import java.util.Map; /** * Created by Wentong WANG on 2016/9/26. */ public class AgendaPresenter { private AgendaView view; private Context mContext; public AgendaPresenter(AgendaView view) { this.view = view; } /** * initial presenter * get Activity context * initial VolleyRequestManager * * @param context */ public void init(Context context) { this.mContext = context; } public void showPopupWindow() { //获取数据,通过构造函数塞到popupWindow里 final PersonInfoPopupWindow popupWindow = new PersonInfoPopupWindow(mContext); popupWindow.setOnDismissListener(() -> view.setBackGroundAlpha(1f)); view.showPersonInfoPopupWindow(popupWindow); view.setBackGroundAlpha(0.55f); } public void getAgenda(){ String url=Constant.HOST+ Constant.GET_AGENDA_PATH; //TODO:接口重写 Map<String, String> params = new HashMap<>(); params.put("user_id", ""); params.put("user_event_time", ""); params.put("page_size", "15"); params.put("current_page", "5"); view.showProgressBar(); // RxVolleyRequest.getInstance().resourceRequestObservable(mContext,Request.Method.POST,url,params) // .subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程 // .observeOn(AndroidSchedulers.mainThread())// 指定 Subscriber 的回调发生在主线程 // .subscribe(new Observer<String>() { // @Override // public void onCompleted() { // view.hideProgressBar(); // } // // @Override // public void onError(Throwable e) { // view.hideProgressBar(); // ToastUtil.show(mContext, e.toString(), 1500); // } // // @Override // public void onNext(String response) { // VolleyResponse<AgendaEvents> agendaEventsVolleyResponse = new VolleyResponse<AgendaEvents>(); // agendaEventsVolleyResponse.setMsg(response); // List<AgendaEvents> list=agendaEventsVolleyResponse.getResultArray(AgendaEvents.class); // view.setAgendaList(list); // } // }); } }
package ru.job4j.todo.servlet; import ru.job4j.todo.model.Task; import ru.job4j.todo.service.HibernateService; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class DoneServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.parseInt(req.getParameter("id")); HibernateService.instOf().setDone(new Task(id)); } }
import org.junit.Assert; import org.junit.Test; public class ConeAreaTest { @Test public void coneAreaTest(){ Cone cone=new Cone(5,2); Assert.assertEquals(43,cone.area(),1); } }
/** * */ package com.shubhendu.javaworld.recursion; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author ssingh * */ public class CombinationSum { // public List<List<Integer>> combinationSum(int[] candidates, int target) { // Arrays.sort(candidates); // List<List<Integer>> result = new ArrayList<List<Integer>>(); // getResult(result, new ArrayList<Integer>(), candidates, target, 0); // // return result; // } // // private void getResult(List<List<Integer>> result, List<Integer> cur, int // candidates[], int target, int start) { // if (target > 0) { // for (int i = start; i < candidates.length && target >= candidates[i]; // i++) { // cur.add(candidates[i]); // getResult(result, cur, candidates, target - candidates[i], i); // cur.remove(cur.size() - 1); // } // for // } // if // else if (target == 0) { // result.add(new ArrayList<Integer>(cur)); // } // else if // } public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(candidates); combinationSumRecursive(candidates, target, 0, new ArrayList<Integer>(), result); return result; } private void combinationSumRecursive(int[] candidates, int target, int startIndex, ArrayList<Integer> currList, List<List<Integer>> result) { if (target < 0) { return; } if (target == 0) { result.add(new ArrayList<Integer>(currList)); return; } for (int i = startIndex; i < candidates.length && target >= candidates[i]; i++) { currList.add(candidates[i]); combinationSumRecursive(candidates, target - candidates[i], i, currList, result); currList.remove(currList.size() - 1); } } public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(candidates); combinationSum2Recursive(candidates, target, 0, new ArrayList<Integer>(), result); return result; } private void combinationSum2Recursive(int[] candidates, int target, int startIndex, ArrayList<Integer> currList, List<List<Integer>> result) { if (target < 0) { return; } if (target == 0) { result.add(new ArrayList<Integer>(currList)); return; } for (int i = startIndex; i < candidates.length && target >= candidates[i]; i++) { if (i > startIndex && candidates[i] == candidates[i - 1]) continue; currList.add(candidates[i]); combinationSum2Recursive(candidates, target - candidates[i], i + 1, currList, result); currList.remove(currList.size() - 1); } } public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> result = new ArrayList<List<Integer>>(); combinationSum3Recursive(k, n, 1, new ArrayList<Integer>(), result); return result; } public void combinationSum3Recursive(int maxSize, int target, int startIndex, ArrayList<Integer> currList, List<List<Integer>> result) { if (target < 0 || currList.size() > maxSize) { return; } if (target == 0) { if (currList.size() == maxSize) { result.add(new ArrayList<Integer>(currList)); } else { return; } } for (int i = startIndex; i <= 9; i++) { currList.add(i); combinationSum3Recursive(maxSize, target - i, i + 1, currList, result); currList.remove(currList.size() - 1); } } private int[] dp; public int combinationSum4(int[] nums, int target) { this.dp = new int[target + 1]; Arrays.fill(this.dp, -1); this.dp[0] = 1; return combinationSum4Recursive(nums, target); } public int combinationSum4Recursive(int[] nums, int target) { if (dp[target] != -1) { return dp[target]; } int count = 0; for (int i = 0; i < nums.length && target >= nums[i]; i++) { count += combinationSum4Recursive(nums, target - nums[i]); } dp[target] = count; return count; } // public void combinationSum4Recursive(int[] nums, int target, int // startIndex, ArrayList<Integer> currList, // List<List<Integer>> result) { // if (target < 0) { // return; // } // // if (target == 0) { // result.add(new ArrayList<Integer> (currList)); // } // // for (int i = startIndex; i < nums.length && target >= nums[i]; i++) { // currList.add(nums[i]); // combinationSum4Recursive(nums, target - nums[i], startIndex, currList, // result); // currList.remove(currList.size() - 1); // } // // } private static void printList(List<List<Integer>> permutations) { for (List<Integer> l : permutations) { for (Integer i : l) { System.out.print(i + " "); } System.out.println("\n==="); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = new int[] { 1, 2, 3 }; int target = 4; CombinationSum c = new CombinationSum(); // List<List<Integer>> result = c.combinationSum(nums, target); // printList(result); // nums = new int[] { 10, 1, 2, 7, 6, 1, 5 }; // target = 8; // List<List<Integer>> result = c.combinationSum2(nums, target); // printList(result); // List<List<Integer>> result = c.combinationSum3(3, 7); // printList(result); System.out.println(c.combinationSum4(nums, target)); } }
/* Using CountMap : t : O(n) s : O(n); */ // ------------------- HashTable class HashTable{ public final int tableSize; public Node[] list; public HashTable(){ tableSize = 512; list = new Node[tableSize]; } class Node{ int key; int data; Node next; public Node(int key, int data, Node next){ this.key = key; this.data = data; this.next = next; } } public int compare(int a, int b){ return a-b; } // Get the hash code for the key. To keep things simple, here is a dummy hash function : // it get the key, then simply return the key. // If as example the entry key was a phone number associated to employee // I can use the last 3 number as hashcode, and then hashtable index would be taken from this in computeHash public int getHashCode(int key){ return key; } // reduce the hashcode value (here making the mod of it), and getting the index inside the hashtable // to make index range smaller and array dimension not too big public int computeHash(int key){ int hashValue = 0; hashValue = getHashCode(key); return hashValue % tableSize; } // to keep things simple, the key and the data associated are the same, here the field could have been only one public void insert( int key, Integer data ){ if (data == null) data = key; int index = computeHash(key); Node head = list[index]; while( head != null ){ // Collision : key already in hashtable, put it in the linked list if(compare(head.key, key) == 0){ // Update : In case key is already present in list : exit head.data = data; return; } head = head.next; // put it at the end of the list } // No collision, new key; list.get(index) = null because that node at that index is not present list[index] = new Node(key, data, list[index]); } public boolean remove(int key){ Node nextNode; int index = computeHash(key); Node head = list[index]; // if is a head key node, delete pointing to the next node // (which will be : // - null it is a key node with no list chained to it) // - the next node in the chained list if( (head != null) && (compare(head.key,key) == 0) ){ list[index] = head.next; return true; } // it is not head key node : search in the chained list while( head != null){ nextNode = head.next; if ( (nextNode != null) && (compare(nextNode.key,key) == 0) ){ head.next = nextNode.next; return true; }else{ head = nextNode; } } return false; } public void print(){ for(int i=0; i<tableSize; i++){ System.out.print("Print for index value : "+i+" Values :: "); Node head = list[i]; if (head == null) { System.out.println("0"); continue; } while(head != null){ System.out.println(head.data); head = head.next; } } } public boolean find(int key){ int index = computeHash(key); Node head = list[index]; while(head != null){ if(head.key == key) return true; // key node head = head.next; // search in chained list } return false; } public Integer getData(int key){ int index = computeHash(key); Node head = list[index]; while(head != null){ if(head.key == key) return head.data; // key node head = head.next; // search in chained list } return null; } } // ------------------- CountMap class CountMap{ public int sizeCountMap; public HashTable hm; public CountMap(){ sizeCountMap = 0; // NB : size of the key and their repetition, not that of hashtable hm = new HashTable(); } public void insert(int key){ sizeCountMap++; if(hm.find(key)){ // if already in hm, increment value int cnt = hm.getData(key); hm.insert(key, cnt+1); } else { hm.insert(key, 1); // else if new, set 1 } } public void remove(int key){ if(hm.find(key)){ if(hm.getData(key) == 1){ hm.remove(key); }else{ decrementDataBy(key, 1); } } sizeCountMap--; } public void decrementDataBy(int key, int dec){ int cnt = hm.getData(key); hm.insert(key, cnt-1); } public Integer getData(int key){ if(hm.find(key)) return hm.getData(key); else return 0; } public boolean find(int key){ return hm.find(key); } public int size(){ return sizeCountMap; } public void print(){ hm.print(); } } public class Main{ public static void findFirstRepeating(int[] arr){ if (arr.length <= 0 ) return; CountMap cm = new CountMap(); for(int i=0;i<arr.length;i++) { cm.insert(arr[i]); } for(int i=0;i<arr.length;i++) { int k = arr[i]; cm.remove(k); if (cm.find(k)) { System.out.println("First repeating number : "+k); break; } } } public static void main(String args[]){ // int[] data ={8,9,12,6,0,6,7,1,2,3,8,10,4,4,2,2,4,10,12}; int[] data ={1,2,3,2,1}; findFirstRepeating(data); } }
package cn.bs.zjzc.presenter; import cn.bs.zjzc.App; import cn.bs.zjzc.model.IAddInsuredModel; import cn.bs.zjzc.model.callback.HttpTaskCallback; import cn.bs.zjzc.model.impl.AddInsuredModel; import cn.bs.zjzc.model.response.AddInsuredResponse; import cn.bs.zjzc.ui.view.IAddInsuredView; /** * 添加保价费计算方式 * Created by mgc on 2016/7/1. */ public class AddInsuredPresenter { private IAddInsuredModel model; private IAddInsuredView view; public AddInsuredPresenter(IAddInsuredView view) { this.view = view; model = new AddInsuredModel(); } public void getAddInsuredWay() { view.showLoading(); model.getInsured_way(new HttpTaskCallback<AddInsuredResponse.DataBean>() { @Override public void onTaskFailed(String errorInfo) { view.hideLoading(); view.showMsg(errorInfo); } @Override public void onTaskSuccess(AddInsuredResponse.DataBean data) { App.LOGIN_USER.setData(data); view.hideLoading(); view.getInsuredWaySuccess(data); } }); } }
package HomeworkDay5; public class Palindrome { public static void main(String[] args) { // TODO Auto-generated method stub } } class node{ protected node next; protected int d; public node(int x){ d=x; next=null; } } class IntSlist{ private node first; private node last; public IntSlist(){ first=null; last=null; } public void add(int x){ node n=new node(x); if(first!=null){ last.next=n; } else{ first=n; } last=n; } public static IntSlist buildList(int n){ IntSlist l=new IntSlist(); for(int i=0;i<n;i++){ int x=i; l.add(x); } return l; } public boolean remove(int x) { node [] nodes = new node[2] ; //find(x,nodes) ; if (nodes[0] != null) { if ((nodes[0] == first) && (nodes[0] == last)) { //Does list has only one element first = null ; last = null ; }else if (nodes[0] == first) { //first element being removed and list //has more than 1 element first = nodes[0].next ; }else if (nodes[0] == last) { //last element being removed and list //has more than 1 element nodes[1].next = null ; last = nodes[1] ; }else { //You are removing middle element nodes[1].next = nodes[0].next ; } nodes[0] = null ; //Garbage collection //decSize(); return true ; }else { return false ; } } }
package graphloaders.oldDotParser.actions; import graphana.graphs.GraphLibrary; import graphloaders.oldDotParser.parser.DotGraphAction; import graphloaders.oldDotParser.parser.DotReader; import graphloaders.oldDotParser.tokens.DotIdentifier; public class SetGraphNameAction extends DotGraphAction { @Override public <VertexType, EdgeType> void action(GraphLibrary<VertexType, EdgeType> graph, DotReader source) { graph.setName(((DotIdentifier) source.pollTokenValue()).getIdent()); } }
package pl.training.shop; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.html.Anchor; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.Router; import pl.training.shop.product.ui.ProductsView; @Route public class MainView extends VerticalLayout { private HorizontalLayout menu = new HorizontalLayout(); public MainView() { Router router = UI.getCurrent().getRouter(); Anchor productsAnchor = new Anchor(router.getUrl(ProductsView.class), "Produkty"); menu.add(productsAnchor); add(menu); } }
package com.cxjd.nvwabao.adapter; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.cxjd.nvwabao.FirstAid.Aid01; import com.cxjd.nvwabao.FirstAid.Aid02; import com.cxjd.nvwabao.FirstAid.Aid03; import com.cxjd.nvwabao.FirstAid.Aid04; import com.cxjd.nvwabao.FirstAid.Aid05; import com.cxjd.nvwabao.FirstAid.Aid06; import com.cxjd.nvwabao.FirstAid.Aid07; import com.cxjd.nvwabao.FirstAid.Aid08; import com.cxjd.nvwabao.FirstAid.Aid09; import com.cxjd.nvwabao.FirstAid.Aid10; import com.cxjd.nvwabao.FirstAid.Aid11; import com.cxjd.nvwabao.FirstAid.Aid12; import com.cxjd.nvwabao.FirstAid.Aid13; import com.cxjd.nvwabao.FirstAid.Aid14; import com.cxjd.nvwabao.FirstAid.Aid15; import com.cxjd.nvwabao.FirstAid.Aid16; import com.cxjd.nvwabao.FirstAid.Aid17; import com.cxjd.nvwabao.FirstAid.Aid18; import com.cxjd.nvwabao.FirstAid.Aid19; import com.cxjd.nvwabao.FirstAid.Aid20; import com.cxjd.nvwabao.FirstAid.Aid21; import com.cxjd.nvwabao.FirstAid.Aid22; import com.cxjd.nvwabao.FirstAid.Aid23; import com.cxjd.nvwabao.FirstAid.Aid24; import com.cxjd.nvwabao.FirstAid.Aid25; import com.cxjd.nvwabao.FirstAid.Aid26; import com.cxjd.nvwabao.FirstAid.Aid27; import com.cxjd.nvwabao.FirstAid.Aid28; import com.cxjd.nvwabao.FirstAid.Aid29; import com.cxjd.nvwabao.FirstAid.Aid30; import com.cxjd.nvwabao.FirstAid.Aid31; import com.cxjd.nvwabao.FirstAid.Aid32; import com.cxjd.nvwabao.FirstAid.Aid33; import com.cxjd.nvwabao.FirstAid.Aid34; import com.cxjd.nvwabao.FirstAid.Aid35; import com.cxjd.nvwabao.FirstAid.Aid36; import com.cxjd.nvwabao.FirstAid.Aid37; import com.cxjd.nvwabao.FirstAid.Aid38; import com.cxjd.nvwabao.FirstAid.Aid39; import com.cxjd.nvwabao.FirstAid.Aid40; import com.cxjd.nvwabao.FirstAid.Aid41; import com.cxjd.nvwabao.FirstAid.Aid42; import com.cxjd.nvwabao.FirstAid.Aid43; import com.cxjd.nvwabao.FirstAid.Aid44; import com.cxjd.nvwabao.R; import com.cxjd.nvwabao.bean.ListView; import java.util.List; /** * Created by 李超 on 2017/12/4. */ public class AidAdapter extends RecyclerView.Adapter<AidAdapter.ViewHolder> { private List<ListView> mListView; static class ViewHolder extends RecyclerView.ViewHolder { View aidItemView; TextView textView; public ViewHolder(View itemView) { super(itemView); aidItemView = itemView; textView = itemView.findViewById(R.id.aid_TextView); } } public AidAdapter(List<ListView> mListView) { this.mListView = mListView; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.aid_item,parent,false); final ViewHolder holder = new ViewHolder(view); holder.aidItemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = holder.getAdapterPosition(); switch (position){ case 0 : Intent intent = new Intent(view.getContext(), Aid01.class); view.getContext().startActivity(intent); break; case 1 : Intent intent1 = new Intent(view.getContext(), Aid02.class); view.getContext().startActivity(intent1); break; case 2 : Intent intent2 = new Intent(view.getContext(), Aid03.class); view.getContext().startActivity(intent2); break; case 3 : Intent intent3 = new Intent(view.getContext(), Aid04.class); view.getContext().startActivity(intent3); break; case 4 : Intent intent4 = new Intent(view.getContext(), Aid05.class); view.getContext().startActivity(intent4); break; case 5 : Intent intent5 = new Intent(view.getContext(), Aid06.class); view.getContext().startActivity(intent5); break; case 6 : Intent intent6 = new Intent(view.getContext(), Aid07.class); view.getContext().startActivity(intent6); break; case 7 : Intent intent7 = new Intent(view.getContext(), Aid08.class); view.getContext().startActivity(intent7); break; case 8 : Intent intent8 = new Intent(view.getContext(), Aid09.class); view.getContext().startActivity(intent8); break; case 9 : Intent intent9 = new Intent(view.getContext(), Aid10.class); view.getContext().startActivity(intent9); break; case 10 : Intent intent10 = new Intent(view.getContext(), Aid11.class); view.getContext().startActivity(intent10); break; case 11 : Intent intent11 = new Intent(view.getContext(), Aid12.class); view.getContext().startActivity(intent11); break; case 12 : Intent intent12 = new Intent(view.getContext(), Aid13.class); view.getContext().startActivity(intent12); break; case 13 : Intent intent13 = new Intent(view.getContext(), Aid14.class); view.getContext().startActivity(intent13); break; case 14 : Intent intent14 = new Intent(view.getContext(), Aid15.class); view.getContext().startActivity(intent14); break; case 15 : Intent intent15 = new Intent(view.getContext(), Aid16.class); view.getContext().startActivity(intent15); break; case 16 : Intent intent16 = new Intent(view.getContext(), Aid17.class); view.getContext().startActivity(intent16); break; case 17 : Intent intent17 = new Intent(view.getContext(), Aid18.class); view.getContext().startActivity(intent17); break; case 18 : Intent intent18 = new Intent(view.getContext(), Aid19.class); view.getContext().startActivity(intent18); break; case 19 : Intent intent19 = new Intent(view.getContext(), Aid20.class); view.getContext().startActivity(intent19); break; case 20 : Intent intent20 = new Intent(view.getContext(), Aid21.class); view.getContext().startActivity(intent20); break; case 21 : Intent intent21 = new Intent(view.getContext(), Aid22.class); view.getContext().startActivity(intent21); break; case 22 : Intent intent22 = new Intent(view.getContext(), Aid23.class); view.getContext().startActivity(intent22); break; case 23 : Intent intent23 = new Intent(view.getContext(), Aid24.class); view.getContext().startActivity(intent23); break; case 24 : Intent intent24 = new Intent(view.getContext(), Aid25.class); view.getContext().startActivity(intent24); break; case 25 : Intent intent25 = new Intent(view.getContext(), Aid26.class); view.getContext().startActivity(intent25); break; case 26 : Intent intent26 = new Intent(view.getContext(), Aid27.class); view.getContext().startActivity(intent26); break; case 27 : Intent intent27 = new Intent(view.getContext(), Aid28.class); view.getContext().startActivity(intent27); break; case 28 : Intent intent28 = new Intent(view.getContext(), Aid29.class); view.getContext().startActivity(intent28); break; case 29 : Intent intent29 = new Intent(view.getContext(), Aid30.class); view.getContext().startActivity(intent29); break; case 30 : Intent intent30 = new Intent(view.getContext(), Aid31.class); view.getContext().startActivity(intent30); break; case 31 : Intent intent31 = new Intent(view.getContext(), Aid32.class); view.getContext().startActivity(intent31); break; case 32 : Intent intent32 = new Intent(view.getContext(), Aid33.class); view.getContext().startActivity(intent32); break; case 33 : Intent intent33 = new Intent(view.getContext(), Aid34.class); view.getContext().startActivity(intent33); break; case 34 : Intent intent34 = new Intent(view.getContext(), Aid35.class); view.getContext().startActivity(intent34); break; case 35 : Intent intent35 = new Intent(view.getContext(), Aid36.class); view.getContext().startActivity(intent35); break; case 36 : Intent intent36 = new Intent(view.getContext(), Aid37.class); view.getContext().startActivity(intent36); break; case 37 : Intent intent37 = new Intent(view.getContext(), Aid38.class); view.getContext().startActivity(intent37); break; case 38 : Intent intent38 = new Intent(view.getContext(), Aid39.class); view.getContext().startActivity(intent38); break; case 39 : Intent intent39 = new Intent(view.getContext(), Aid40.class); view.getContext().startActivity(intent39); break; case 40 : Intent intent40 = new Intent(view.getContext(), Aid41.class); view.getContext().startActivity(intent40); break; case 41 : Intent intent41 = new Intent(view.getContext(), Aid42.class); view.getContext().startActivity(intent41); break; case 42 : Intent intent42 = new Intent(view.getContext(), Aid43.class); view.getContext().startActivity(intent42); break; case 43 : Intent intent43 = new Intent(view.getContext(), Aid44.class); view.getContext().startActivity(intent43); break; } } }); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { ListView listView = mListView.get(position); holder.textView.setText(listView.getName()); } @Override public int getItemCount() { return mListView.size(); } }
public class Guitar extends Instrument { public Guitar() { super("Guitar"); } public void play() { System.out.println("strum!"); } }
package jneiva.hexbattle; public enum Time { Jogador, Computador, }
import java.util.*; class array_Test_Paper1 { public static void main(String ar[]){ Scanner sc = new Scanner(System.in); /*1. int z, x = 0; int a = 0; System.out.print("세자리 변수의 값 입력(일십백) : "); int n = sc.nextInt(); z = n/100; x = (n-z*100)/10; x = x* 10; z = z* 100; a = z+x+1; System.out.println("결과 : "+ a); */ System.out.print("화씨 온도 입력 : "); int tem = sc.nextInt(); float sub = 0; sub = (float)(tem - 32) * 18 / 10; System.out.println(tem + "의 섭씨 온도 : "+sub); } }
package com.tencent.mm.plugin.appbrand.game.page; import com.tencent.mm.plugin.appbrand.game.page.WAGamePageViewContainerLayout.b; interface WAGamePageViewContainerLayout$a { void a(b bVar, b bVar2); }
package com.tencent.mm.plugin.sight.encode.ui; import java.util.List; public interface d$a { void bwu(); void bwv(); void ce(List<String> list); }
package es.bvalero.cifras.solvers.intarray; import static es.bvalero.cifras.solvers.intarray.IntArraySolution.ADDITION; import static es.bvalero.cifras.solvers.intarray.IntArraySolution.DIVISION; import static es.bvalero.cifras.solvers.intarray.IntArraySolution.MULTIPLICATION; import static es.bvalero.cifras.solvers.intarray.IntArraySolution.SUBTRACTION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Test; public class IntArraySolutionTest { private static final int THREE = 3; private static final int FIVE = 5; private static final int SIX = 6; @Test public final void testMonomial() { final int[] monomial = { 1 }; final IntArraySolution monomialSolution = new IntArraySolution(monomial); assertEquals(monomialSolution.getResult(), Integer.valueOf(1)); } @Test public final void testBinomial() { final int[] binomial = { 1, 2, ADDITION }; final IntArraySolution binomialSolution = new IntArraySolution(binomial); assertEquals(binomialSolution.getResult(), Integer.valueOf(1 + 2)); } @Test public final void testMonomialOpBinomial() { final int[] array = { 1, THREE, FIVE, MULTIPLICATION, ADDITION }; final IntArraySolution solution = new IntArraySolution(array); assertEquals(solution.getResult(), Integer.valueOf(1 + (THREE * FIVE))); } @Test public final void testBinomialOpMonomial() { final int[] array = { 1, THREE, ADDITION, FIVE, MULTIPLICATION }; final IntArraySolution solution = new IntArraySolution(array); assertEquals(solution.getResult(), Integer.valueOf((1 + THREE) * FIVE)); } @Test public final void testBinomialOpBinomial() { final int[] array = { 2, THREE, ADDITION, SIX, 1, SUBTRACTION, MULTIPLICATION }; final IntArraySolution solution = new IntArraySolution(array); assertEquals(solution.getResult(), Integer.valueOf((2 + THREE) * (SIX - 1))); } @Test public final void testOnlyOperation() { final int[] array = { -1 }; final IntArraySolution solution = new IntArraySolution(array); assertNull(solution.getResult()); } @Test public final void testInexistentOperation() { final int[] array = { 1, 2, -5 }; final IntArraySolution solution = new IntArraySolution(array); assertNull(solution.getResult()); } @Test public final void testBinomialDivision() { final int[] array = { SIX, THREE, DIVISION }; final IntArraySolution solution = new IntArraySolution(array); assertEquals(solution.getResult(), Integer.valueOf(SIX / THREE)); } @Test public final void testBinomialNonDivision() { final int[] array = { SIX, 4, DIVISION }; final IntArraySolution solution = new IntArraySolution(array); assertNull(solution.getResult()); } }