text
stringlengths
10
2.72M
package Model.DAO; import Model.Game; import Model.GameSession; import Model.PlaySession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.util.ArrayList; import java.util.List; @Component public class JDBCGameSessionDAO implements GameSessionDAO { private JdbcTemplate jdbcTemplate; @Autowired public JDBCGameSessionDAO(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } @Override public void startNewGameSession(PlaySession session, Game game, String gameSelectionType) { String newSqlRow = "INSERT INTO game_session (session_id, game_id, game_selection_type) VALUES (?,?,?);"; jdbcTemplate.update(newSqlRow, session.getSessionId(), game.getGameId(), gameSelectionType); } @Override public List<GameSession> getGameSessionByGame(Game game) { String getSessionsByGame = "SELECT * FROM game_session WHERE game_id = ?;"; SqlRowSet sessions = jdbcTemplate.queryForRowSet(getSessionsByGame, game.getGameId()); List<GameSession> sessionsWithGameX = new ArrayList<>(); GameSession thisSession; while (sessions.next()) { thisSession = new GameSession(); thisSession.setGameSessionId(sessions.getInt("game_session_id")); thisSession.setPlaySessionId(sessions.getInt("session_id")); thisSession.setGameId(sessions.getInt("game_id")); thisSession.setGameSelectionType(sessions.getString("game_selection_type")); sessionsWithGameX.add(thisSession); } return sessionsWithGameX; } @Override public List<GameSession> getGameSessionBySelectionType(String gameSelectionType) { String sqlGetSessionsBySelection = "SELECT * FROM game_session WHERE game_selection_type = ?;"; SqlRowSet sessions = jdbcTemplate.queryForRowSet(sqlGetSessionsBySelection, gameSelectionType); List<GameSession> sessionsBySelection = new ArrayList<>(); GameSession thisSession; while (sessions.next()) { thisSession = new GameSession(); thisSession.setGameSessionId(sessions.getInt("game_session_id")); thisSession.setPlaySessionId(sessions.getInt("session_id")); thisSession.setGameId(sessions.getInt("game_id")); thisSession.setGameSelectionType(sessions.getString("game_selection_type")); sessionsBySelection.add(thisSession); } return sessionsBySelection; } @Override public void updateGameSession(GameSession gameSession) { jdbcTemplate.update("BEGIN TRANSACTION; UPDATE game_session SET session_id = ?, game_id = ?, game_selection_type = ?; COMMIT;" + "WHERE game_session_id = ?;", gameSession.getPlaySessionId(), gameSession.getGameId(), gameSession.getGameSelectionType(), gameSession.getGameSessionId()); } @Override public void deleteGameSession(GameSession gameSession) { jdbcTemplate.update("DELETE * FROM game_session WHERE game_session_id = ?;", gameSession.getGameSessionId()); } }
package com.jbico.myspringsecurity.web.controller; public abstract class BaseWebController { }
package com.needii.dashboard.model; import javax.persistence.*; /** * The persistent class for the admins database table. * */ @Entity @Table(name="shippers_price_day") @NamedQuery(name="ShippersPriceDay.findAll", query="SELECT s FROM ShippersPriceDay s") public class ShippersPriceDay extends BaseModel { private static final long serialVersionUID = 1L; @Id @Column(name="id") @GeneratedValue(strategy= GenerationType.IDENTITY) private long id; @Column(name = "price_day") private Long priceDay; public long getId() { return id; } public void setId(long id) { this.id = id; } public Long getPriceDay() { return priceDay; } public void setPriceDay(Long priceDay) { this.priceDay = priceDay; } }
//논리연산 package com.eomcs.basic.ex05test; public class Exam0310 { public static void main(String[] args) { //And연산 둘다 트루여야 트루 System.out.println(true && true); System.out.println(true && false); System.out.println(false && true); System.out.println(false && false); System.out.println("-----------------"); System.out.println(); //Or연산자 둘중하나만 트루라면 트루 System.out.println(true || true); System.out.println(true || false); System.out.println(false || true); System.out.println(false || false); System.out.println("-------------"); //Not 연산자 반대로 System.out.println(!true); System.out.println(!false); System.out.println("------------"); //Xor 연산자 두개값이 달라야 트루 System.out.println( true ^ true); System.out.println( false ^ false); System.out.println(true ^ false); } }
package com.younchen.younsampleproject; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); StringBuilder ids = new StringBuilder(); ids.append("("); for (int i = 0; i < 10; i++) { //ids.append(i).append(","); ids.append('\'').append(i).append('\'').append(","); } ids.deleteCharAt(ids.length() - 1).append(")"); System.out.println(ids.toString()); } }
package org.valdi.entities.management.hooks; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.valdi.entities.iDisguise; public class ScoreboardHooks { public static boolean nametagEdit = false; public static boolean coloredTags = false; public static void setup() { nametagEdit = Bukkit.getPluginManager().getPlugin("NametagEdit") != null; coloredTags = Bukkit.getPluginManager().getPlugin("ColoredTags") != null; } public static void updatePlayer(final Player player) { if(nametagEdit) { final com.nametagedit.plugin.NametagEdit plugin = (com.nametagedit.plugin.NametagEdit)Bukkit.getPluginManager().getPlugin("NametagEdit"); plugin.getHandler().getNametagManager().reset(player.getName()); Bukkit.getScheduler().runTaskLaterAsynchronously(iDisguise.getInstance(), new Runnable() { public void run() { plugin.getHandler().applyTagToPlayer(player, false); } }, 5L); } if(coloredTags) { Bukkit.getScheduler().runTaskLater(iDisguise.getInstance(), new Runnable() { public void run() { com.gmail.filoghost.coloredtags.ColoredTags.updateNametag(player); com.gmail.filoghost.coloredtags.ColoredTags.updateTab(player); } }, 5L); } } }
package cttd.cryptography.demo; import java.util.HashMap; import java.util.Map; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTCreationException; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; public class JavaJwtDemo { private static final String SECRET_KEY = "keep_it_secret"; private static void sign() { try { Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); Map<String, Object> headerClaims = new HashMap<>(); headerClaims.put("owner", "auth0"); String token = JWT.create() .withIssuer("auth0") .withHeader(headerClaims) .withClaim("isAdmin", 123) .withArrayClaim("array", new Integer[] { 1, 2, 3 }) .sign(algorithm); System.out.println(token); } catch (JWTCreationException exception) { // Invalid Signing configuration / Couldn't convert Claims. exception.printStackTrace(); } } private static void verify() { String token = "eyJvd25lciI6ImF1dGgwIiwiYWxnIjoiSFMyNTYiLCJ0eXAiOiJKV1QifQ.eyJhcnJheSI6WzEsMiwzXSwiaXNzIjoiYXV0aDAiLCJpc0FkbWluIjoxMjN9.ISM7zUWpGePCgY_64kEt-5I2W4Oatu7pzqims3Z5hQM"; try { Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); JWTVerifier verifier = JWT.require(algorithm) .withIssuer("auth0") .build(); // Reusable verifier instance DecodedJWT jwt = verifier.verify(token); System.out.println(jwt.getAlgorithm() + "\n" + jwt.getType() + "\n" + jwt.getContentType() + "\n" + jwt.getKeyId() + "\n" + jwt.getHeaderClaim("owner") + "\n" + jwt.getIssuer() + "\n" + jwt.getSubject() + "\n" + jwt.getAudience() + "\n" + jwt.getExpiresAt() + "\n" + jwt.getNotBefore() + "\n" + jwt.getIssuedAt() + "\n" + jwt.getId() + "\n"); Map<String, Claim> claims = jwt.getClaims(); // Key is the Claim name Claim claim = claims.get("isAdmin"); System.out.println(claim.asInt()); } catch (JWTVerificationException exception) { exception.printStackTrace(); // Invalid signature/claims } } public static void main(String[] args) { sign(); verify(); } }
package at.sync.app; import at.sync.controller.OSMSyncController; import at.sync.util.SyncLogger; /** * PostgisSync application */ public class boot { public static void main(String[] args) { // try { // OSMSyncController.getInstance().fetchDataByRegion("Götzis"); // OSMSyncController.getInstance().startSyncronisation("Götzis", true); // } catch (Exception e) { // SyncLogger.log(e); // } // first step: get all types > show mapping view (combobox) return; } }
package com.dbs.portal.ui.component.application; import com.dbs.portal.ui.component.menu.MenuItem; public interface IMenuApplication extends IApplication { public boolean addFavouriteMenuItem(MenuItem item); public boolean removeFavouritemMenuItem(MenuItem item); }
package com.sunny.netty.chat.client.handler; import com.sunny.netty.chat.protocol.response.MessageResponsePacket; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; /** * <Description> <br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/10/26 16:17 <br> * @see com.sunny.netty.chat.client.handler <br> */ public class MessageResponseHandler extends SimpleChannelInboundHandler<MessageResponsePacket> { @Override protected void channelRead0(ChannelHandlerContext ctx, MessageResponsePacket messageResponsePacket) { String fromUserId = messageResponsePacket.getFromUserId(); String fromUserName = messageResponsePacket.getFromUserName(); System.out.println(fromUserId + ":" + fromUserName + " -> " + messageResponsePacket .getMessage()); } }
package org.sql2o.converters; import org.codehaus.jackson.JsonFactory; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.map.ObjectMapper; import org.postgresql.util.PGobject; public class JsonNodeConverter implements Converter<JsonNode> { public JsonNode convert(Object val) throws ConverterException { if(val == null) return null; if(JsonNode.class.isAssignableFrom(val.getClass())) { return (JsonNode)val; } if(PGobject.class.equals(val.getClass())) { String jsonString = ((PGobject)val).getValue(); ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead try { JsonParser parser = factory.createJsonParser(jsonString); return mapper.readTree(parser); } catch(Exception e) { throw new ConverterException("Error parsing JSON", e); } } if(String.class.equals(val.getClass())) { String jsonString = (String)val; ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead try { JsonParser parser = factory.createJsonParser(jsonString); return mapper.readTree(parser); } catch(Exception e) { throw new ConverterException("Error parsing JSON", e); } } throw new ConverterException("Unable to convert: " + val.getClass().getCanonicalName() + " to JsonNode"); } }
package com.xyt.service; import java.io.Serializable; import com.xyt.model.Usertbl; import com.xyt.pageModel.User; public interface UserService { public void insertUser(User user); public Serializable save(Usertbl t); public boolean login(String userid); }
package com.legaoyi.message.ext.service.impl; import org.springframework.stereotype.Service; import com.legaoyi.platform.ext.service.impl.DefaultMongoExtendServiceImpl; /** * @author gaoshengbo */ @Service("accStateLogExtendService") public class AccStateLogExtendServiceImpl extends DefaultMongoExtendServiceImpl { @Override protected String getEntityName() { return "acc_state_logs_"; } }
package org.hackerrank.test; import java.util.ArrayList; import java.util.List; import static java.lang.System.out; /** * @author Created by Vitalij Radchenko on 01.05.18. */ public class OddNumbersTask { /** * Produce odd numbers from a range * @param l left value of range * @param r right value of range * @return Array odd numbers */ int[] genOddNumbers(int l, int r) { List<Integer> intRange = new ArrayList<>(); for(int n=l; n<=r; n++) { if(n%2==1) { intRange.add(n); } } int[] arrInt = new int[intRange.size()]; for(int n=0; n<intRange.size(); n++) { arrInt[n] = intRange.get(n); } return arrInt; } public static void main(String[] args) { OddNumbersTask numberTask = new OddNumbersTask(); for(int num : numberTask.genOddNumbers(2, 5)) { out.println(num); } } }
/** * "Visual Paradigm: DO NOT MODIFY THIS FILE!" * * This is an automatic generated file. It will be regenerated every time * you generate persistence class. * * Modifying its content may cause the program not work, or your work may lost. */ /** * Licensee: Juan José(University of Almeria) * License Type: Academic */ package database; import org.hibernate.Criteria; import org.orm.PersistentException; import org.orm.PersistentSession; import org.orm.criteria.*; public class Usuario_registradoCriteria extends AbstractORMCriteria { public final IntegerExpression ID; public final StringExpression nombre; public final StringExpression apellido; public final StringExpression email; public final StringExpression contrasenia; public final StringExpression apodo; public final StringExpression avatar; public final IntegerExpression id_Usuario_registrado; public final StringExpression anio; public final IntegerExpression numeroVisitas; public final IntegerExpression edad; public final CollectionExpression suscrito; public final CollectionExpression comentarios; public final CollectionExpression videos_que_gustan; public final CollectionExpression video_subido; public final CollectionExpression video_visualizado; public final CollectionExpression listas_de_reproduccion; public final CollectionExpression suscriptor; public final IntegerExpression historial_usuarioId; public final AssociationExpression historial_usuario; public Usuario_registradoCriteria(Criteria criteria) { super(criteria); ID = new IntegerExpression("ID", this); nombre = new StringExpression("nombre", this); apellido = new StringExpression("apellido", this); email = new StringExpression("email", this); contrasenia = new StringExpression("contrasenia", this); apodo = new StringExpression("apodo", this); avatar = new StringExpression("avatar", this); id_Usuario_registrado = new IntegerExpression("id_Usuario_registrado", this); anio = new StringExpression("anio", this); numeroVisitas = new IntegerExpression("numeroVisitas", this); edad = new IntegerExpression("edad", this); suscrito = new CollectionExpression("ORM_suscrito", this); comentarios = new CollectionExpression("ORM_comentarios", this); videos_que_gustan = new CollectionExpression("ORM_videos_que_gustan", this); video_subido = new CollectionExpression("ORM_video_subido", this); video_visualizado = new CollectionExpression("ORM_video_visualizado", this); listas_de_reproduccion = new CollectionExpression("ORM_listas_de_reproduccion", this); suscriptor = new CollectionExpression("ORM_suscriptor", this); historial_usuarioId = new IntegerExpression("historial_usuario.", this); historial_usuario = new AssociationExpression("historial_usuario", this); } public Usuario_registradoCriteria(PersistentSession session) { this(session.createCriteria(Usuario_registrado.class)); } public Usuario_registradoCriteria() throws PersistentException { this(ProyectoMDSPersistentManager.instance().getSession()); } public Usuario_registradoCriteria createSuscritoCriteria() { return new Usuario_registradoCriteria(createCriteria("ORM_suscrito")); } public ComentariosCriteria createComentariosCriteria() { return new ComentariosCriteria(createCriteria("ORM_comentarios")); } public VideosCriteria createVideos_que_gustanCriteria() { return new VideosCriteria(createCriteria("ORM_videos_que_gustan")); } public VideosCriteria createVideo_subidoCriteria() { return new VideosCriteria(createCriteria("ORM_video_subido")); } public VideosCriteria createVideo_visualizadoCriteria() { return new VideosCriteria(createCriteria("ORM_video_visualizado")); } public Listas_de_reproduccionCriteria createListas_de_reproduccionCriteria() { return new Listas_de_reproduccionCriteria(createCriteria("ORM_listas_de_reproduccion")); } public Usuario_registradoCriteria createSuscriptorCriteria() { return new Usuario_registradoCriteria(createCriteria("ORM_suscriptor")); } public Listas_de_reproduccionCriteria createHistorial_usuarioCriteria() { return new Listas_de_reproduccionCriteria(createCriteria("historial_usuario")); } public Usuario_registrado uniqueUsuario_registrado() { return (Usuario_registrado) super.uniqueResult(); } public Usuario_registrado[] listUsuario_registrado() { java.util.List list = super.list(); return (Usuario_registrado[]) list.toArray(new Usuario_registrado[list.size()]); } }
package com.example.km.genericapp.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import com.example.km.genericapp.R; import com.example.km.genericapp.adapters.RecipeAdapter; import com.example.km.genericapp.constants.Constants; import com.example.km.genericapp.models.recipes.Recipes; import com.example.km.genericapp.network.RecipeApiService; import com.example.km.genericapp.utilities.SnackbarHelper; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; public class RecipesFragment extends Fragment { private View progressOverlay; private RecyclerView recyclerView; private CompositeDisposable disposables; private RecipeAdapter adapter; protected EditText searchText; private ProgressBar searchProgressBar; private ImageButton searchClearButton; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); View view = inflater.inflate(R.layout.fragment_recipes, container, false); setupScreenLayout(view); disposables = new CompositeDisposable(); initializeRecyclerView(); loadRecipes(Constants.EMPTY_STRING); return view; } private void initializeRecyclerView() { recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); } private void loadRecipes(String query) { showProgressIndicator(); disposables.add(RecipeApiService.getRecipes(query) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableObserver<Recipes>() { @Override public void onComplete() { hideProgressIndicator(); } @Override public void onError(Throwable throwable) { handleError(throwable); } @Override public void onNext(Recipes recipes) { handleResponse(recipes); } })); } private void handleResponse(Recipes recipes) { adapter = new RecipeAdapter(recipes); recyclerView.setAdapter(adapter); } private void handleError(Throwable error) { SnackbarHelper.showSnackbar(getActivity(), recyclerView, getActivity().getString(R.string.api_call_error) + error.getLocalizedMessage()); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); menu.clear(); inflater.inflate(R.menu.menu_main, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: getActivity().finish(); return true; case R.id.action_home: return true; case R.id.action_settings: return true; default: return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroy() { super.onDestroy(); disposables.clear(); } public void showProgressIndicator() { searchProgressBar.setVisibility(View.VISIBLE); } public void hideProgressIndicator() { searchProgressBar.setVisibility(View.GONE); } private void setupScreenLayout(View view) { progressOverlay = view.findViewById(R.id.progressOverlay); recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); searchProgressBar = (ProgressBar) view.findViewById(R.id.searchProgressBar); searchClearButton = (ImageButton) view.findViewById(R.id.searchClearButton); searchText = (EditText) view.findViewById(R.id.searchEditText); searchText.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { handleSearchTextUpdate(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); searchClearButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { searchText.setText(Constants.EMPTY_STRING); } }); //noinspection deprecation searchProgressBar.getIndeterminateDrawable().setColorFilter( getResources().getColor(R.color.colorAccent), android.graphics.PorterDuff.Mode.MULTIPLY); } private void handleSearchTextUpdate() { final String query = searchText.getText().toString(); if (TextUtils.isEmpty(query)) { searchClearButton.setVisibility(View.GONE); } else { searchClearButton.setVisibility(View.VISIBLE); } loadRecipes(query); } }
package application; import java.io.File; public interface Factory { public File openFile(); public void importFile(); }
package com.example.suneel.musicapp.Activities; import android.annotation.SuppressLint; import android.app.ActivityManager; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.provider.MediaStore; import android.speech.RecognizerIntent; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.content.FileProvider; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.text.method.KeyListener; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.suneel.musicapp.Database.GetSongData; import com.example.suneel.musicapp.Utils.Utilities; import com.example.suneel.musicapp.Utils.Utils; import com.example.suneel.musicapp.models.SongDataModel; import com.getkeepsafe.taptargetview.TapTarget; import com.getkeepsafe.taptargetview.TapTargetSequence; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.util.ExponentialBackOff; import com.miguelcatalan.materialsearchview.MaterialSearchView; import com.sothree.slidinguppanel.SlidingUpPanelLayout.PanelState; import com.example.suneel.musicapp.Adapters.SearchAdapter; import com.example.suneel.musicapp.Adapters.SelectSongAdapter; import com.example.suneel.musicapp.Database.DatabaseHelper; import com.example.suneel.musicapp.Database.Getmusic; import com.example.suneel.musicapp.Fragments.Album; import com.example.suneel.musicapp.Fragments.Artist; import com.example.suneel.musicapp.Fragments.Genres; import com.example.suneel.musicapp.Fragments.MyDialog; import com.example.suneel.musicapp.Fragments.Playlist; import com.example.suneel.musicapp.Fragments.SelectPlaylist; import com.example.suneel.musicapp.Fragments.Songs; import com.example.suneel.musicapp.R; import com.example.suneel.musicapp.Services.MusicService; import com.example.suneel.musicapp.models.PlayListStore; import com.example.suneel.musicapp.models.SongList; import com.example.suneel.musicapp.models.SongModel; import com.sothree.slidinguppanel.SlidingUpPanelLayout; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import de.hdodenhof.circleimageview.CircleImageView; import me.itangqi.waveloadingview.WaveLoadingView; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { private static final int MY_PERMISSION_REQUEST = 1; private RecyclerView recyclerView,recyclerView1; private SearchAdapter adapter; private SearchView searchView; private TextView contentText, dname; private Toolbar toolbar,toolbar1; private TabLayout tabLayout,tabLayout1; private ViewPager viewPager,viewPager1; private ActionModeCallback actionModeCallback; private ActionMode actionMode; LinearLayout frame,frame1; Bundle base; Menu menu; FragmentManager mMangaer; private final int REQ_CODE_SPEECH_INPUT = 100; private final String voiceValue = ""; FragmentTransaction myfragmentTransaction; EditText songType; String playname; private String playlistname; SelectSongAdapter songadapter; List<SongModel> selectedSong; Intent playIntent; private MyDialog mydailog; private boolean mActionModeIsActive = false; android.app.FragmentManager manger; private KeyListener originalKeyListener; private DrawerLayout dl; private ActionBarDrawerToggle abdt; private ViewPagerAdapter viewPagerAdapter; PlalistItem item = new PlalistItem(); Getmusic help; SQLiteDatabase db; private ArrayList<String> tester; private ImageView contentviewImage; private SelectPlaylist selectplaylist; private RecyclerView selectsongrecycle,selectsongrecycle1; private boolean stateSelection = false; private int count = 0; private SongModel smodel; private LinearLayout layoutmain, dragView, listview; private LinearLayout layoutselectsong,layoutselectsong1; private SongModel songModel; private int addnewplaylistsongposition; private RelativeLayout searchbarview; public SlidingUpPanelLayout slidingUpPanelLayout; private static final String ACTION_VOICE_SEARCH = "com.google.android.gms.actions.SEARCH_ACTION"; TextView stitle, sartist, starttime, endtime; CircleImageView simage; Button play, backbtn, fwdbtn, btnRepeat, btnShuffle; SeekBar updater; Utilities utils; DatabaseHelper helper; private int position; private boolean isShuffle = false; private boolean isRepeat = false; public static MainActivity instance; private MusicService player; boolean serviceBound = false; private String s; private String category; private ArrayList<SongModel> sList; private WaveLoadingView waveLoadingView; private GetSongData getSongData; private ArrayList<SongModel> totalsongList; private int requestCode; private String totalprogress; private String currentprogress; private String oldsongname; public int progress=0; private Intent intent; public static Handler hand; private Button smallbtnplay; private MaterialSearchView searchview,searchview1; private LinearLayout smallview; private RelativeLayout mainframe; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.base = savedInstanceState; instance = this; setContentView(R.layout.dummy); utils = new Utilities(); hand = new Handler(); slidingUpPanelLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout); slidingUpPanelLayout.setVisibility(View.GONE); if (getIntent() != null) { requestCode = getIntent().getIntExtra("requestcode", 0); category = getIntent().getStringExtra("category"); playlistname = getIntent().getStringExtra("name"); position = getIntent().getIntExtra("value", 0); } help = new Getmusic(this); getSongData = new GetSongData(this); db = help.getWritableDatabase(); tester = new ArrayList<>(); dl = (DrawerLayout) findViewById(R.id.dl); mainframe=(RelativeLayout)findViewById(R.id.main_frame); hand=new Handler(); dragView = (LinearLayout) findViewById(R.id.dragView); searchview = (MaterialSearchView) findViewById(R.id.search_view); searchview1 = (MaterialSearchView) findViewById(R.id.search_view1); listview = (LinearLayout) findViewById(R.id.list); contentText = (TextView) findViewById(R.id.contentviewtext); dname = (TextView) findViewById(R.id.dname); contentviewImage = (ImageView) findViewById(R.id.contentviewimage); layoutmain = (LinearLayout) findViewById(R.id.lineartab); layoutselectsong = (LinearLayout) findViewById(R.id.removetab); layoutselectsong1 = (LinearLayout) findViewById(R.id.removetab1); selectsongrecycle = (RecyclerView) findViewById(R.id.rsongViewaction); selectsongrecycle1 = (RecyclerView) findViewById(R.id.rsongViewaction1); layoutselectsong.setVisibility(View.GONE); layoutmain.setVisibility(View.VISIBLE); recyclerView = (RecyclerView) findViewById(R.id.rsongView); recyclerView1 = (RecyclerView) findViewById(R.id.rsongView1); playIntent = getIntent(); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView1.setHasFixedSize(true); recyclerView1.setLayoutManager(new LinearLayoutManager(this)); toolbar = (Toolbar) findViewById(R.id.toolbar); //setSupportActionBar(toolbar); toolbar1 = (Toolbar) findViewById(R.id.toolbar1); //setSupportActionBar(toolbar1); viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); viewPager1 = (ViewPager) findViewById(R.id.viewpager1); setupViewPager(viewPager1); tabLayout1 = (TabLayout) findViewById(R.id.tabs1); tabLayout1.setupWithViewPager(viewPager1); actionModeCallback = new ActionModeCallback(); frame = (LinearLayout) findViewById(R.id.container); frame1 = (LinearLayout) findViewById(R.id.container1); mMangaer = getSupportFragmentManager(); count = 0; if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST); } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST); } } else { getMusic(); } OpenNavigation(); final NavigationView nav_view = (NavigationView) findViewById(R.id.nav_view); nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if(slidingUpPanelLayout.getVisibility()==View.GONE) { if (id == R.id.song1) { viewPager.setCurrentItem(0); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.playlist1) { viewPager.setCurrentItem(4); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.artists1) { viewPager.setCurrentItem(3); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.genres1) { viewPager.setCurrentItem(1); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.albums1) { viewPager.setCurrentItem(2); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.youtubeid) { /* dl.closeDrawer(Gravity.LEFT);*/ Intent intent = new Intent(MainActivity.this, Youtube.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } return true; }else{ if (id == R.id.song1) { viewPager1.setCurrentItem(0); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.playlist1) { viewPager1.setCurrentItem(4); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.artists1) { viewPager1.setCurrentItem(3); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.genres1) { viewPager1.setCurrentItem(1); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.albums1) { viewPager1.setCurrentItem(2); dl.closeDrawer(Gravity.LEFT); } if (id == R.id.youtubeid) { /* dl.closeDrawer(Gravity.LEFT);*/ Intent intent = new Intent(MainActivity.this, Youtube.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } return true; } } }); waveLoadingView = (WaveLoadingView) findViewById(R.id.waveloading); updater = (SeekBar) findViewById(R.id.Songrun); stitle = (TextView) findViewById(R.id.dname); sartist = (TextView) findViewById(R.id.dartist); simage = (CircleImageView) findViewById(R.id.SongImage); starttime = (TextView) findViewById(R.id.start); backbtn = (Button) findViewById(R.id.BackBtn); fwdbtn = (Button) findViewById(R.id.FwdBtn); endtime = (TextView) findViewById(R.id.end); play = (Button) findViewById(R.id.PlayBtn); smallbtnplay=(Button)findViewById(R.id.smallplaybtn); updater.setOnSeekBarChangeListener(this); play.setBackgroundResource(R.drawable.ic_pause); smallbtnplay.setBackgroundResource(R.drawable.ic_pause); btnRepeat = (Button) findViewById(R.id.Repeat); btnShuffle = (Button) findViewById(R.id.Shuffle); btnRepeat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (btnRepeat.isSelected()) { btnRepeat.setSelected(false); } else btnRepeat.setSelected(true); if (isRepeat) { if (player != null) { isRepeat = false; player.getRepeat(isRepeat); Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show(); } } else { // make repeat to true if (player != null) { isRepeat = true; player.getRepeat(isRepeat); isShuffle = false; btnShuffle.setSelected(false); player.getShuffle(isShuffle); Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show(); // make shuffle to false } } } }); btnShuffle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { if (btnShuffle.isSelected()) { btnShuffle.setSelected(false); } else btnShuffle.setSelected(true); if (isShuffle) { if (player != null) { isShuffle = false; player.getShuffle(isShuffle); Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show(); } } else { // make repeat to true if (player != null) { isShuffle = true; player.getShuffle(isShuffle); Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show(); isRepeat = false; btnRepeat.setSelected(false); player.getRepeat(isRepeat); // make shuffle to false } } } }); fwdbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // check if next song is there or not nextSong(); } }); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // check for already playing playpause(); } }); smallbtnplay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { playpause(); } }); /** * Back button click event * Plays previous song by currentSongIndex - 1 * */ backbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { previousSong(); } }); /* new TapTargetSequence(this) .targets( TapTarget.forView(findViewById(R.id.search_view), "You", "Up") .dimColor(android.R.color.background_dark) .outerCircleColor(R.color.white) .targetCircleColor(R.color.colorAccent) .textColor(android.R.color.black)) .listener(new TapTargetSequence.Listener() { // This listener will tell us when interesting(tm) events happen in regards // to the sequence @Override public void onSequenceFinish() { // Yay } @Override public void onSequenceStep(TapTarget lastTarget, boolean targetClicked) { } @Override public void onSequenceCanceled(TapTarget lastTarget) { // Boo } });*/ } public void addSongintonewplaylist(int getUri, String playname) { DatabaseHelper help = new DatabaseHelper(this); SQLiteDatabase db = help.getWritableDatabase(); ContentValues values = new ContentValues(); // `id` and `timestamp` will be inserted automatically. // no need to add them values.put(PlayListStore.PLAYLIST_ID, playname); values.put(PlayListStore.SONG_NAME, sList.get(getUri).getTitle()); values.put(PlayListStore.SONG_ARTIST, sList.get(getUri).getArtist()); values.put(PlayListStore.SONG_LOCATION, sList.get(getUri).getLocation()); values.put(PlayListStore.SONG_URI, String.valueOf(sList.get(getUri).getUri())); values.put(PlayListStore.SONG_IMAGE, getBitmapAsByteArray(sList.get(getUri).getImage())); // insert row db.insert(PlayListStore.TABLE_NAME, null, values); // close db connection db.close(); Toast.makeText(this, "Playlist Created", Toast.LENGTH_SHORT).show(); } public void OpenSliding() { slidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED); } private void OpenNavigation() { if(slidingUpPanelLayout.getVisibility()==View.GONE) abdt = new ActionBarDrawerToggle(this, dl, toolbar, R.string.Open, R.string.Close); else abdt = new ActionBarDrawerToggle(this, dl, toolbar1, R.string.Open, R.string.Close); abdt.setDrawerIndicatorEnabled(true); dl.addDrawerListener(abdt); abdt.syncState(); } @SuppressLint("MissingSuperCall") @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); abdt.syncState(); } public void getMusic() { sList = new ArrayList<>(); totalsongList = new ArrayList<>(); String selectQuery = "SELECT * FROM " + SongList.TABLE_NAME; Log.e("QUERY_____", selectQuery); try { Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { if (cursor == null) Toast.makeText(MainActivity.this, cursor.getCount() + "Cursor values", Toast.LENGTH_SHORT).show(); // looping through all rows and adding to list else { if (cursor.moveToFirst()) { do { String id = cursor.getString(cursor.getColumnIndex(SongList.SONG_ID)); String title = cursor.getString(cursor.getColumnIndex(SongList.SONG_NAME)); String location = cursor.getString(cursor.getColumnIndex(SongList.SONG_LOCATION)); Uri uri = Uri.parse(cursor.getString(cursor.getColumnIndex(SongList.SONG_URI))); byte[] blob = cursor.getBlob(cursor.getColumnIndex(SongList.SONG_IMAGE)); ByteArrayInputStream inputStream = new ByteArrayInputStream(blob); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); String artistid = cursor.getString(cursor.getColumnIndex(SongList.ARTIST_ID)); String artist = cursor.getString(cursor.getColumnIndex(SongList.ARTIST)); String albumid = cursor.getString(cursor.getColumnIndex(SongList.ALBUM_ID)); String album = cursor.getString(cursor.getColumnIndex(SongList.ALBUM)); String genres = cursor.getString(cursor.getColumnIndex(SongList.GENRES)); sList.add(new SongModel(id, title, location, uri, bitmap, artistid, artist, albumid, album, genres, false)); totalsongList.add(new SongModel(id, title, location, uri, bitmap, artistid, artist, albumid, album, genres, false)); } while (cursor.moveToNext()); } // close db connection db.close(); } } while (cursor.moveToNext()); } } catch (IllegalStateException e) { e.printStackTrace(); } } public void openpopup(final SongModel smodel, final int position, View view, final Fragment songsContext) { final PopupMenu popup = new PopupMenu(this, view); //Inflating the Popup using xml file popup.getMenuInflater() .inflate(R.menu.popup, popup.getMenu()); //registering popup with OnMenuItemClickListener popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.share: Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.putExtra(Intent.EXTRA_STREAM, sList.get(position).getUri()); sharingIntent.setType("audio/mp3"); sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); startActivity(Intent.createChooser(sharingIntent, "Share via")); popup.dismiss(); break; case R.id.addtoplaylist: Bundle bundle = new Bundle(); bundle.putInt("songuri", position); manger = getFragmentManager(); selectplaylist = new SelectPlaylist(); selectplaylist.show(manger, "MyPlaylist"); selectplaylist.setArguments(bundle); popup.dismiss(); break; case R.id.remove: deleteSong(smodel,position,songsContext); popup.dismiss(); break; } return true; } }); popup.show(); } private void deleteSong(SongModel smodel,int position,Fragment songs) { try { if (songs instanceof Songs && songs != null) { final String where = MediaStore.Audio.Media.TITLE + "='" + smodel.getTitle() + "'"; Uri uri = smodel.getUri(); getPermissions(); getContentResolver().delete(uri, where, null); deleteRow(smodel.getTitle()); sList.remove(smodel); ((Songs) songs).notifyDb(position); Toast.makeText(this, "song deleted", Toast.LENGTH_SHORT).show(); } }catch(IllegalStateException e){ e.getMessage(); } } public void deleteRow(String value) { db = help.getWritableDatabase(); db.execSQL("delete from "+SongList.TABLE_NAME+" where song_name='"+value+"'"); db.close(); } private void getPermissions() { if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST); } else { ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST); } } else { } } @Override public boolean onCreateOptionsMenu(final Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); this.menu = menu; MenuItem item = menu.findItem(R.id.search); if(slidingUpPanelLayout.getVisibility()==View.GONE) { searchview.setMenuItem(item); searchview.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (!searchView.isIconified()) { searchView.setIconified(true); } //Do some magic return false; } @Override public boolean onQueryTextChange(String newText) { final List<SongModel> filteredModelList = filter(sList, newText); if (newText.isEmpty()) { recyclerView.setVisibility(View.GONE); } else { recyclerView.setVisibility(View.VISIBLE); adapter = new SearchAdapter(MainActivity.this, totalsongList); adapter.setFilter(filteredModelList); recyclerView.setAdapter(adapter); } //Do some magic return false; } }); searchview.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() { @Override public void onSearchViewShown() { tabLayout.setVisibility(View.GONE); viewPager.setVisibility(View.GONE); frame.setVisibility(View.VISIBLE); //setItemsVisibility(menu, search, false); //Do some magic } @Override public void onSearchViewClosed() { tabLayout.setVisibility(View.VISIBLE); viewPager.setVisibility(View.VISIBLE); //layoutmain.setVisibility(View.VISIBLE); frame.setVisibility(View.GONE); //setItemsVisibility(menu, searchview, true); //Do some magic } }); }else{ searchview1.setMenuItem(item); searchview1.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (!searchView.isIconified()) { searchView.setIconified(true); } //Do some magic return false; } @Override public boolean onQueryTextChange(String newText) { final List<SongModel> filteredModelList = filter(sList, newText); if (newText.isEmpty()) { recyclerView1.setVisibility(View.GONE); } else { recyclerView1.setVisibility(View.VISIBLE); adapter = new SearchAdapter(MainActivity.this, totalsongList); adapter.setFilter(filteredModelList); recyclerView1.setAdapter(adapter); } //Do some magic return false; } }); searchview1.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() { @Override public void onSearchViewShown() { tabLayout1.setVisibility(View.GONE); viewPager1.setVisibility(View.GONE); frame1.setVisibility(View.VISIBLE); //setItemsVisibility(menu, search, false); //Do some magic } @Override public void onSearchViewClosed() { tabLayout1.setVisibility(View.VISIBLE); viewPager1.setVisibility(View.VISIBLE); //layoutmain.setVisibility(View.VISIBLE); frame1.setVisibility(View.GONE); //setItemsVisibility(menu, searchview, true); //Do some magic } }); } return true; } private List<SongModel> filter(List<SongModel> models, String query) { query = query.toLowerCase(); final List<SongModel> filteredModelList = new ArrayList<>(); for (SongModel model : models) { final String text = model.getTitle().toLowerCase(); if (text.contains(query)) { filteredModelList.add(model); } } return filteredModelList; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_CODE_SPEECH_INPUT: { if (resultCode == RESULT_OK && null != data) { ArrayList<String> result = data .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); Intent intent = new Intent(Intent.ACTION_SEARCH); intent.setPackage("com.google.android.youtube"); intent.putExtra("query", result.get(0).toString()); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } break; } } } private void getPlaylistItems(String s) { sList = new ArrayList<>(); helper = new DatabaseHelper(this); // Select All Query String selectQuery = "SELECT * FROM " + PlayListStore.TABLE_NAME + " WHERE " + PlayListStore.PLAYLIST_ID + "='" + s + "'"; Log.e("QUERY_____", selectQuery); SQLiteDatabase db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor == null) Toast.makeText(this, cursor.getCount() + "Cursor values", Toast.LENGTH_SHORT).show(); // looping through all rows and adding to list else { if (cursor.moveToFirst()) { do { byte[] blob = cursor.getBlob(5); ByteArrayInputStream inputStream = new ByteArrayInputStream(blob); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); sList.add(new SongModel(cursor.getString(1), cursor.getString(2), cursor.getString(3), Uri.parse(cursor.getString(4)), bitmap)); } while (cursor.moveToNext()); } // close db connection sList.size(); } } public void getPlaylist(ArrayList<SongModel> sList, int location) { this.sList = sList; this.position = location; player.setPlaylist(sList, position); songPlay(); slidingUpPanelLayout.setPanelState(PanelState.EXPANDED); } public void previousSong() { if (player != null && sList.size() > 0) { player.getPreviousSong(); //setSongView(); setSongPlayView(); } } public void nextSong() { if (player != null && sList.size() > 0) { player.sList=this.sList; player.getNextSong(); //setSongView(); setSongPlayView(); } } public void playpause() { if (player.mp != null) { if (player.mp.isPlaying()) { player.getPause(); // Changing button image to play button play.setBackgroundResource(R.drawable.ic_play); smallbtnplay.setBackgroundResource(R.drawable.ic_play); } else { // Resume song if (player.mp != null) { player.getPlay(); // Changing button image to pause button play.setBackgroundResource(R.drawable.ic_pause); smallbtnplay.setBackgroundResource(R.drawable.ic_pause); } } } } public void stopSong() { if (player.mp != null) { player.stopSong(); play.setBackgroundResource(R.drawable.ic_play); smallbtnplay.setBackgroundResource(R.drawable.ic_play); } } @Override protected void onDestroy() { super.onDestroy(); } private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { // We've bound to LocalService, cast the IBinder and get LocalService instance MusicService.LocalBinder binder = (MusicService.LocalBinder) service; player = binder.getService(); updateProgressBar(); setSongPlayView(); if(player.getPlaylistData().size()>0 && player.getPlaylistData()!=null) { getPlaylistData(); mainframe.setVisibility(View.GONE); slidingUpPanelLayout.setVisibility(View.VISIBLE); setSupportActionBar(toolbar1); layoutselectsong1.setVisibility(View.GONE); } else { setSupportActionBar(toolbar); mainframe.setVisibility(View.VISIBLE); slidingUpPanelLayout.setVisibility(View.GONE); } serviceBound = true; //setSongPlayView(); if (requestCode != 0) { setSongPlayView(); slidingUpPanelLayout.setPanelState(PanelState.EXPANDED); } if (playlistname != null) { if (category != null) { getCategorydata(category, playlistname); getPlaylist(sList, position); } else { getPlaylistItems(playlistname); getPlaylist(sList, position); } } } @Override public void onServiceDisconnected(ComponentName name) { serviceBound = false; Toast.makeText(MainActivity.this,"Servcie instance disconnected",Toast.LENGTH_SHORT).show(); } }; private void getPlaylistData() { this.sList=player.getPlaylistData(); this.position=player.getPosition(); } private void getCategorydata(String category, String name) { sList = new ArrayList<>(); Getmusic helper = new Getmusic(this); // Select All Query String selectQuery = "SELECT * FROM " + SongList.TABLE_NAME + " WHERE " + category + "='" + name + "'"; Log.e("QUERY_____", selectQuery); SQLiteDatabase db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor == null) Toast.makeText(this, cursor.getCount() + "Cursor values", Toast.LENGTH_SHORT).show(); // looping through all rows and adding to list else { if (cursor.moveToFirst()) { do { byte[] blob = cursor.getBlob(4); ByteArrayInputStream inputStream = new ByteArrayInputStream(blob); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); sList.add(new SongModel(cursor.getString(1), s, cursor.getString(2), Uri.parse(cursor.getString(3)), bitmap)); } while (cursor.moveToNext()); } // close db connection sList.size(); } } private void setSongPlayView() { if(player.sList!=null && (player.sList.size()>0)) { stitle.setText(player.sList.get(player.position()).getTitle()); sartist.setText(player.sList.get(player.position()).getArtist()); simage.setImageBitmap(player.sList.get(player.position()).getImage()); setdataToView(player.sList.get(player.position()).getTitle(),player.sList.get(player.position()).getImage()); } } private void songPlay() { try { // set Progress bar values if(player!=null) { slidingUpPanelLayout.setVisibility(View.VISIBLE); setSupportActionBar(toolbar1); layoutselectsong1.setVisibility(View.GONE); mainframe.setVisibility(View.GONE); updater.setProgress(0); waveLoadingView.setProgressValue(0); updater.setMax(100); player.getStart(position); setSongPlayView(); updateProgressBar(); slidingUpPanelLayout.setPanelState(PanelState.EXPANDED); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } } public void updateProgressBar() { if(hand!=null) hand.postDelayed(mUpdateTimeTask, 100); } /** * Background Runnable thread * */ private Runnable mUpdateTimeTask = new Runnable() { public void run() { if(hand!=null) { // Displaying Total Duration time endtime.setText("" + utils.milliSecondsToTimer(player.mp.getDuration())); // Displaying time completed playing starttime.setText("" + utils.milliSecondsToTimer(player.mp.getCurrentPosition())); // Updating progress bar int progress = (int) (utils.getProgressPercentage(player.mp.getCurrentPosition(), player.mp.getDuration())); //Log.d("Progress", ""+progress); updater.setProgress(progress); waveLoadingView.setProgressValue(progress); hand.postDelayed(this, 100); } } }; /** * * */ @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { if(fromTouch){ updater.setProgress(progress); waveLoadingView.setProgressValue(progress); updateProgressBar(); } } /** * When user starts moving the progress handler * */ @Override public void onStartTrackingTouch(SeekBar seekBar) { // remove message Handler from updating progress bar if(hand!=null) hand.removeCallbacks(mUpdateTimeTask); } /** * When user stops moving the progress hanlder * */ @Override public void onStopTrackingTouch(SeekBar seekBar) { if(hand!=null) { hand.removeCallbacks(mUpdateTimeTask); int currentPosition = utils.progressToTimer(seekBar.getProgress(), player.mp.getDuration()); // forward or backward to certain seconds player.mp.seekTo(currentPosition); // update timer progress again updateProgressBar(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { item.expandActionView(); switch (item.getItemId()) { case R.id.addplaylist: showDailog(); break; case R.id.voice: if (Utils.isInternetAvaliable(this)) { promptSpeechInput(); } else { Utils.showNetworkAlertDialog(this); } break; case R.id.search: songType.requestFocus(); songType.setFocusableInTouchMode(true); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(songType, InputMethodManager.SHOW_FORCED); break; } return abdt.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } public void open(ArrayList<SongModel> smodel, int position) { if (player != null) { this.position = position; this.sList = smodel; player.resetSong(); player.setPlaylist(smodel, position); songPlay(); setSongPlayView(); } } private void promptSpeechInput() { Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.speech_prompt)); try { startActivityForResult(intent, REQ_CODE_SPEECH_INPUT); } catch (ActivityNotFoundException a) { Toast.makeText(getApplicationContext(), getString(R.string.speech_not_supported), Toast.LENGTH_SHORT).show(); } } public void showDailog() { Bundle bundle = new Bundle(); bundle.putInt("songuri", -1); manger = getFragmentManager(); mydailog = new MyDialog(); mydailog.show(manger, "MyDialog"); mydailog.setArguments(bundle); } public void showDailog(int songposition) { Bundle bundle = new Bundle(); bundle.putInt("songuri", songposition); manger = getFragmentManager(); mydailog = new MyDialog(); mydailog.show(manger, "MyDialog"); mydailog.setArguments(bundle); } private void setupViewPager(ViewPager viewPager) { viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); viewPagerAdapter.addFrag(new Songs(), "SONGS"); viewPagerAdapter.addFrag(new Genres(), "GENRES"); viewPagerAdapter.addFrag(new Album(), "ALBUM"); viewPagerAdapter.addFrag(new Artist(), "ARTIST"); viewPagerAdapter.addFrag(new Playlist(), "PLAYLIST"); viewPager.setAdapter(viewPagerAdapter); } public void toolbarchange(int i) { enableActionMode(i); } private void enableActionMode(int position) { if (actionMode == null) { actionMode = startSupportActionMode(actionModeCallback); mActionModeIsActive = true; } toggleSelection(position); } private void toggleSelection(int position) { if (position == 0) { actionMode.finish(); } else { actionMode.setTitle(String.valueOf(position)); actionMode.invalidate(); } } @Override public void onBackPressed() { super.onBackPressed(); } public void setSelectedSong(String s, String s1, Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); Intent in1 = new Intent(this, PlalistItem.class); in1.putExtra("songname", s); in1.putExtra("songcount", s1); in1.putExtra("image", byteArray); startActivity(in1); } public void openSong(SongModel smodel) { if(slidingUpPanelLayout.getVisibility()==View.GONE) searchview.closeSearch(); else searchview1.closeSearch(); for(int i=0;i<sList.size();i++){ if((sList.get(i)==smodel)){ this.position=i; player.setPlaylist(sList,position); songPlay(); break; } } } public void dismisspopup() { selectplaylist.dismiss(); } public void mydialogdismisspopup() { mydailog.dismiss(); } public void changelayout(String playlistname) { if (actionMode == null) { if(slidingUpPanelLayout.getVisibility()==View.GONE){ this.playlistname = playlistname; layoutselectsong.setVisibility(View.VISIBLE); actionMode = startSupportActionMode(actionModeCallback); mActionModeIsActive = true; selectedSong = new ArrayList<>(); selectsongrecycle.setHasFixedSize(true); selectsongrecycle.setLayoutManager(new LinearLayoutManager(this)); songadapter = new SelectSongAdapter(this, totalsongList); selectsongrecycle.setAdapter(songadapter); } else{ this.playlistname = playlistname; layoutselectsong1.setVisibility(View.VISIBLE); actionMode = startSupportActionMode(actionModeCallback); mActionModeIsActive = true; selectedSong = new ArrayList<>(); selectsongrecycle1.setHasFixedSize(true); selectsongrecycle1.setLayoutManager(new LinearLayoutManager(this)); songadapter = new SelectSongAdapter(this, totalsongList); selectsongrecycle1.setAdapter(songadapter); } } } public static Context getActivityContext() { return instance; } public void setdataToView(String title, Bitmap image) { contentText.setText(title); contentviewImage.setImageBitmap(image); } public void updateui(int progress) { updater.setProgress(progress); waveLoadingView.setProgressValue(progress); } private class ActionModeCallback implements ActionMode.Callback { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { mode.getMenuInflater().inflate(R.menu.selectmode, menu); // disable swipe refresh if action mode is enabled return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { if(slidingUpPanelLayout.getVisibility()==View.GONE) toolbar.setVisibility(View.GONE); else toolbar1.setVisibility(View.GONE); return false; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.okbtn: if (playlistname != null && selectedSong.size() > 0) insertSong(playlistname); if(slidingUpPanelLayout.getVisibility()==View.GONE) layoutselectsong.setVisibility(View.GONE); else layoutselectsong1.setVisibility(View.GONE); if (mode != null) mode.finish(); return true; case R.id.canbtn: if(slidingUpPanelLayout.getVisibility()==View.GONE) layoutselectsong.setVisibility(View.GONE); else layoutselectsong1.setVisibility(View.GONE); if (mode != null) mode.finish(); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; if(slidingUpPanelLayout.getVisibility()==View.GONE){ toolbar.setVisibility(View.VISIBLE); layoutselectsong.setVisibility(View.GONE);} else{ toolbar1.setVisibility(View.VISIBLE); layoutselectsong1.setVisibility(View.GONE); } } } public void insertSong(String note) { // get writable database as we want to write data DatabaseHelper help = new DatabaseHelper(this); SQLiteDatabase db = help.getWritableDatabase(); int countsongs = 0; for (int i = 0; i < selectedSong.size(); i++) { ContentValues values = new ContentValues(); // `id` and `timestamp` will be inserted automatically. // no need to add them values.put(PlayListStore.PLAYLIST_ID, note); values.put(PlayListStore.SONG_NAME, selectedSong.get(i).getTitle()); values.put(PlayListStore.SONG_ARTIST, selectedSong.get(i).getArtist()); values.put(PlayListStore.SONG_LOCATION, selectedSong.get(i).getLocation()); values.put(PlayListStore.SONG_URI, String.valueOf(selectedSong.get(i).getUri())); values.put(PlayListStore.SONG_IMAGE, getBitmapAsByteArray(selectedSong.get(i).getImage())); // insert row db.insert(PlayListStore.TABLE_NAME, null, values); countsongs++; } // close db connection db.close(); Toast.makeText(this, "Playlist created", Toast.LENGTH_SHORT).show(); } private byte[] getBitmapAsByteArray(Bitmap image) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.PNG, 0, outputStream); return outputStream.toByteArray(); } private class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragmentList = new ArrayList<>(); private final List<String> mFragmentTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager manager) { super(manager); } @Override public Fragment getItem(int position) { return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } public void addFrag(Fragment fragment, String title) { mFragmentList.add(fragment); mFragmentTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitleList.get(position); } } @Override public void setContentView(int layoutResID) { super.setContentView(R.layout.dummy); } private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } @Override protected void onStop() { super.onStop(); } @Override protected void onStart() { intent = new Intent(this, MusicService.class); startService(intent); bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); super.onStart(); } public void setCheck(boolean state, SongModel model) { if (state) { count++; this.toolbarchange(count); selectedSong.add(model); } else { --count; this.toolbarchange(count); selectedSong.remove(model); } } }
package com.zxt.compplatform.codegenerate.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; public class CodegenerateUtil { public static org.jdom.Element transformElement(org.dom4j.Element element) { String xml = element.asXML(); org.jdom.Element ele = new org.jdom.Element(xml); return ele; } public static String transformTableName(String tableName) { StringBuffer sb = new StringBuffer(); boolean nextIsUpper = false; if(tableName != null && tableName.length() > 0){ sb.append(tableName.substring(0,1).toUpperCase()); for(int i = 1; i< tableName.length();i++){ String s = tableName.substring(i, i+1); if(s.equals("_")){ nextIsUpper = true; continue; } if(nextIsUpper){ sb.append(s.toUpperCase()); nextIsUpper = false; }else{ sb.append(s.toLowerCase()); } } } return sb.toString(); } public static String transformColumnName(String columnName) { StringBuffer sb = new StringBuffer(); boolean nextIsUpper = false; if(columnName != null && columnName.length() > 0){ sb.append(columnName.substring(0,1).toLowerCase()); for(int i = 1; i< columnName.length();i++){ String s = columnName.substring(i, i+1); if(s.equals("_")){ nextIsUpper = true; continue; } if(nextIsUpper){ sb.append(s.toUpperCase()); nextIsUpper = false; }else{ sb.append(s.toLowerCase()); } } } return sb.toString(); } public static Map getDataSourcesAndObjects(Document doc) { Map map = new HashMap(); try{ // Format format = Format.getPrettyFormat(); // format.setEncoding("UTF-8"); // XMLOutputter xmlout = new XMLOutputter(); // ByteArrayOutputStream bo = new ByteArrayOutputStream(); // xmlout.output(doc, bo); }catch(Exception e){ e.printStackTrace(); } return map; } public static List copyBySerialize(List list){ List dest = null; try{ ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(list); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteIn); dest = (List)in.readObject(); }catch(Exception e){ e.printStackTrace(); } return dest; } }
package com.pdd.pop.sdk.http.api.request; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.api.response.PddAdCreativeCreateResponse; import com.pdd.pop.sdk.http.HttpMethod; import com.pdd.pop.sdk.http.PopBaseHttpRequest; import com.pdd.pop.sdk.common.util.JsonUtil; import java.util.Map; import java.util.TreeMap; public class PddAdCreativeCreateRequest extends PopBaseHttpRequest<PddAdCreativeCreateResponse>{ /** * 单元id */ @JsonProperty("unit_id") private Long unitId; /** * 0:搜索广告 */ @JsonProperty("scene_type") private Integer sceneType; /** * jsonObject 的json string。示例:{"title":"ceshi","image_url":"https://img12.360buyimg.com/n7/g14/M07/16/00/rBEhVlJfpdwIAAAAAADurQhBHX0AAETNABbGNkAAO7F355.jpg"} */ @JsonProperty("creative") private Creative creative; @Override public String getVersion() { return "V1"; } @Override public String getDataType() { return "JSON"; } @Override public String getType() { return "pdd.ad.creative.create"; } @Override public HttpMethod getHttpMethod() { return HttpMethod.POST; } @Override public Class<PddAdCreativeCreateResponse> getResponseClass() { return PddAdCreativeCreateResponse.class; } @Override public Map<String, String> getParamsMap() { Map<String, String> paramsMap = new TreeMap<String, String>(); paramsMap.put("version", getVersion()); paramsMap.put("data_type", getDataType()); paramsMap.put("type", getType()); paramsMap.put("timestamp", getTimestamp().toString()); if(unitId != null) { paramsMap.put("unit_id", unitId.toString()); } if(sceneType != null) { paramsMap.put("scene_type", sceneType.toString()); } if(creative != null) { paramsMap.put("creative", creative.toString()); } return paramsMap; } public void setUnitId(Long unitId) { this.unitId = unitId; } public void setSceneType(Integer sceneType) { this.sceneType = sceneType; } public void setCreative(Creative creative) { this.creative = creative; } public static class Creative { /** * */ @JsonProperty("title") private String title; /** * 图片地址 */ @JsonProperty("image_url") private String imageUrl; public void setTitle(String title) { this.title = title; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } @Override public String toString() { return JsonUtil.transferToJson(this); } } }
package com.bottomup.demo; import java.math.BigInteger; import java.net.MalformedURLException; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; import com.mi9dev.customerorders.GetOrdersRequest; import com.mi9dev.customerorders.GetOrdersResponse; import com.mi9dev.customerorders.Order; import com.mi9dev.customerorders.Product; public class PaymentProcessorWSClientTest { public static void main(String[] args) throws MalformedURLException, DatatypeConfigurationException { GregorianCalendar gregorianCalendar = new GregorianCalendar(); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar); CCInfo creditCardInfo = new CCInfo(); creditCardInfo.setCardNumber("123"); creditCardInfo.setFirstName("Tim"); creditCardInfo.setLastName("Tom"); creditCardInfo.setExpirtyDate(date2); creditCardInfo.setSecCode("1234"); creditCardInfo.setAddress("Tim Tom"); PaymentRequest paymentRequest = new PaymentRequest(); paymentRequest.setAmount(123); paymentRequest.setCreditCardInfo(creditCardInfo); PaymentProcessorWSClient paymentProcessorWSClient = new PaymentProcessorWSClient(); PaymentResponse processPaymentByDetails = paymentProcessorWSClient.processPaymentByDetails(paymentRequest); boolean result = processPaymentByDetails.isResult(); System.out.println(result); } }
package com.eomcs; class Example { public static void main(String[] args) { System.out.frintln("이그젬플 0"); } } class Example2 { public static void main2(String[] args) { System.out.frintln("이그젬플 2"); } } class Example3 { public static void main3(String[] args) { System.out.frintln("이그젬플 3"); } }
public class Ch12_08 { }
package util; import javax.servlet.http.HttpSession; /** * @author Andriy Yednarovych */ public class HttpSessionUtil { public boolean requestConnection(HttpSession session) { boolean ok = false; String user = (String) session.getAttribute("user"); if (user != null) { ok = true; } return ok; } }
package com.springboot.system.notificaition; public interface MessageService { Message createMessage(Message ms); }
package me.ewriter.chapter4.pizzaaf; /** 原料类供工厂使用 */ public class MozzarellaCheese implements Cheese { public String toString() { return "Shredded Mozzarella"; } }
package com.goldenasia.lottery.data; import com.goldenasia.lottery.base.net.RequestConfig; import com.google.gson.annotations.SerializedName; import java.util.List; /** * 追号撤单 * Created by Alashi on 2016/2/8. */ @RequestConfig(api = "?c=game&a=cancelTrace") public class CancelTraceCommand { @SerializedName("wrap_id") private String wrapId; private List<String> pkids; public void setWrapId(String wrapId) { this.wrapId = wrapId; } public void setPkids(List<String> pkids) { this.pkids = pkids; } }
package prevoznaSredstva; public class Avion extends Vozilo { // avion je vozilo koje sadrzi putnike // i koje ima jedinstveni serijski broj String, marku STRING, // kao i klasu putnika koju // koje prevozi STRING private String serijskiBroj; private String markaAviona; private String klasaPutnika; public Avion(int brMesta, String serijskiBroj, String markaAviona) { super(brMesta); this.serijskiBroj = serijskiBroj; this.markaAviona = markaAviona; } public String getSerijskiBroj() { return serijskiBroj; } public void setSerijskiBroj(String serijskiBroj) { this.serijskiBroj = serijskiBroj; } public String getMarkaAviona() { return markaAviona; } public void setMarkaAviona(String markaAviona) { this.markaAviona = markaAviona; } public String getKlasaPutnika() { return klasaPutnika; } public void setKlasaPutnika(String klasaPutnika) { this.klasaPutnika = klasaPutnika; } @Override public boolean postaviPutnika(Putnik p, int i) { if (i >= getBrojMestaZaPrevoz().length || i < 0) { System.out.println("Nesto nije u redu, nema tog mesta u vozilu"); return false; } if (getBrojMestaZaPrevoz()[i] != null) { System.out.println("Nesto nije u redu, izgleda da je mesto zauzeto"); return false; } for (int j = 0; j < getBrojMestaZaPrevoz().length; j++) { if (getBrojMestaZaPrevoz()[j] != null) { if (getBrojMestaZaPrevoz()[j] == p) { System.out.println("Nesto nije u redu, probajte ponovo da postavite putnika"); return false; } } } getBrojMestaZaPrevoz()[i] = p; setBrojPutnika(getBrojPutnika() + 1); if (i >= 1 && i < 25) { this.setKlasaPutnika("I klasa"); } else if (i > 26 && i < 75) { this.setKlasaPutnika("business klasa"); } else { this.setKlasaPutnika("economic klasa"); } System.out.println("Putnik " + p.getImeIPrezime() + " je postavljen na mesto " + i); return true; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Avion(" + getId() + ":" + this.getSerijskiBroj() + ":<" + getGorivo() + ">:"); sb.append(getBrojPutnika() + "{"); for (int i = 0; i < getBrojMestaZaPrevoz().length; i++) { if (getBrojMestaZaPrevoz()[i] != null) sb.append(getBrojMestaZaPrevoz()[i] + ","); } sb.append("}"); return sb.toString(); } }
package com.example.main.repository; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.stereotype.Repository; import com.example.main.utils.Constants; @Repository public class SimpleJdbcCallExample { @Autowired private Environment env; public String callStoredProcedure(String inParam) { SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(this.dataSource()) .withCatalogName(Constants.PACKAGE_NAME) // If SP is inside a Package, then Package name must be given here. .withProcedureName(Constants.INOUT_SP_WITHOUT_PKG_NAME); SqlParameterSource inParameters = new MapSqlParameterSource() .addValue("inParam1", inParam); Map<String, Object> storedProcedureResult = simpleJdbcCall.execute(inParameters); String result = (String) storedProcedureResult.get("OUTPARAM1"); // Out Parameter works only when given in Upper Case. return result; } // @Bean // @Bean can be used to inject this DataSource bean in some other place. // In this case, dataSource() method is called in this class itself. So, @Bean is not mandatory. public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setUrl(env.getProperty("spring.datasource.url")); dataSource.setUsername(env.getProperty("spring.datasource.username")); dataSource.setPassword(env.getProperty("spring.datasource.password")); dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name")); return dataSource; } }
package br.com.fiap.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name="T_Patrocinio") @SequenceGenerator(name="seqPatrocinio", sequenceName = "SQ_Patrocinio", allocationSize=1 ) public class Patrocinio { @Id @GeneratedValue (strategy = GenerationType.SEQUENCE, generator = "seqPatrocinio") @Column (name="CD_PATROCINIO") private int codigo; @Column (name="VL_PATROCINIO") private double valor; @Column (name="NM_EMPRESA") private String nome; public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } }
package com.corejava.basic; import java.io.File; public class ListOutFilesWithSpecificExtensionOfADirectory { public static void main(String[] args) { String filePath="/home/rahul/Pictures/upload"; File folder=new File(filePath); File files[]=folder.listFiles(); for(File file:files) { if(file.getName().endsWith(".xml")) { System.out.println("Files ends with .xml are::"+file.getName()); } } } }
package entities; import engine.Values; public class Fruit extends Entity { private int points; public enum FruitType { NORMAL_BANANA, SPECIAL_BANANA, PINEAPPLE, STRAWBERRY, GRAPES, WATERMELON } private FruitType fruitType; public Fruit(float x, float y, EntityType entityType, ScrollableType scrollableType) { super(x, y, entityType, scrollableType); // Some customizations body.x += 3 * Values.Scalar_Width; body.y += 3 * Values.Scalar_Height; body.width -= 6 * Values.Scalar_Width; body.height -= 6 * Values.Scalar_Height; } public int getPoints() { return points; } public void setFruitType(FruitType type) { this.fruitType = type; switch (fruitType) { case SPECIAL_BANANA: setWidth(Values.Banana_Width_Special); setHeight(Values.Banana_Height_Special); points = 15; break; case NORMAL_BANANA: setWidth(Values.Banana_Width_Normal); setHeight(Values.Banana_Height_Normal); points = 5; break; case GRAPES: setWidth(Values.Grapes_Width); setHeight(Values.Grapes_Height); points = 7; break; case WATERMELON: setWidth(Values.Watermelon_Width); setHeight(Values.Watermelon_Height); points = 9; break; case STRAWBERRY: setWidth(Values.Strawberry_Width); setHeight(Values.Strawberry_Height); points = 5; break; case PINEAPPLE: setWidth(Values.Pineapple_Width); setHeight(Values.Pineapple_Height); points = 10; break; default: break; } } public FruitType getFruitType() { return fruitType; } }
/* * © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied * verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. */ package cern.molr.mole.impl; import cern.molr.TestDefinitions; import cern.molr.commons.exception.MissionExecutionException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Class that tests the behaviour of {@link JunitMole} * * @author tiagomr */ public class JunitMoleTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private final JunitMole junitMole = new JunitMole(); @Test public void testDiscoverJunitMission() throws NoSuchMethodException { List<String> actualMethodsNames = junitMole.discover(TestDefinitions.JunitMission.class) .stream() .map(method -> method.getName()) .collect(Collectors.toList()); List<String> expectedMethodNames = new ArrayList<>(); expectedMethodNames.add("mission1"); expectedMethodNames.add("mission2"); assertTrue(expectedMethodNames.stream().allMatch(actualMethodsNames::contains)); } @Test public void testDiscoverNonRunnableMission() { List<Method> actualMethods = junitMole.discover(TestDefinitions.EmptyMission.class); assertTrue(actualMethods.isEmpty()); } @Test public void testDiscoverJunitMissionWithNullClassType() { expectedException.expect(IllegalArgumentException.class); junitMole.discover(null); } @Test public void testRunJunitMission() { junitMole.run(TestDefinitions.JunitMission.class.getName()); } @Test public void testRunWithNonJunitMission() { junitMole.run(TestDefinitions.EmptyMission.class.getName()); } @Test public void testRunWithNullMissionContentClassType() { expectedException.expect(MissionExecutionException.class); expectedException.expectCause(isA(IllegalArgumentException.class)); junitMole.run(null); } @Test public void testRunWithNonExistentMissionContentClassType() { expectedException.expect(MissionExecutionException.class); expectedException.expectCause(isA(ClassNotFoundException.class)); junitMole.run("NonExistent"); } }
package com.example.gamedb.db.repository; import android.app.Application; import android.os.AsyncTask; import com.example.gamedb.db.GameDatabase; import com.example.gamedb.db.dao.ScreenshotDao; import com.example.gamedb.db.entity.Screenshot; public class ScreenshotRepository { private ScreenshotDao mScreenshotDao; public ScreenshotRepository(Application application) { GameDatabase database = GameDatabase.getDatabase(application); mScreenshotDao = database.screenshotDao(); } public void insert(Screenshot... screenshots) { new InsertAsyncTask(mScreenshotDao).execute(screenshots); } public void update(Screenshot... screenshots) { new UpdateAsyncTask(mScreenshotDao).execute(screenshots); } public void deleteAll(Long date) { new DeleteAsyncTask(mScreenshotDao).execute(date); } private static class InsertAsyncTask extends AsyncTask<Screenshot, Void, Void> { private ScreenshotDao mDao; public InsertAsyncTask(ScreenshotDao screenshotDao) { mDao = screenshotDao; } @Override protected Void doInBackground(Screenshot... screenshots) { mDao.insert(screenshots); return null; } } private static class UpdateAsyncTask extends AsyncTask<Screenshot, Void, Void> { private ScreenshotDao mDao; public UpdateAsyncTask(ScreenshotDao screenshotDao) { mDao = screenshotDao; } @Override protected Void doInBackground(Screenshot... screenshots) { mDao.update(screenshots); return null; } } private static class DeleteAsyncTask extends AsyncTask<Long, Void, Void> { private ScreenshotDao mDao; public DeleteAsyncTask(ScreenshotDao screenshotDao) { mDao = screenshotDao; } @Override protected Void doInBackground(Long... dates) { mDao.deleteAll(dates[0]); return null; } } }
package walke.base.tool; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.ImageFormat; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.YuvImage; import android.hardware.Camera; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; /** * 图像处理 */ public class ImageHelper { /** * 根据图片需要旋转的角度进行图片旋转 * @param yuv420sp 图片数据 * @param width * @param height * @param angle 需要旋转的角度 只支持 90度 180度 270度 * @return */ public static byte[] rotateYUV420sp(byte[] yuv420sp, int width, int height, int angle) { switch (angle) { case 0: return yuv420sp; case 90: return rotate90YUV420SP(yuv420sp, width, height); case 180: return rotate180YUV420SP(yuv420sp, width, height); case 270: return rotate270YUV420SP(yuv420sp, width, height); } return yuv420sp; } /** * 顺时针旋转270. * * @param yuv420sp * @param width * @param height * @return */ public static byte[] rotate270YUV420SP(byte[] yuv420sp, int width, int height) { byte[] des = new byte[yuv420sp.length]; int wh = width * height; // 旋转Y // b[w-j-1,i] = a[i,j] // => b[i,j] = a[j,w - i - 1] // j*w+w-i-1 int k = 0; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { des[k] = yuv420sp[width * j + width - i - 1]; k++; } } // b[w-j-1,i] = a[i,j] // => b[i,j] = a[j,w - i - 1] for (int i = 0; i < width; i += 2) { for (int j = 0; j < height / 2; j++) { des[k] = yuv420sp[wh + width * j + width - i - 2]; des[k + 1] = yuv420sp[wh + width * j + width - i - 1]; k += 2; } } return des; } /** * 顺时针旋转90. * * @param yuv420sp * @param width * @param height * @return */ public static byte[] rotate90YUV420SP(byte[] yuv420sp, int width, int height) { byte[] des = new byte[yuv420sp.length]; int wh = width * height; // 旋转Y // => b[i,j] = a[h - j - 1, i] // j*w+i int k = 0; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { des[k] = yuv420sp[width * (height - j - 1) + i]; k++; } } // b[w-j-1,i] = a[i,j] // => b[i,j] = a[j,i] // for (int i = 0; i < width; i += 2) { for (int j = 0; j < height / 2; j++) { des[k] = yuv420sp[wh + width * (height / 2 - j - 1) + i]; des[k + 1] = yuv420sp[wh + width * (height / 2 - j - 1) + i + 1]; k += 2; } } return des; } /** * 顺时针旋转180. * * @param yuv420sp * @param width * @param height * @return */ public static byte[] rotate180YUV420SP(byte[] yuv420sp, int width, int height) { // 旋转Y int length = width * height; for (int i = 0; i < length / 2 - 1; i++) { byte temp = yuv420sp[i]; yuv420sp[i] = yuv420sp[length - 1 - i]; yuv420sp[length - 1 - i] = temp; } int startIndex = width * height; int count = width * height / 4; // 旋转uv for (int i = 0; i < count / 2 - 1; ++i) { byte temp = yuv420sp[i * 2 + startIndex]; yuv420sp[i * 2 + startIndex] = yuv420sp[(count - i - 1) * 2 + startIndex]; yuv420sp[(count - i - 1) * 2 + startIndex] = temp; temp = yuv420sp[i * 2 + 1 + startIndex]; yuv420sp[i * 2 + 1 + startIndex] = yuv420sp[(count - i - 1) * 2 + 1 + startIndex]; yuv420sp[(count - i - 1) * 2 + 1 + startIndex] = temp; } return yuv420sp; } public static void cropYUV420SP(byte[] yuv420sp, byte[] croppedYUV420sp, Rect rectangle, Rect originalRect) { if (!originalRect.contains(rectangle)) { throw new IllegalArgumentException( "rectangle is not inside the image"); } int width = rectangle.width(); int height = rectangle.height(); // Make sure left, top, width and height are all even. width &= ~1; height &= ~1; rectangle.left &= ~1; rectangle.top &= ~1; rectangle.right = rectangle.left + width; rectangle.bottom = rectangle.top + height; width = rectangle.width(); height = rectangle.height(); int top = rectangle.top; // int bottom = rectangle.bottom; int left = rectangle.left; // int right = rectangle.right; croppedYUV420sp = new byte[width * height * 3 / 2]; // Crop Y for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { croppedYUV420sp[i * width + j] = yuv420sp[(top + i) * width + (left + j)]; } } // Crop UV int widthCountOfUV = originalRect.width() / 2; int LeftOffsetCountOfUV = left / 2; int originalOffSet = originalRect.width() * originalRect.height(); int croppedOffSet = width*height; int k = 0; for (int i = 0; i <= height; i += 2) { for (int j = 0; j < width; j+= 2) { int orignalIndex = (top + i)*widthCountOfUV + LeftOffsetCountOfUV*2 + j + originalOffSet; croppedYUV420sp[croppedOffSet + k] = yuv420sp[orignalIndex]; croppedYUV420sp[croppedOffSet + k + 1] = yuv420sp[orignalIndex + 1]; k += 2; } } } public static Boolean saveImage(byte[] data, Camera camera, int[] faceRects, String bigPicture/*, String smallPicture*/) { int left = 0; int bottom = 0; int top = 0; left = faceRects[0]; top = faceRects[1]; bottom = faceRects[1] + faceRects[3]; Log.i("huakuang", "left =" + left + "" + " top = " + top + "" + " button=" + bottom + ""); YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, camera.getParameters().getPreviewSize().width, camera.getParameters().getPreviewSize().height, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); yuvimage.compressToJpeg(new Rect(0, 0, camera.getParameters().getPreviewSize().width, camera.getParameters().getPreviewSize().height), 100, baos); // Log.i("waaa", // "width="+camera.getParameters().getPreviewSize().width+""+"hig="+camera.getParameters().getPreviewSize().height+"");//width=320,hig=240 byte[] dataBy = baos.toByteArray(); Matrix matrix = new Matrix(); // 翻转图片,原图片长宽交换。 matrix.postRotate(270); matrix.postScale(-1, 1); // 镜像水平翻转 Bitmap bitmap = BitmapFactory.decodeByteArray(dataBy, 0, dataBy.length); Bitmap nbmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // 原数12 10 File bigFile = new File(bigPicture); FileOutputStream bigOut = null; try { bigOut = new FileOutputStream(bigFile); nbmp.compress(Bitmap.CompressFormat.JPEG, 50, bigOut); bigOut.close(); } catch (Exception e) { e.printStackTrace(); return false; } // try { // File smallFile = new File(smallPicture); // FileOutputStream smallOut = new FileOutputStream(smallFile); // Bitmap biduiBitmap = resizeBitmap(nbmp, 150, 150); // biduiBitmap.compress(Bitmap.CompressFormat.PNG, 80, smallOut); // Log.i("biduiBitmap.getHeight", "" + biduiBitmap.getHeight()); // Log.i("biduiBitmap.getWidth()", "" + biduiBitmap.getWidth()); // // picNewRes.compress(Bitmap.CompressFormat.PNG, 100, newOut); // smallOut.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } return true; } public Boolean saveImage(byte[] data, Camera camera, String imagePath) { YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, camera.getParameters().getPreviewSize().width, camera.getParameters().getPreviewSize().height, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); yuvimage.compressToJpeg(new Rect(0, 0, camera.getParameters().getPreviewSize().width, camera.getParameters().getPreviewSize().height), 80, baos); byte[] dataBy = baos.toByteArray(); Matrix matrix = new Matrix(); // 翻转图片,原图片长宽交换。 matrix.postRotate(270); matrix.postScale(-1, 1); // 镜像水平翻转 Bitmap bitmap = BitmapFactory.decodeByteArray(dataBy, 0, dataBy.length); Bitmap nbmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); // 原数12 10 File bigFile = new File(imagePath); FileOutputStream bigOut = null; try { bigOut = new FileOutputStream(bigFile); nbmp.compress(Bitmap.CompressFormat.PNG, 80, bigOut); bigOut.close(); } catch (Exception e) { e.printStackTrace(); } return false; } public static Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) { int originWidth = bitmap.getWidth(); int originHeight = bitmap.getHeight(); // no need to resize if (originWidth < maxWidth && originHeight < maxHeight) { return bitmap; } int width = originWidth; int height = originHeight; // 若图片过宽, 则保持长宽比缩放图片 if (originWidth > maxWidth) { width = maxWidth; double i = originWidth * 1.0 / maxWidth; height = (int) Math.floor(originHeight / i); bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false); } // 若图片过长, 则从上端截取 if (height > maxHeight) { height = maxHeight; bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height); } // Log.i(TAG, width + " width"); // Log.i(TAG, height + " height"); return bitmap; } public static Bitmap bytes2Bimap(byte[] b) { if (b != null && b.length != 0) { return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } } }
package com.esum.router.logger.document; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.framework.core.event.log.DocumentLog; import com.esum.framework.core.event.log.LoggingEvent; import com.esum.framework.core.event.message.EventHeader; import com.esum.router.logger.history.MessageHistoryTable; public abstract class DocumentLogTable { protected Logger log = LoggerFactory.getLogger(DocumentLogTable.class); protected File datafile; protected LoggingEvent logEvent = null; protected String controlID, traceID = null; protected Connection connection = null; protected int messageType = EventHeader.TYPE_MESSAGE; /** * 생성한 DocumentLogTable 객체를 LoggingEvent로 초기화한다. */ public DocumentLogTable(String traceId, int messageType, LoggingEvent logEvent, Connection connection) { this.messageType = messageType; this.logEvent = logEvent; this.controlID = logEvent.getMessageCtrlId(); this.traceID = traceId; this.connection = connection; } /** * DocumentLog 테이블에 Document 정보들을 Insert한다. */ public void insert(DocumentLog document) throws SQLException, IOException { String errSeqNo = this.insertDocumentLog(document); String errorCode = document.getErrorInfo()==null?null:document.getErrorInfo().getErrorCode(); new MessageHistoryTable(traceID, logEvent, datafile, this.connection).updateHistory(errSeqNo, errorCode); } /** * DocumentLog 테이블에 Document 정보들을 Insert한다. */ public void insert(DocumentLog document, File datafile) throws SQLException, IOException { this.datafile = datafile; String errSeqNo = this.insertDocumentLog(document); String errorCode = document.getErrorInfo()==null?null:document.getErrorInfo().getErrorCode(); new MessageHistoryTable(traceID, logEvent, datafile, this.connection).updateHistory(errSeqNo, errorCode); } /** * DocumentLog 테이블에 Insert. */ protected abstract String insertDocumentLog(DocumentLog docLog) throws SQLException, IOException; /** * DocumentLog 테이블에 Document 정보들을 Update한다. */ public void update(DocumentLog document) throws SQLException, IOException { String errSeqNo = this.updateDocumentLog(document); String errorCode = document.getErrorInfo()==null?null:document.getErrorInfo().getErrorCode(); if(messageType!=EventHeader.TYPE_ACKNOWLEDGE) new MessageHistoryTable(traceID, logEvent, datafile, this.connection).updateHistory(errSeqNo, errorCode); } /** * DocumentLog 테이블에 Document 정보들을 Update한다. */ public void update(DocumentLog document, File datafile) throws SQLException, IOException { this.datafile = datafile; String errSeqNo = this.updateDocumentLog(document); String errorCode = document.getErrorInfo()==null?null:document.getErrorInfo().getErrorCode(); if(messageType!=EventHeader.TYPE_ACKNOWLEDGE) new MessageHistoryTable(traceID, logEvent, datafile, this.connection).updateHistory(errSeqNo, errorCode); } /** * DocumentLog 테이블에 Update. * * @param document * @return String */ protected abstract String updateDocumentLog(DocumentLog docLog) throws SQLException, IOException; }
package com.itheima.day_01.animals; public class Cat extends Animals { public Cat() { } public Cat(String breed, String color) { super(breed, color); } @Override void eat() { System.out.println("eating fish"); } @Override void bark() { System.out.println("meow"); } }
package com.example.administrator.panda_channel_app.MVP_Framework.base; /** * Created by Administrator on 2017/7/12 0012. */ public interface BaseView<T> { void setPresenter(T t); }
package com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.gravity; import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter.AbstractLayouter; import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter.Item; import java.util.List; class EmptyRowStrategy implements IRowStrategy { @Override public void applyStrategy(AbstractLayouter abstractLayouter, List<Item> row) { //do nothing } }
package de.cuuky.varo.gui.admin.troll; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import de.cuuky.varo.gui.SuperInventory; import de.cuuky.varo.gui.utils.PageAction; import de.cuuky.varo.item.ItemBuilder; import de.cuuky.varo.troll.TrollModule; public class TrollGUI extends SuperInventory { public TrollGUI(Player opener) { super("§5Troll", opener, 9, false); open(); } @Override public boolean onOpen() { int i = 1; for(TrollModule mod : TrollModule.getModules()) { linkItemTo(i, new ItemBuilder().displayname(mod.getName()).itemstack(new ItemStack(mod.getIcon())).lore(new String[] { "§7Enabled for: {2DO}", "", "§7" + mod.getDescription() }).build(), new Runnable() { @Override public void run() { } }); i += 2; } return false; } @Override public void onClick(InventoryClickEvent event) {} @Override public void onInventoryAction(PageAction action) {} @Override public boolean onBackClick() { return false; } @Override public void onClose(InventoryCloseEvent event) {} }
package com.zyx.test; import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zhou.redis.User; import com.zyx.service.ListTaskQueueService; import com.zyx.service.UserService; public class redisTemplateTest { ClassPathXmlApplicationContext applicationContext; UserService userService; ListTaskQueueService listTaskQueueService; @Before public void before() { applicationContext = new ClassPathXmlApplicationContext("applicationcontext-redis.xml"); userService = applicationContext.getBean(UserService.class);// 获取Bean listTaskQueueService = applicationContext.getBean(ListTaskQueueService.class);// 获取Bean } /** * String 类型测试 */ @Test public void StrTest() { String key = "applicationName1"; String result = userService.getStr(key); System.out.println(result); } /** * hash类型测试 */ @Test public void HashTest() { User user = new User(); user.setId(1); user.setName("username"); user.setAge(22); userService.addUser(user); } /** * hash类型测试 */ @Test public void selectUserFromRedis() { User user = userService.selectUserById(4); System.out.println(user); } /** * list 类型测试 */ @SuppressWarnings("rawtypes") @Test public void ListAddTest() { listTaskQueueService.listAdd(); List list = (List) listTaskQueueService.ListRange(); for (Object object : list) { System.out.println(object); } } /** * list 分页测试 */ @SuppressWarnings("rawtypes") @Test public void ListRangeTest() { List list = (List) listTaskQueueService.ListRange(1, 3); for (Object object : list) { System.out.println(object); } } /** * 任务队列测试: */ @SuppressWarnings("rawtypes") @Test public void listTaskQueueTest() { String orderId = "0001"; System.out.println("-------初始化任务队列-------"); listTaskQueueService.creatListQueueInit(orderId);// 初始化队列任务 System.out.println("-------当前待执行的任务队列-------"); List listWait = listTaskQueueService.listQueueWait(orderId); for (Object object : listWait) { System.out.println(object); } System.out.println("-------触发任务:完成某项队列任务-------"); listTaskQueueService.listQueueEventTouch(orderId); System.out.println("-------执行某项触发任务之后的等待队列-------"); List newListWait = listTaskQueueService.listQueueWait(orderId);// for (Object object : newListWait) { System.out.println(object); } System.out.println("-------已完成的任务队列-------"); List listSuc = listTaskQueueService.listQueueSuc(orderId); for (Object object : listSuc) { System.out.println(object); } } }
package com.haut.searchofthetestinfo.controller; import com.haut.searchofthetestinfo.po.InfoTest; import com.haut.searchofthetestinfo.tools.ParseExcel; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.ClassUtils; import org.springframework.util.ResourceUtils; 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.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List; @Controller @RequestMapping("/uploadAndDownload") public class UploadAndDownloadFileController { @RequestMapping("/index") public String index() { return "uploadAndDownload.html"; } @RequestMapping(value = "/uploadFileAction", method = RequestMethod.POST) public String uploadFileAction(@RequestParam("uploadFile") MultipartFile uploadFile, @RequestParam("id") Long id, ModelMap modelMap) { InputStream fis = null; OutputStream outputStream = null; try { fis = uploadFile.getInputStream(); String path = "E:\\"+uploadFile.getOriginalFilename(); // outputStream = new FileOutputStream(ClassUtils.getDefaultClassLoader().getResource("UploadAndDownloadFileController.class").getPath()+uploadFile.getOriginalFilename()); outputStream = new FileOutputStream(path); IOUtils.copy(fis,outputStream); ParseExcel parseExcel = new ParseExcel(); List<InfoTest> list = parseExcel.getExcelData(path); parseExcel.addToDatabaseAll(list); modelMap.addAttribute("success","上传成功"); System.out.println("执行测试"); return "success.html"; } catch (IOException e) { e.printStackTrace(); }finally { if(fis != null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if(outputStream != null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } modelMap.addAttribute("sucess", "上传失败!"); return "success.html"; } @RequestMapping("downloadFileAction") public void downloadFileAction(HttpServletRequest request, HttpServletResponse response) { response.setCharacterEncoding(request.getCharacterEncoding()); response.setContentType("application/octet-stream"); FileInputStream fis = null; try { File file = new File("G:\\config.ini"); fis = new FileInputStream(file); response.setHeader("Content-Disposition", "attachment; filename="+file.getName()); IOUtils.copy(fis,response.getOutputStream()); response.flushBuffer(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
class A1Q15 { public static void main(String [] args) { int a=2,b=7,temp; System.out.println("Before swapping" ); System.out.println("a = "+a+" b= "+b); temp=a; a=b; b=temp; System.out.println("After swapping"); System.out.println("a = "+a+" b= "+b); } }
package se.rtz.csvtool.command.server; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.gson.JsonObject; import se.rtz.tool.util.csv.RecordConverter; import se.rtz.tool.util.csv.impl.CsvRecord; public enum SupportedMimeTypes { TEXT("text/text", "", (header, record) -> record.toCsvString(',') + "\n", "", ""), CSV("text/csv", "", (header, record) -> record.toCsvString(',') + "\n", "", ""), HTML("text/html", "<html><body><table>", (header, record) -> { StringBuilder r = new StringBuilder("<tr>"); record.forEach(rec -> r.append("<td>").append(rec).append("</td>")); r.append("</tr>"); return r.toString(); }, "", "</table></body></html>"), JSON("application/json", "[", new RecordConverter<String>() { @Override public String convert(CsvRecord header, CsvRecord record) { if (Objects.equal(header, record)) { return ""; } String[] headerArray = header.toArray(); String[] recordArray = record.toArray(); JsonObject element = new JsonObject(); for (int i = 0; i < headerArray.length; i++) { String aHeader = headerArray[i]; String aValue = ""; if (i < recordArray.length) aValue = recordArray[i]; element.addProperty(aHeader, aValue); } return element.toString(); } }, ",", "]"); public static final SupportedMimeTypes DEFAULT_TYPE = TEXT; private final String mimeType; private final RecordConverter<String> function; private final String beforeElements; private final String afterElements; private final String betweenElements; private SupportedMimeTypes(String mimeType, String beforeElements, RecordConverter<String> function, String betweenElements, String afterElements) { this.mimeType = mimeType; this.function = function; this.beforeElements = beforeElements; this.afterElements = afterElements; this.betweenElements = betweenElements; } public String getMimeType() { return mimeType; } public static SupportedMimeTypes findSupportedMimeType(String mimeTypes) { SupportedMimeTypes result = DEFAULT_TYPE; if (Strings.isNullOrEmpty(mimeTypes)) { return result; } for (SupportedMimeTypes candidate: values()) { if (mimeTypes.contains(candidate.getMimeType())) result = candidate; } return result; } public RecordConverter<String> getConverter() { return function; } public String getBeforeElement() { return this.beforeElements; } public String getAfterElements() { return this.afterElements; } public String getBetweenElements() { return betweenElements; } }
/** * Copyright 2018 RDP http://product.mftcc.cn/rdp/ * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 io.report.modules.sys.service.impl; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import io.report.common.utils.PageUtils; import io.report.common.utils.Query; import io.report.modules.ser.entity.DbTypeEntity; import io.report.modules.sys.dao.SysWayDao; import io.report.modules.sys.entity.SysWayEntity; import io.report.modules.sys.service.SysWayService; @Service("sysWayService") public class SysWayServiceImpl extends ServiceImpl<SysWayDao, SysWayEntity> implements SysWayService { @Override public List<SysWayEntity> getList(SysWayEntity sysWayEntity){ List<SysWayEntity> list = this.selectList(new EntityWrapper<SysWayEntity>()); return list; } }
package com.cloudinte.common.utils; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.thinkgem.jeesite.common.utils.excel.ImportExcel; import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField; import com.thinkgem.jeesite.modules.sys.utils.DictUtils; public class ImportObjectExcel extends ImportExcel { private static Logger log = LoggerFactory .getLogger(ImportObjectExcel.class); public ImportObjectExcel(File file, int headerNum) throws InvalidFormatException, IOException { super(file, headerNum); // TODO Auto-generated constructor stub } public ImportObjectExcel(MultipartFile file, int headerNum, int sheetIndex) throws InvalidFormatException, IOException { super(file, headerNum,sheetIndex); } public List<Object[]> getDataObjList(Class<?> cls, int... groups) throws InstantiationException, IllegalAccessException { List<Object[]> annotationList = Lists.newArrayList(); // Get annotation field Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { ExcelField ef = f.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == 2)) { if (groups != null && groups.length > 0) { boolean inGroup = false; for (int g : groups) { if (inGroup) { break; } for (int efg : ef.groups()) { if (g == efg) { inGroup = true; annotationList.add(new Object[] { ef, f }); break; } } } } else { annotationList.add(new Object[] { ef, f }); } } } // Get annotation method Method[] ms = cls.getDeclaredMethods(); for (Method m : ms) { ExcelField ef = m.getAnnotation(ExcelField.class); if (ef != null && (ef.type() == 0 || ef.type() == 2)) { if (groups != null && groups.length > 0) { boolean inGroup = false; for (int g : groups) { if (inGroup) { break; } for (int efg : ef.groups()) { if (g == efg) { inGroup = true; annotationList.add(new Object[] { ef, m }); break; } } } } else { annotationList.add(new Object[] { ef, m }); } } } // Field sorting Collections.sort(annotationList, new Comparator<Object[]>() { @Override public int compare(Object[] o1, Object[] o2) { return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort())); }; }); //log.debug("Import column count:"+annotationList.size()); // Get excel data List<Object[]> dataList = Lists.newArrayList(); Object[] objarrObjects=null; for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) { int column = 0; Row row = this.getRow(i); StringBuilder sb = new StringBuilder(); objarrObjects=new Object[annotationList.size()]; for (Object[] os : annotationList) { Object val = this.getCellValue(row, column); if (val != null) { ExcelField ef = (ExcelField) os[0]; // If is dict type, get dict value if (StringUtils.isNotBlank(ef.dictType())) { val = DictUtils.getDictValue(val.toString(), ef.dictType(), ""); //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val); } // Get param type and type cast Class<?> valType = Class.class; if (os[1] instanceof Field) { valType = ((Field) os[1]).getType(); } else if (os[1] instanceof Method) { Method method = ((Method) os[1]); if ("get".equals(method.getName().substring(0, 3))) { valType = method.getReturnType(); } else if ("set".equals(method.getName().substring(0, 3))) { valType = ((Method) os[1]).getParameterTypes()[0]; } } log.debug("Import value type: [" + i + "," + column + "] " + valType); try { if (valType == String.class) { String s = String.valueOf(val.toString()); if (StringUtils.endsWith(s, ".0")) { val = StringUtils.substringBefore(s, ".0"); } else { val = String.valueOf(val.toString()); } } else if (valType == Integer.class) { val = Double.valueOf(val.toString()).intValue(); } else if (valType == Long.class) { val = Double.valueOf(val.toString()).longValue(); } else if (valType == Double.class) { val = Double.valueOf(val.toString()); } else if (valType == Float.class) { val = Float.valueOf(val.toString()); } else if (valType == Date.class) { val = DateUtil.getJavaDate((Double) val); } else { val = String.valueOf(val.toString()); } } catch (Exception ex) { log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString()); val = null; } objarrObjects[column++]=val; } sb.append(val + ", "); } dataList.add(objarrObjects); log.debug("Read success: [" + i + "] " + sb.toString()); } return dataList; } }
package com.example.demo.service.impl; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.example.demo.entity.InvoiceRecord; import com.example.demo.entity.InvoiceRecordParams; import com.example.demo.entity.InvoiceRecordVO; import com.example.demo.entity.PageInfo; import com.example.demo.mapper.InvoiceRecordMapper; import com.example.demo.service.IInvoiceRecordService; import com.example.demo.untils.ExcelUtils; import lombok.extern.slf4j.Slf4j; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.Map; import static com.example.demo.untils.ExcelUtils.addCellContent; import static com.example.demo.untils.ExcelUtils.addExcelHeader; import static com.example.demo.untils.ExcelUtils.excelOutput; /** * <p> * 服务实现类 * </p> * * @author zjp * @since 2020-11-30 */ @Service @Slf4j public class InvoiceRecordServiceImpl extends ServiceImpl<InvoiceRecordMapper, InvoiceRecord> implements IInvoiceRecordService { private final InvoiceRecordMapper mapper; @Autowired public InvoiceRecordServiceImpl(InvoiceRecordMapper mapper) { this.mapper = mapper; } /** * 获取历史数据 * * @param params 参数 * @return list */ @Override public PageInfo<InvoiceRecordVO> getHistory(InvoiceRecordParams params) { Page<InvoiceRecordVO> page = new Page<>(params.getPageNumber(), params.getPageSize()); Page<InvoiceRecordVO> list = mapper.selectHistoryList(page, params); return new PageInfo<>(list.getTotal(), list.getCurrent(), list.getPages(), list.getRecords()); } /** * 导出 * * @param response / * @param params / */ @Override public void exportHistory(HttpServletResponse response, InvoiceRecordParams params) { String[] excelHeader = { "系统编号", "部门", "项目组", "发起人ID", "市场部门合作支付", "合作合同ID", "合同编号", "合同名称", "合同总金额", "已支付金额", "可付金额", "收入合同ID", "合同编号", "合同名称", "合同总金额", "到款金额", "应付合作费用", "支付方式", "支付类型", "支付类别", "申请支付金额", "银行账户名", "银行账户", "开户银行", "开户支行", "申请理由", "备注", "创建时间" }; String[] excelHeaderKey = { "id", "dept_name", "sub_dept_name", "user_id", "cooperative_payment", "contract_id", "num", "name", "sum_money", "amount_paid", "payable_amount", "income_id", "income_num", "income_name", "income_sum_money", "income_paid", "income_payable_expenses", "type", "category", "sub_category", "amount", "customer_name", "bank_account", "bank_name", "bank_branch_name", "apply_reason", "note", "create_time" }; List<Map<String, Object>> list = mapper.listByParams(params); excelNoMerge(response, excelHeader, excelHeaderKey, list); } private void excelNoMerge(HttpServletResponse response, String[] excelHeader, String[] excelHeaderKey, List<Map<String, Object>> list) { List<String> column10Width = Arrays.asList("系统编号", "市场部门合作支付", "合作合同ID", "收入合同ID", "支付方式", "支付类型", "支付类别"); List<String> column60Width = Arrays.asList("申请理由", "合同名称"); List<String> column30Width = Arrays.asList("银行账户名", "银行账户", "开户银行", "开户支行"); // 设置cell type 为 number 类型的列名 List<String> cellTypeNumber = Arrays.asList("系统编号", "合作合同ID", "合同总金额", "已支付金额", "可付金额", "收入合同ID", "到款金额", "应付合作费用", "申请支付金额"); try (SXSSFWorkbook workbook = new SXSSFWorkbook(list.size() + 1)) { SXSSFSheet sheet = workbook.createSheet("支付申请"); // excel header addExcelHeader(workbook, sheet, excelHeader, column10Width, column30Width, column60Width); // content style CellStyle contentCellStyle = ExcelUtils.contentStyle(workbook); // cell content addCellContent(sheet, list, excelHeader, excelHeaderKey, cellTypeNumber, null, contentCellStyle); // excel output excelOutput(response, workbook, "支付申请记录" + LocalDate.now() + ".xlsx"); } catch (IOException e) { log.error("ExcelUtils - exportExcel {} [error]: ", LocalDateTime.now(), e); } } }
package communicator.messages.search; import communicator.messages.Message; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by lasitha on 3/5/15. */ public class AckSearch extends Message{ /* length SEROK no_files IP port hops filename1 filename2 ... ... e.g., Suppose we are searching for string baby. So it will return, 0114 SEROK 3 129.82.128.1 2301 baby_go_home.mp3 baby_come_back.mp3 baby.mpeg length – Length of the entire message including 4 characters used to indicate the length. In xxxx format. SEROK – Sends the result for search. The node that sends this message is the one that actually stored the (key, value) pair, i.e., node that index the file information. no_files – Number of results returned ≥ 1 – Successful 0 – no matching results. Searched key is not in key table 9999 – failure due to node unreachable 9998 – some other error. IP – IP address of the node having (stored) the file. port – Port number of the node having (stored) the file. hops – Hops required to find the file(s). filename – Actual name of the file. */ private int noOfFiles; private String ip; private String port; private int hops; private String[] fileNames; public AckSearch(int noOfFiles, String ip, String port, int hops, String[] fileNames) { this.noOfFiles = noOfFiles; this.ip = ip; this.port = port; this.hops = hops; this.fileNames = fileNames; } public AckSearch(int noOfFiles, String ip, String port, int hops) { this.noOfFiles = noOfFiles; this.ip = ip; this.port = port; this.hops = hops; } public AckSearch(String message){ this.decodeMessage(message); } public void setNoOfFiles(int noOfFiles) { this.noOfFiles = noOfFiles; } public void setIp(String ip) { this.ip = ip; } public void setPort(String port) { this.port = port; } public void setHops(int hops) { this.hops = hops; } public void setFileNames(String[] fileNames) { this.fileNames = fileNames; } public int getNoOfFiles() { return noOfFiles; } public String getIp() { return ip; } public String getPort() { return port; } public String[] getFileNames() { return fileNames; } public int getHops() { return hops; } @Override public String toString() { /*length SEROK no_files IP port hops filename1 filename2 ... ...*/ String msg=" SEROK "+noOfFiles+" "+ip+" "+port+" "+hops; if(fileNames!=null) { for (String filename : fileNames) { msg = msg + " \"" + filename+"\""; } } msg=String.format("%04d",msg.length()+4)+msg; return msg; } @Override public void decodeMessage(String message) { String[] s=splitMessage(message); this.noOfFiles=Integer.parseInt(s[2]); this.ip=s[3]; this.port=s[4]; this.hops=Integer.parseInt(s[5]); message=trimLength(message); Pattern pattern = Pattern.compile("\"(.*?)\""); Matcher matcher = pattern.matcher(message); int i=0; if(noOfFiles!=0) { fileNames = new String[noOfFiles]; while (matcher.find()) { fileNames[i] = matcher.group(1); i++; } } } // public static void main(String[] args) { // String s="0046 SEROK 1 10.8.98.13 5300 0 \"Modern Family\"0\" 0in\""; // AckSearch a=new AckSearch(s); // System.out.println(a.toString()); // } }
package loecraftpack.common.blocks.render; import loecraftpack.common.blocks.BlockColoredBed; import loecraftpack.common.blocks.TileColoredBed; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.Direction; import net.minecraft.util.Icon; import net.minecraft.world.IBlockAccess; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderColoredBed implements ISimpleBlockRenderingHandler { public int renderID; public Icon getBlockIcon(BlockColoredBed block ,int side, int meta, int id, int pairSide) { if(side == 0) { return Block.planks.getBlockTextureFromSide(side); } else { int k = meta & 3;//get direction int l = Direction.bedDirection[k][side]; int i1 = ( (meta & 8) != 0 ) ? 1 : 0; //isBlockHeadOfBed if (pairSide == 0)//normal { return (i1 != 1 || l != 2) && (i1 != 0 || l != 3) ? (l != 5 && l != 4 ? block.bedtop.get(id)[i1] : block.bedside.get(id)[i1]) : block.bedend.get(id)[i1]; } else if (pairSide == 1)//right pair { return (i1 != 1 || l != 2) && (i1 != 0 || l != 3) ? (l != 5 && l != 4 ? block.bedPairTopRight.get(id)[i1] : block.bedPairSideRight.get(id)[i1]) : block.bedPairEndRight.get(id)[i1]; } else//left pair { return (i1 != 1 || l != 2) && (i1 != 0 || l != 3) ? (l != 5 && l != 4 ? block.bedPairTopLeft.get(id)[i1] : block.bedPairSideLeft.get(id)[i1]) : block.bedPairEndLeft.get(id)[i1]; } } } @Override public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { TileEntity colorTile = world.getBlockTileEntity(x, y, z); int id = 0;//set by tile entity int pairSide = 0; if(colorTile != null && colorTile instanceof TileColoredBed) { if( ((TileColoredBed)colorTile).pairID == -1 ) id = ((TileColoredBed)colorTile).id; else { pairSide = ((TileColoredBed)colorTile).pairSide; id = ((TileColoredBed)colorTile).pairID; } } int metadata = world.getBlockMetadata(x, y, z); //altered Vanilla bed code// Tessellator tessellator = Tessellator.instance; int i1 = block.getBedDirection(world, x, y, z); boolean flag = block.isBedFoot(world, x, y, z); float f = 0.5F; float f1 = 1.0F; float f2 = 0.8F; float f3 = 0.6F; int j1 = block.getMixedBrightnessForBlock(world, x, y, z); tessellator.setBrightness(j1); tessellator.setColorOpaque_F(f, f, f); Icon icon = this.getBlockIcon((BlockColoredBed)block, 0, metadata, id, pairSide); double d0 = (double)icon.getMinU(); double d1 = (double)icon.getMaxU(); double d2 = (double)icon.getMinV(); double d3 = (double)icon.getMaxV(); double d4 = (double)x + renderer.renderMinX; double d5 = (double)x + renderer.renderMaxX; double d6 = (double)y + renderer.renderMinY + 0.1875D; double d7 = (double)z + renderer.renderMinZ; double d8 = (double)z + renderer.renderMaxZ; tessellator.addVertexWithUV(d4, d6, d8, d0, d3); tessellator.addVertexWithUV(d4, d6, d7, d0, d2); tessellator.addVertexWithUV(d5, d6, d7, d1, d2); tessellator.addVertexWithUV(d5, d6, d8, d1, d3); tessellator.setBrightness(block.getMixedBrightnessForBlock(world, x, y + 1, z)); tessellator.setColorOpaque_F(f1, f1, f1); icon = this.getBlockIcon((BlockColoredBed)block, 1, metadata, id, pairSide); d0 = (double)icon.getMinU(); d1 = (double)icon.getMaxU(); d2 = (double)icon.getMinV(); d3 = (double)icon.getMaxV(); d4 = d0; d5 = d1; d6 = d2; d7 = d2; d8 = d0; double d9 = d1; double d10 = d3; double d11 = d3; if (i1 == 0) { d5 = d0; d6 = d3; d8 = d1; d11 = d2; } else if (i1 == 2) { d4 = d1; d7 = d3; d9 = d0; d10 = d2; } else if (i1 == 3) { d4 = d1; d7 = d3; d9 = d0; d10 = d2; d5 = d0; d6 = d3; d8 = d1; d11 = d2; } double d12 = (double)x + renderer.renderMinX; double d13 = (double)x + renderer.renderMaxX; double d14 = (double)y + renderer.renderMaxY; double d15 = (double)z + renderer.renderMinZ; double d16 = (double)z + renderer.renderMaxZ; tessellator.addVertexWithUV(d13, d14, d16, d8, d10); tessellator.addVertexWithUV(d13, d14, d15, d4, d6); tessellator.addVertexWithUV(d12, d14, d15, d5, d7); tessellator.addVertexWithUV(d12, d14, d16, d9, d11); int k1 = Direction.directionToFacing[i1]; if (flag) { k1 = Direction.directionToFacing[Direction.rotateOpposite[i1]]; } byte b0 = 4; switch (i1) { case 0: b0 = 5; break; case 1: b0 = 3; case 2: default: break; case 3: b0 = 2; } if (k1 != 2 && (renderer.renderAllFaces || block.shouldSideBeRendered(world, x, y, z - 1, 2))) { tessellator.setBrightness(renderer.renderMinZ > 0.0D ? j1 : block.getMixedBrightnessForBlock(world, x, y, z - 1)); tessellator.setColorOpaque_F(f2, f2, f2); renderer.flipTexture = b0 == 2; renderer.renderFaceZNeg(block, (double)x, (double)y, (double)z, getBlockIcon((BlockColoredBed)block, 2, metadata, id, pairSide)); } if (k1 != 3 && (renderer.renderAllFaces || block.shouldSideBeRendered(world, x, y, z + 1, 3))) { tessellator.setBrightness(renderer.renderMaxZ < 1.0D ? j1 : block.getMixedBrightnessForBlock(world, x, y, z + 1)); tessellator.setColorOpaque_F(f2, f2, f2); renderer.flipTexture = b0 == 3; renderer.renderFaceZPos(block, (double)x, (double)y, (double)z, getBlockIcon((BlockColoredBed)block, 3, metadata, id, pairSide)); } if (k1 != 4 && (renderer.renderAllFaces || block.shouldSideBeRendered(world, x - 1, y, z, 4))) { tessellator.setBrightness(renderer.renderMinZ > 0.0D ? j1 : block.getMixedBrightnessForBlock(world, x - 1, y, z)); tessellator.setColorOpaque_F(f3, f3, f3); renderer.flipTexture = b0 == 4; renderer.renderFaceXNeg(block, (double)x, (double)y, (double)z, getBlockIcon((BlockColoredBed)block, 4, metadata, id, pairSide)); } if (k1 != 5 && (renderer.renderAllFaces || block.shouldSideBeRendered(world, x + 1, y, z, 5))) { tessellator.setBrightness(renderer.renderMaxZ < 1.0D ? j1 : block.getMixedBrightnessForBlock(world, x + 1, y, z)); tessellator.setColorOpaque_F(f3, f3, f3); renderer.flipTexture = b0 == 5; renderer.renderFaceXPos(block, (double)x, (double)y, (double)z, getBlockIcon((BlockColoredBed)block, 5, metadata, id, pairSide)); } renderer.flipTexture = false; return true; } @Override public boolean shouldRender3DInInventory() { return false; } @Override public int getRenderId() { return renderID; } }
package bank.accounts; import bank.customers.Customer; import bank.movements.Transfer; /** * * @author Castro */ public class InvestmentAccount extends Account implements Transfer { /** * the associated cost to maintain the account */ private double associatedCost; /** * constructor * * @param costumer the owner of the account */ public InvestmentAccount(Customer costumer) { super(costumer); this.associatedCost = 5; Account.generalAccountsList.add(this); } /** * transfers between two current accounts */ @Override public void transferBetween(double amount, int numRecAcct) { } }
package cn.springboot.controller; import cn.springboot.mapper.BookMapper; import cn.springboot.pojo.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @Controller public class BookController { private static final String UPLOADED_FOLDER = "/"; //目录 @Autowired BookMapper bookMapper; @RequestMapping("/listBook") public String listBook(Model model){ List<Book> books = bookMapper.findAll(); model.addAttribute("book",books); return "listBook"; } @RequestMapping("/toaddBook") public String toaddBook(){ return "addBook"; } @RequestMapping("/addBook") public String addBook(Book book){ int i = bookMapper.save(book); System.out.println(i); return "redirect:/listBook"; } @RequestMapping("/tesx") public String tesx(@RequestParam("id") int id){ System.out.println("id:" + id); return "redirect:/listBook"; } @RequestMapping("toupdatefile") public String toupdatefile(){ return "updatefile"; } @PostMapping("/singleFileUpload") // //new annotation since 4.3 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:uploadStatus"; } try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { e.printStackTrace(); } return "redirect:/uploadStatus"; } @GetMapping("/uploadStatus") public String uploadStatus() { return "uploadStatus"; } }
package com.example.lesson_5_fedin; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Activity5 extends AppCompatActivity { Data data; TextView textView; public static final String MESSAGE = "message"; public static final String SAVE_DATA = "saveData"; public static Intent createStartIntent(Context context){ return new Intent(context, Activity5.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_5); // if(data != null) { // TextView textView = findViewById(R.id.textView); // textView.setText(data.getValue()); // } goToActivity3(); SaveData(); } public void SaveData(){ Button button = findViewById(R.id.buttonSave); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editText = findViewById(R.id.editText); String message = editText.getText().toString(); TextView textView = findViewById(R.id.textView); textView.setText(message); data = new Data(message); } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if(data != null) outState.putParcelable(Activity5.SAVE_DATA, data); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); data = savedInstanceState.getParcelable(Activity5.SAVE_DATA); if(data != null) { TextView textView = findViewById(R.id.textView); textView.setText(data.getValue()); } } public void goToActivity3(){ Button buttonGoTo3 = findViewById(R.id.button_go_to_3); buttonGoTo3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EditText editText = findViewById(R.id.editText); String message = editText.getText().toString(); Intent intent = new Intent(); intent.putExtra(Activity5.MESSAGE, message); setResult(RESULT_OK, intent); finish(); } }); } }
package net.oneqas; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OneqasMain { public static void main(String[] args) { SpringApplication.run(OneqasMain.class); } }
package com.example.aluno.helloup.utils; import android.util.Log; import java.io.IOException; import java.util.Map; import okhttp3.FormBody; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; // Classe utilitária para fazer requisições HTTP com a lib OKHttp public class HttpHelpers { private static final String TAG = "http"; private static final boolean LOG_ON = true; private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); // GET public static final String get(String url) throws IOException { log("HttpHelper.get: " + url); Request request = new Request.Builder().url(url).get().build(); return getJson(request); } // POST com JSON public static final String post(String url, String json) throws IOException { log("HttpHelper.post: " + url + " > " + json); RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder().url(url).post(body).build(); return getJson(request); } // POST com parâmetros (form-urlencoded) public static final String postForm(String url, Map params) throws IOException { log("HttpHelper.postForm: " + url + " > " + params); FormBody.Builder builder = new FormBody.Builder(); for (Object o : params.entrySet()) { Map.Entry entry = (Map.Entry) o; String key = (String) entry.getKey(); String value = (String) entry.getValue(); builder.add(key, value); } FormBody body = builder.build(); Request request = new Request.Builder().url(url).post(body).build(); return getJson(request); } // DELETE public static final String delete(String url) throws IOException { log("HttpHelper.delete: " + url); Request request = new Request.Builder().url(url).delete().build(); return getJson(request); } // Lê a resposta do servidor no formato JSON private static String getJson(Request request) throws IOException { OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); ResponseBody responseBody = response.body(); if (responseBody != null) { String json = responseBody.string(); log(" << : " + json); return json; } else { throw new IOException("Erro ao fazer a requisição"); } } private static void log(String s) { if (LOG_ON) { Log.d(TAG, s); } } }
package web.id.azammukhtar.subico.Network; import android.content.Context; import android.net.ConnectivityManager; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import web.id.azammukhtar.subico.Utils.SessionManager; import static web.id.azammukhtar.subico.Utils.Constant.BASE_URL; public class ApiNetwork { private static HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); private static OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)) .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .build(); private static Gson gson = new GsonBuilder() .setLenient() .create(); private static Retrofit.Builder retrofitBuilder = new Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client); private static Retrofit retrofit = retrofitBuilder.build(); private static ApiInterface apiInterface = retrofit.create(ApiInterface.class); public static ApiInterface getApiInterface(){ return apiInterface; } public static boolean isNetworkConnected(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); return (cm != null ? cm.getActiveNetworkInfo() : null) != null && cm.getActiveNetworkInfo().isConnected(); } }
package org.rs.core.log; import java.io.Serializable; import java.lang.reflect.Method; import java.util.Date; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.rs.core.annotation.ApiInfo; import org.rs.core.beans.RsAccessLog; import org.rs.core.security.authentication.RsLoginUser; import org.rs.core.service.RsLogService; import org.rs.core.utils.SecurityUtils; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.WebAuthenticationDetails; import com.fasterxml.jackson.databind.ObjectMapper; @SuppressWarnings("serial") public class RsLogInterceptor implements MethodInterceptor, Serializable{ private ObjectMapper jsonMapper; private RsLogService logService; public RsLogInterceptor(RsLogService logService,ObjectMapper jsonMapper) { this.logService = logService; this.jsonMapper = jsonMapper; } @Override public Object invoke(MethodInvocation invocation) throws Throwable { String parameters = jsonMapper.writeValueAsString(invocation.getArguments()); long startTime = System.currentTimeMillis(); Object result = invocation.proceed(); //String className = invocation.getClass().getName(); Method method = invocation.getMethod(); String methodName = method.getDeclaringClass().getName() + "." + method.getName() + "()"; ApiInfo apiInfo = method.getAnnotation(ApiInfo.class); recordAccessLog(apiInfo.value(),methodName,parameters,System.currentTimeMillis() - startTime); return result; } private void recordAccessLog( String operation,String methodName, String parameters, long milliseconds ) { RsLoginUser userInfo = null; String ip = ""; Authentication authentication = SecurityUtils.getAuthentication(); if( authentication != null ) { Object principal = authentication.getPrincipal(); Object details = authentication.getDetails(); if( details instanceof WebAuthenticationDetails ) { ip = ((WebAuthenticationDetails)details).getRemoteAddress(); } if( principal instanceof RsLoginUser ) { userInfo = (RsLoginUser)principal; }else { return; } } RsAccessLog bean = new RsAccessLog(); bean.setMethodName(methodName); bean.setParameters(parameters); bean.setOperation(operation); bean.setIp(ip); bean.setMilliseconds((int)milliseconds); bean.setUserId(userInfo.getYhbh()); bean.setUserName(userInfo.getYhmc()); bean.setAccessDate(new Date()); bean.setDeptId(userInfo.getBmbh()); bean.setDeptName(userInfo.getBmmc()); bean.setDeptPath(userInfo.getBmlj()); logService.insertAccessLogBean(bean); } }
package com.gaby.facade.stu; import com.gaby.stu.model.student.query.Request; import com.gaby.stu.model.student.query.Response; public interface StudentFacade { Response query(Request request); }
package RSA; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.security.*; public class main { public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException { String s = "\"On the other hand, we denounce with ri" + "ghteous indignation and dislike men who are so beguiled and de" + "moralized by the charms of pleasure of the moment, so blinded by des" + "ire, that they cannot foresee the pain and trouble that are bound to ensue; an" + "d equal blame belongs to those who fail in their duty through weakness of w" + "ill, which is the same as saying through shrinking from toil and pain. These " + "cases are perfectly simple and easy to distinguish. In a free hour, when our pow" + "er of choice is untrammelled and when nothing prevents our being able to do what we" + " like best, every pleasure is to be welcomed and every pain avoided. But in certai" + "n circumstances and owing to the claims of duty or the obligations of business it " + "will frequently occur that pleasures have to be repudiated and annoyances accepted. " + "The wise man therefore always holds in these matters to this principle of selection:" + " he rejects pleasures to secure other" + " greater pleasures, or else he endures pains to avoid worse pains.\""; Cipher cipher = Cipher.getInstance("RSA"); KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); pairgen.initialize(4096); KeyPair keyPair = pairgen.generateKeyPair(); Key publicKey = keyPair.getPublic(); Key privateKey = keyPair.getPrivate(); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytes = cipher.doFinal(s.getBytes()); for (byte b : bytes) { System.out.print(b); } System.out.println("\n"); Cipher decriptCipher = Cipher.getInstance("RSA"); decriptCipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decripteBytes = decriptCipher.doFinal(bytes); for (byte b : decripteBytes) { System.out.print((char) b); } } }
public class ex_1_1_15 { public static void main(String args[]) { int N = 10000; //size of the a array int[] a = new int[N]; for (int i = 0; i < N; i++) a[i] = StdRandom.uniform(N); //execute the function: int M = N; int[] b = new int[M]; b = histogram(a, M); //Display the results: for (int i = 0; i < N; i++) StdOut.printf("%d ", a[i]); StdOut.println(); for (int i = 0; i < M; i++) StdOut.printf("%d ", b[i]); } public static int[] histogram(int[] a, int M) { int[] b = new int[M]; for (int i = 0; i < M; i++) b[a[i]]++; return b; } }
package com.sh.ori.feedmeplease.Recipes; /** * Created by omer on 18/05/2017. */ public class Ingredient { public String name; public Ingredient(String name){ this.name = name; } }
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.cloudera.director.client.d6_2.model; import java.util.Objects; import com.cloudera.director.client.d6_2.model.ErrorInfo; import com.cloudera.director.client.d6_2.model.WarningInfo; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * ValidationResult */ public class ValidationResult { @SerializedName("errors") private List<ErrorInfo> errors = null; @SerializedName("warnings") private List<WarningInfo> warnings = null; @SerializedName("formatWarnings") private List<WarningInfo> formatWarnings = null; public ValidationResult() { // Do nothing } private ValidationResult(ValidationResultBuilder builder) { this.errors = builder.errors; this.warnings = builder.warnings; this.formatWarnings = builder.formatWarnings; } public static ValidationResultBuilder builder() { return new ValidationResultBuilder(); } public static class ValidationResultBuilder { private List<ErrorInfo> errors = new ArrayList<ErrorInfo>(); private List<WarningInfo> warnings = new ArrayList<WarningInfo>(); private List<WarningInfo> formatWarnings = new ArrayList<WarningInfo>(); public ValidationResultBuilder errors(List<ErrorInfo> errors) { this.errors = errors; return this; } public ValidationResultBuilder warnings(List<WarningInfo> warnings) { this.warnings = warnings; return this; } public ValidationResultBuilder formatWarnings(List<WarningInfo> formatWarnings) { this.formatWarnings = formatWarnings; return this; } public ValidationResult build() { return new ValidationResult(this); } } public ValidationResultBuilder toBuilder() { return builder() .errors(errors) .warnings(warnings) .formatWarnings(formatWarnings) ; } public ValidationResult errors(List<ErrorInfo> errors) { this.errors = errors; return this; } public ValidationResult addErrorsItem(ErrorInfo errorsItem) { if (this.errors == null) { this.errors = new ArrayList<ErrorInfo>(); } this.errors.add(errorsItem); return this; } /** * Validation Errors * @return errors **/ @ApiModelProperty(value = "Validation Errors") public List<ErrorInfo> getErrors() { return errors; } public void setErrors(List<ErrorInfo> errors) { this.errors = errors; } public ValidationResult warnings(List<WarningInfo> warnings) { this.warnings = warnings; return this; } public ValidationResult addWarningsItem(WarningInfo warningsItem) { if (this.warnings == null) { this.warnings = new ArrayList<WarningInfo>(); } this.warnings.add(warningsItem); return this; } /** * Validation Warnings * @return warnings **/ @ApiModelProperty(value = "Validation Warnings") public List<WarningInfo> getWarnings() { return warnings; } public void setWarnings(List<WarningInfo> warnings) { this.warnings = warnings; } public ValidationResult formatWarnings(List<WarningInfo> formatWarnings) { this.formatWarnings = formatWarnings; return this; } public ValidationResult addFormatWarningsItem(WarningInfo formatWarningsItem) { if (this.formatWarnings == null) { this.formatWarnings = new ArrayList<WarningInfo>(); } this.formatWarnings.add(formatWarningsItem); return this; } /** * Format Warnings * @return formatWarnings **/ @ApiModelProperty(value = "Format Warnings") public List<WarningInfo> getFormatWarnings() { return formatWarnings; } public void setFormatWarnings(List<WarningInfo> formatWarnings) { this.formatWarnings = formatWarnings; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ValidationResult validationResult = (ValidationResult) o; return Objects.equals(this.errors, validationResult.errors) && Objects.equals(this.warnings, validationResult.warnings) && Objects.equals(this.formatWarnings, validationResult.formatWarnings); } @Override public int hashCode() { return Objects.hash(errors, warnings, formatWarnings); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ValidationResult {\n"); sb.append(" errors: ").append(toIndentedString(errors)).append("\n"); sb.append(" warnings: ").append(toIndentedString(warnings)).append("\n"); sb.append(" formatWarnings: ").append(toIndentedString(formatWarnings)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package com.sinodynamic.hkgta.dao.mms; import java.io.Serializable; import java.util.List; import com.sinodynamic.hkgta.dao.IBaseDao; import com.sinodynamic.hkgta.entity.mms.SpaRetreat; public interface SpaRetreatDao extends IBaseDao<SpaRetreat>{ public Serializable addSpaRetreat(SpaRetreat spaRetreat); public SpaRetreat getByRetId(Long retId); public List<SpaRetreat> getAllSpaRetreats(); public Long getMaxDisplayOrder(); }
import java.util.*; import java.io.*; public class prob03 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new File("prob03-1-in.txt")); int N = in.nextInt(); in.nextLine(); for (int idx = 0; idx < N; idx++) { String line = in.nextLine(); boolean like = false; for (int i = 0; i + 1 < line.length(); i++) { if (line.charAt(i) == line.charAt(i+1)) { like = true; break; } } if (like) System.out.println("likes " + line); else System.out.println("hates " + line); } in.close(); } }
package communicator.messages; /** * Created by lasitha on 3/5/15. */ public class Error extends Message { /* length ERROR 0010 ERROR length – Length of the entire message including 4 characters used to indicate the length. In xxxx format. ERROR – Generic error message, to indicate that a given command is not understood. For storing and searching files/keys this should be send to the initiator of the message. */ private String error; public Error(){ this.error=null; } public Error(String error) { this.error = error; } @Override public String toString() { String msg=" ERROR"; if(error!=null) { msg = msg + " " + error; } msg=String.format("%04d",msg.length()+4)+msg; return msg; } @Override public void decodeMessage(String message) { String[] s=splitMessage(message); if(s.length>2) { int index=message.indexOf(s[1]); this.error = message.substring(1+index+s[1].length()); } } }
/* ------------------------------------------------------------------------------ * 软件名称:BB语音 * 公司名称:乐多科技 * 开发作者:Yongchao.Yang * 开发时间:2016年3月3日/2016 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.ace.web.service * fileName:Order.java * ------------------------------------------------------------------------------- */ package com.rednovo.ace.entity; import java.math.BigDecimal; import com.rednovo.ace.constant.Constant; /** * @author yongchao.Yang/2016年3月3日 */ public class Order { /** * */ public Order() { // TODO Auto-generated constructor stub } private String orderId; private String thirdId; private String payerId; private String payerName; private String receiverId; private String receiveName; private String goodId; private String goodName; private int goodCnt; private String orderDes; private BigDecimal rmbAmount; private BigDecimal coinAmount; private Constant.payChannel payChannel; private BigDecimal payedAmount; private String rate; private String createTime; private String openTime; private String openUserId; private String openUserName; private String status; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getPayerId() { return payerId; } public void setPayerId(String payerId) { this.payerId = payerId; } public String getPayerName() { return payerName; } public void setPayerName(String payerName) { this.payerName = payerName; } public String getReceiverId() { return receiverId; } public void setReceiverId(String receiverId) { this.receiverId = receiverId; } public String getReceiveName() { return receiveName; } public void setReceiveName(String receiveName) { this.receiveName = receiveName; } public String getOrderDes() { return orderDes; } public void setOrderDes(String orderDes) { this.orderDes = orderDes; } public BigDecimal getRmbAmount() { return rmbAmount; } public void setRmbAmount(BigDecimal rmbAmount) { this.rmbAmount = rmbAmount; } public BigDecimal getCoinAmount() { return coinAmount; } public void setCoinAmount(BigDecimal coinAmount) { this.coinAmount = coinAmount; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getCreateTime() { return createTime; } public void setCreateTime(String orderTime) { this.createTime = orderTime; } public String getOpenTime() { return openTime; } public void setOpenTime(String openTime) { this.openTime = openTime; } public String getOpenUserId() { return openUserId; } public void setOpenUserId(String operatorId) { this.openUserId = operatorId; } public String getOpenUserName() { return openUserName; } public void setOpenUserName(String operatorName) { this.openUserName = operatorName; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getGoodId() { return goodId; } public void setGoodId(String goodId) { this.goodId = goodId; } public String getGoodName() { return goodName; } public void setGoodName(String goodName) { this.goodName = goodName; } public int getGoodCnt() { return goodCnt; } public void setGoodCnt(int goodCnt) { this.goodCnt = goodCnt; } public Constant.payChannel getPayChannel() { return payChannel; } public void setPayChannel(Constant.payChannel payChannel) { this.payChannel = payChannel; } public BigDecimal getPayedAmount() { return payedAmount; } public void setPayedAmount(BigDecimal payedAmount) { this.payedAmount = payedAmount; } public String getThirdId() { return thirdId; } public void setThirdId(String thirdId) { this.thirdId = thirdId; } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.http.server.reactive; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicLong; import javax.net.ssl.SSLSession; import io.undertow.connector.ByteBufferPool; import io.undertow.connector.PooledByteBuffer; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import org.xnio.channels.StreamSourceChannel; import reactor.core.publisher.Flux; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.http.HttpCookie; import org.springframework.http.HttpMethod; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Adapt {@link ServerHttpRequest} to the Undertow {@link HttpServerExchange}. * * @author Marek Hawrylczak * @author Rossen Stoyanchev * @author Juergen Hoeller * @since 5.0 */ class UndertowServerHttpRequest extends AbstractServerHttpRequest { private static final AtomicLong logPrefixIndex = new AtomicLong(); private final HttpServerExchange exchange; private final RequestBodyPublisher body; public UndertowServerHttpRequest(HttpServerExchange exchange, DataBufferFactory bufferFactory) throws URISyntaxException { super(HttpMethod.valueOf(exchange.getRequestMethod().toString()), initUri(exchange), "", new UndertowHeadersAdapter(exchange.getRequestHeaders())); this.exchange = exchange; this.body = new RequestBodyPublisher(exchange, bufferFactory); this.body.registerListeners(exchange); } private static URI initUri(HttpServerExchange exchange) throws URISyntaxException { Assert.notNull(exchange, "HttpServerExchange is required"); String requestURL = exchange.getRequestURL(); String query = exchange.getQueryString(); String requestUriAndQuery = (StringUtils.hasLength(query) ? requestURL + "?" + query : requestURL); return new URI(requestUriAndQuery); } @Override protected MultiValueMap<String, HttpCookie> initCookies() { MultiValueMap<String, HttpCookie> cookies = new LinkedMultiValueMap<>(); for (Cookie cookie : this.exchange.requestCookies()) { HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue()); cookies.add(cookie.getName(), httpCookie); } return cookies; } @Override @Nullable public InetSocketAddress getLocalAddress() { return this.exchange.getDestinationAddress(); } @Override @Nullable public InetSocketAddress getRemoteAddress() { return this.exchange.getSourceAddress(); } @Nullable @Override protected SslInfo initSslInfo() { SSLSession session = this.exchange.getConnection().getSslSession(); if (session != null) { return new DefaultSslInfo(session); } return null; } @Override public Flux<DataBuffer> getBody() { return Flux.from(this.body); } @SuppressWarnings("unchecked") @Override public <T> T getNativeRequest() { return (T) this.exchange; } @Override protected String initId() { return ObjectUtils.getIdentityHexString(this.exchange.getConnection()) + "-" + logPrefixIndex.incrementAndGet(); } private class RequestBodyPublisher extends AbstractListenerReadPublisher<DataBuffer> { private final StreamSourceChannel channel; private final DataBufferFactory bufferFactory; private final ByteBufferPool byteBufferPool; public RequestBodyPublisher(HttpServerExchange exchange, DataBufferFactory bufferFactory) { super(UndertowServerHttpRequest.this.getLogPrefix()); this.channel = exchange.getRequestChannel(); this.bufferFactory = bufferFactory; this.byteBufferPool = exchange.getConnection().getByteBufferPool(); } private void registerListeners(HttpServerExchange exchange) { exchange.addExchangeCompleteListener((ex, next) -> { onAllDataRead(); next.proceed(); }); this.channel.getReadSetter().set(c -> onDataAvailable()); this.channel.getCloseSetter().set(c -> onAllDataRead()); this.channel.resumeReads(); } @Override protected void checkOnDataAvailable() { this.channel.resumeReads(); // We are allowed to try, it will return null if data is not available onDataAvailable(); } @Override protected void readingPaused() { this.channel.suspendReads(); } @Override @Nullable protected DataBuffer read() throws IOException { PooledByteBuffer pooledByteBuffer = this.byteBufferPool.allocate(); try (pooledByteBuffer) { ByteBuffer byteBuffer = pooledByteBuffer.getBuffer(); int read = this.channel.read(byteBuffer); if (rsReadLogger.isTraceEnabled()) { rsReadLogger.trace(getLogPrefix() + "Read " + read + (read != -1 ? " bytes" : "")); } if (read > 0) { byteBuffer.flip(); DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(read); dataBuffer.write(byteBuffer); return dataBuffer; } else if (read == -1) { onAllDataRead(); } return null; } } @Override protected void discardData() { // Nothing to discard since we pass data buffers on immediately.. } } }
package com.chess.Pieces; import com.chess.*; import java.util.ArrayList; public class Pawn extends Piece{ public int[][] pieceEval={ {0,0,0,0,0,0,0,0}, {50,50,50,50,50,50,50,50}, {10,10,20,30,30,20,10,10}, {5,5,10,25,25,10,5,5}, {0,0,0,20,30,0,0,0}, {5,-5,-10,-5,-5,-10,-5,5}, {5,5,10,-20,-20,10,5,5}, {0,0,0,0,0,0,0,0}, }; public Pawn(int r, int f, Color c) { super(r, f, c); value=10; if(c==Color.WHITE){pieceEval= reverseGrid(pieceEval);} } @Override public void possibleMoves(Board board) { availCaptures=new ArrayList<>(); availMoves=new ArrayList<>(); availCheck=new ArrayList<>(); //if piece pinned to king // if(board.isPinned(rank, file, color)){ // ArrayList<Square> threats=board.getThreats(rank, file, color); // if(threats.size()>1) return; // int i=threats.get(0).getPiece().rank, j=threats.get(0).getPiece().file; // if(i==rank+1 && (j==file+1 || j==file-1)) availCaptures.add(new Move(rank, file,i,j)); // return; // } if(color==Color.WHITE){ if(!hasMoved()){ if(board.getSquare(rank+1, file).getPiece()==null){ availMoves.add(new Move(rank, file, rank+1, file)); if(board.getSquare(rank+2, file).getPiece()==null){ availMoves.add(new Move(rank, file, rank+2, file)); } } } else if(valid(rank+1,file) && board.getSquare(rank+1, file).getPiece()==null){ if(rank+1==7) availMoves.add(new Move(rank, file, rank+1, file, true, false)); else availMoves.add(new Move(rank, file, rank+1, file)); } if(valid(rank+1,file+1) && board.getSquare(rank+1, file+1).getPiece()!=null && board.getSquare(rank+1, file+1).getPiece().getColor()!=color){ if(board.getSquare(rank+1, file+1).getPiece().getValue()==200) availCheck.add(new Move(rank, file, rank+1, file+1)); else if(rank+1==7) availCaptures.add(new Move(rank, file, rank+1, file+1, true, true)); else availCaptures.add(new Move(rank, file, rank+1, file+1,false,true)); } if(valid(rank+1,file-1) && board.getSquare(rank+1, file-1).getPiece()!=null && board.getSquare(rank+1, file-1).getPiece().getColor()!=color){ if(board.getSquare(rank+1, file-1).getPiece().getValue()==200) availCheck.add(new Move(rank, file, rank+1, file+1)); else if(rank+1==7) availCaptures.add(new Move(rank, file, rank+1, file-1, true,true)); else availCaptures.add(new Move(rank, file, rank+1, file-1,false,true)); } } else if(color==Color.BLACK){ if(!hasMoved()){ availMoves.add(new Move(rank, file, rank-1, file)); availMoves.add(new Move(rank, file, rank-2, file)); } else if(valid(rank-1,file) && board.getSquare(rank-1, file).getPiece()==null){ if(rank-1==0) availMoves.add(new Move(rank, file, rank-1, file, true,false)); else availMoves.add(new Move(rank, file, rank-1, file)); } if(valid(rank-1,file+1) && board.getSquare(rank-1, file+1).getPiece()!=null && board.getSquare(rank-1, file+1).getPiece().getColor()!=color){ if(board.getSquare(rank-1, file+1).getPiece().getValue()==200) availCheck.add(new Move(rank, file, rank+1, file+1)); else if(rank-1==0) availCaptures.add(new Move(rank, file, rank-1, file+1, true, true)); else availCaptures.add(new Move(rank, file, rank-1, file+1,false,true)); } if(valid(rank-1,file-1) && board.getSquare(rank-1, file-1).getPiece()!=null && board.getSquare(rank-1, file-1).getPiece().getColor()!=color){ if(board.getSquare(rank-1, file-1).getPiece().getValue()==200) availCheck.add(new Move(rank, file, rank+1, file+1)); else if(rank-1==0) availCaptures.add(new Move(rank, file, rank-1, file-1, true, true)); else availCaptures.add(new Move(rank, file, rank-1, file-1,false,true)); } } } public String getString(){ if(color==Color.BLACK) return "p"; return "P"; } public int[][] getGrid(){return pieceEval;} }
package com.dfire.core.event.listenter; import com.dfire.common.constants.Constants; import com.dfire.common.entity.HeraJob; import com.dfire.common.entity.HeraJobMonitor; import com.dfire.common.entity.HeraUser; import com.dfire.common.service.EmailService; import com.dfire.common.service.HeraJobMonitorService; import com.dfire.common.service.HeraJobService; import com.dfire.common.service.HeraUserService; import com.dfire.common.util.ActionUtil; import com.dfire.common.util.NamedThreadFactory; import com.dfire.core.config.HeraGlobalEnvironment; import com.dfire.core.event.HeraJobFailedEvent; import com.dfire.core.event.base.MvcEvent; import com.dfire.core.netty.master.MasterContext; import com.dfire.logs.ErrorLog; import com.dfire.logs.ScheduleLog; import org.apache.commons.lang.StringUtils; import javax.mail.MessagingException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 任务失败的预处理 * @author xiaosuda */ public class HeraJobFailListener extends AbstractListener { private HeraUserService heraUserService; private HeraJobMonitorService heraJobMonitorService; private HeraJobService heraJobService; private EmailService emailService; private Executor executor; //告警接口,待开发 public HeraJobFailListener(MasterContext context) { heraUserService = context.getHeraUserService(); heraJobMonitorService = context.getHeraJobMonitorService(); emailService = context.getEmailService(); heraJobService = context.getHeraJobService(); executor = new ThreadPoolExecutor( 1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(Integer.MAX_VALUE), new NamedThreadFactory(), new ThreadPoolExecutor.AbortPolicy()); } @Override public void beforeDispatch(MvcEvent mvcEvent) { if (mvcEvent.getApplicationEvent() instanceof HeraJobFailedEvent) { HeraJobFailedEvent failedEvent = (HeraJobFailedEvent) mvcEvent.getApplicationEvent(); String actionId = failedEvent.getActionId(); Integer jobId = ActionUtil.getJobId(actionId); if (jobId == null) { return; } HeraJob heraJob = heraJobService.findById(jobId); //非开启任务不处理 最好能把这些抽取出去 提供接口实现 if (heraJob.getAuto() != 1) { return ; } executor.execute(() -> { List<String> emails = new ArrayList<>(1); try { HeraJobMonitor monitor = heraJobMonitorService.findByJobId(heraJob.getId()); if (monitor == null && Constants.PUB_ENV.equals(HeraGlobalEnvironment.getEnv())) { ScheduleLog.info("任务无监控人,发送给owner:{}", heraJob.getId()); HeraUser user = heraUserService.findByName(heraJob.getOwner()); emails.add(user.getEmail().trim()); } else if (monitor != null) { String ids = monitor.getUserIds(); String[] id = ids.split(Constants.COMMA); for (String anId : id) { if (StringUtils.isBlank(anId)) { continue; } HeraUser user = heraUserService.findById(Integer.parseInt(anId)); if (user != null && user.getEmail() != null) { emails.add(user.getEmail()); } } } if (emails.size() > 0) { emailService.sendEmail("hera任务失败了(" + HeraGlobalEnvironment.getEnv() + ")", "任务Id :" + actionId, emails); } } catch (MessagingException e) { e.printStackTrace(); ErrorLog.error("发送邮件失败"); } }); } } }
package com.edasaki.rpg.commands.owner; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map.Entry; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.edasaki.core.sql.SQLManager; import com.edasaki.core.utils.RMessages; import com.edasaki.core.utils.RScheduler; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.commands.RPGAbstractCommand; import com.edasaki.rpg.utils.RSerializer; public class ViewBankCommand extends RPGAbstractCommand { public ViewBankCommand(String... commandNames) { super(commandNames); } @Override public void execute(CommandSender sender, String[] args) { } @Override public void executePlayer(Player p, PlayerDataRPG pd, String[] args) { Player target = plugin.getServer().getPlayerExact(args[0]); if (target != null && target.isOnline() && plugin.getPD(target) != null) { PlayerDataRPG pd2 = plugin.getPD(target); pd.bank.setContents(pd2.getBankContents()); p.sendMessage("Set bank to " + target.getName() + "'s"); } else { p.sendMessage(ChatColor.RED + "Could not find online player '" + args[0] + "'."); p.sendMessage(ChatColor.RED + "Attempting offline lookup..."); RScheduler.scheduleAsync(plugin, () -> { AutoCloseable[] ac_dub = SQLManager.prepare("select name, bank from main where name = ?"); try { PreparedStatement request_items = (PreparedStatement) ac_dub[0]; request_items.setString(1, args[0]); AutoCloseable[] ac_trip = SQLManager.executeQuery(request_items); ResultSet rs = (ResultSet) ac_trip[0]; int count = 0; while (rs.next()) { String name = rs.getString("name"); String bank = rs.getString("bank"); RScheduler.schedule(plugin, () -> { pd.bank.clear(); if (bank != null) { HashMap<Integer, ItemStack> dBank = deserializeBank(bank); if (dBank != null) { for (Entry<Integer, ItemStack> e : dBank.entrySet()) { pd.bank.setItem(e.getKey(), e.getValue()); } } } RMessages.announce("set bank to " + name); }, count++); } SQLManager.close(ac_dub); SQLManager.close(ac_trip); } catch (Exception e) { e.printStackTrace(); } }); return; } } @Override public void executeConsole(CommandSender sender, String[] args) { } private HashMap<Integer, ItemStack> deserializeBank(String s) { HashMap<Integer, ItemStack> map = new HashMap<Integer, ItemStack>(); if (s == null) return null; String[] data = s.split("@"); if (data.length == 0 || (data.length == 1 && data[0].equals(""))) return null; for (String temp : data) { try { // don't use split in case item serialization contains :: String a = temp.substring(0, temp.indexOf("::")); String b = temp.substring(temp.indexOf("::") + "::".length()); int k = Integer.parseInt(a); ItemStack item = RSerializer.deserializeItemStack(b); map.put(k, item); } catch (Exception e) { e.printStackTrace(); } } return map; } }
package revolt.backend.controller; //приймає дто з фронту.. import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import revolt.backend.dto.SignInFormDto; import revolt.backend.dto.SignUpFormDto; import revolt.backend.entity.User; import revolt.backend.mapper.SignInFormMapper; import revolt.backend.mapper.SignUpFormMapper; import revolt.backend.security.AuthenticationConstant; import revolt.backend.service.serviceImpl.AuthenticationServiceImpl; import revolt.backend.service.serviceImpl.UserServiceImpl; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; @RestController @CrossOrigin @RequestMapping("/authentication") public class AuthenticationController { @Value("${app.cookieExpirationInS}") private int cookieExpiration; private AuthenticationServiceImpl authenticationService; private UserServiceImpl userServiceImpl; private SignInFormMapper signInFormMapper; private SignUpFormMapper signUpFormMapper; @Autowired public AuthenticationController(AuthenticationServiceImpl authenticationService, UserServiceImpl userServiceImpl, SignInFormMapper signInFormMapper, SignUpFormMapper signUpFormMapper) { this.authenticationService = authenticationService; this.userServiceImpl = userServiceImpl; this.signInFormMapper = signInFormMapper; this.signUpFormMapper = signUpFormMapper; } @PostMapping("/signin") public ResponseEntity<?> authenticateUser(HttpServletResponse response, @Valid @RequestBody SignInFormDto signInFormDTO) { User user = signInFormMapper.toEntity(signInFormDTO); String token = authenticationService.login(user); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(AuthenticationConstant .AUTHENTICATION_TOKEN_HEADER, token); response.addCookie(createCookie(token)); //this should only add headers and redirect, // but we don't have a page for redirection return ResponseEntity.ok() .headers(responseHeaders) .body(token); } @PostMapping("/signup") public ResponseEntity<?> registerUser(HttpServletResponse response, @Valid @RequestBody SignUpFormDto signUpFormDTO) throws Exception { User user = signUpFormMapper.toEntity(signUpFormDTO); String token = authenticationService.register(user); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set(AuthenticationConstant .AUTHENTICATION_TOKEN_HEADER, token); response.addCookie(createCookie(token)); //this should only add headers and redirect, // but we don't have a page for redirection return ResponseEntity.ok() .headers(responseHeaders) .body(token); } private Cookie createCookie(String token) { final Cookie cookie = new Cookie(AuthenticationConstant .AUTHENTICATION_TOKEN_HEADER, token); cookie.setHttpOnly(true); cookie.setMaxAge(cookieExpiration); return cookie; } }
package com.petpet.c3po.adaptor.rules; public class EmptyValueProcessingRule implements PreProcessingRule { @Override public boolean shouldSkip(String property, String value, String status, String tool, String version) { if (value.equals("")) { return true; } return false; } @Override public int getPriority() { return 1000; } }
package com.movieapp.anti.movieapp.Models; import java.io.Serializable; import java.util.ArrayList; /** * Created by Anti on 2/18/2018. */ public class Credits implements Serializable { // public ArrayList<Details> credits = new ArrayList<>(); public ArrayList<Cast> cast = new ArrayList<>(); public ArrayList<Crew> crew = new ArrayList<>(); }
package com.kirer.voice.util; import android.content.Context; import android.util.Log; import com.baidu.voicerecognition.android.Candidate; import com.baidu.voicerecognition.android.VoiceRecognitionClient; import com.baidu.voicerecognition.android.VoiceRecognitionConfig; import java.util.List; /** * Created by xinwb on 2016/12/16. */ public class BaiduUtil extends VoiceUtil { private static String TAG = "BAIDU_UTIL"; public static String LANGUAGE_EN = VoiceRecognitionConfig.LANGUAGE_ENGLISH; public static String LANGUAGE_CN = VoiceRecognitionConfig.LANGUAGE_CHINESE; private VoiceRecognitionClient mASREngine; private VoiceRecognitionConfig config; public BaiduUtil(Context context) { mASREngine = VoiceRecognitionClient.getInstance(context); mASREngine.setTokenApis("ybTWVLOYRWCwd44yuL9tZfSA", "3a8994fd78059014b5f845a693afcfc5"); config = new VoiceRecognitionConfig(); config.setProp(VoiceRecognitionConfig.PROP_INPUT); config.setLanguage(VoiceRecognitionConfig.LANGUAGE_CHINESE); config.enableVoicePower(true); // 音量反馈。 setLanguage(LANGUAGE_CN); } @Override public void setLanguage(String language) { config.setLanguage(language); } @Override public void start() { super.start(); int code = mASREngine.startVoiceRecognition(listener, config); if (code != VoiceRecognitionClient.START_WORK_RESULT_WORKING) { onVoiceToWordListener.onFailed("启动失败: " + code); } } @Override public void stop() { super.stop(); mASREngine.stopVoiceRecognition(); } private VoiceRecognitionClient.VoiceClientStatusChangeListener listener = new VoiceRecognitionClient.VoiceClientStatusChangeListener() { @Override public void onClientStatusChange(int i, Object o) { switch (i) { // 语音识别实际开始,这是真正开始识别的时间点,需在界面提示用户说话。 case VoiceRecognitionClient.CLIENT_STATUS_START_RECORDING: Log.d(TAG, "CLIENT_STATUS_START_RECORDING"); onVoiceToWordListener.onBegin(); break; case VoiceRecognitionClient.CLIENT_STATUS_SPEECH_START: // 检测到语音起点 Log.d(TAG, "CLIENT_STATUS_SPEECH_START"); onVoiceToWordListener.onBegin(); break; // 已经检测到语音终点,等待网络返回 case VoiceRecognitionClient.CLIENT_STATUS_SPEECH_END: Log.d(TAG, "CLIENT_STATUS_SPEECH_END"); break; // 语音识别完成,显示obj中的结果 case VoiceRecognitionClient.CLIENT_STATUS_FINISH: Log.d(TAG, "CLIENT_STATUS_FINISH"); updateRecognitionResult(o); onVoiceToWordListener.onEnd(); break; // 处理连续上屏 case VoiceRecognitionClient.CLIENT_STATUS_UPDATE_RESULTS: Log.d(TAG, "CLIENT_STATUS_UPDATE_RESULTS"); // updateRecognitionResult(o); break; // 用户取消 case VoiceRecognitionClient.CLIENT_STATUS_USER_CANCELED: Log.d(TAG, "CLIENT_STATUS_USER_CANCELED"); break; default: break; } } @Override public void onNetworkStatusChange(int i, Object o) { } @Override public void onError(int i, int errorCode) { onVoiceToWordListener.onFailed("失败: " + errorCode); } }; /** * 将识别结果更新到UI上,搜索模式结果类型为List<String>,输入模式结果类型为List<List<Candidate>> * * @param result */ private void updateRecognitionResult(Object result) { if (result != null && result instanceof List) { List results = (List) result; if (results.size() > 0) { if (results.get(0) instanceof List) { List<List<Candidate>> sentences = (List<List<Candidate>>) result; StringBuffer sb = new StringBuffer(); for (List<Candidate> candidates : sentences) { if (candidates != null && candidates.size() > 0) { sb.append(candidates.get(0).getWord()); } } onVoiceToWordListener.onSucceed(sb.toString()); } else { onVoiceToWordListener.onSucceed(results.get(0).toString()); } } } } }
package com.example; /** * * @author ecolban * */ public interface BufferInterface { /** * Removes the first element from the buffer * * @return the number that was removed * * @throws InterruptedException * if interrupted */ public byte remove() throws InterruptedException; /** * Adds a number to the end of the buffer. * * @param x * the number added * @throws InterruptedException * if interrupted */ public void add(byte x) throws InterruptedException; /** * * @return the first element in the buffer without removing it. * @throws InterruptedException */ public int peek() throws InterruptedException; /** * Gets the count of elements in the buffer * * @return the number of elements in the buffer */ public int getCount(); /** * * @return true if the buffer is empty, false otherwise */ public boolean isEmpty(); /** * * @return true if the buffer is full, false otherwise */ public boolean isFull(); }
public class Book { private int bookNumber; private String bookName; private String author; private int ratePerUnit; static String publisher="Orilley"; public Book() { super(); // TODO Auto-generated constructor stub } public double findDiscount(){ double discount=0.1; if(author.equals("sashi")){ discount=0.2; } return discount; } public int getBookNumber() { return bookNumber; } public void setBookNumber(int bookNumber) { this.bookNumber = bookNumber; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getRatePerUnit() { return ratePerUnit; } public void setRatePerUnit(int ratePerUnit) { this.ratePerUnit = ratePerUnit; } public Book(int bookNumber, String bookName, String author, int ratePerUnit) { super(); this.bookNumber = bookNumber; this.bookName = bookName; this.author = author; this.ratePerUnit = ratePerUnit; } /*public Book(int bookNumber, String bookName, String author) { //super(); this(bookNumber,bookName,author,0.0); }*/ @Override public String toString() { // TODO Auto-generated method stub return this.bookName; //return super.toString(); } }
package com.pbadun.database; import java.util.ArrayList; import com.pbadun.fragment.interfaces.IAsync; import com.pbadun.model.RssItemModel; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; public class DbWork extends AsyncTask<Void, Void, Void> { private DBase db; private SQLiteDatabase sdb; private ArrayList<RssItemModel> myResult; private IAsync bagItrerface; public DbWork(Context context, IAsync bg) { this.bagItrerface = bg; this.db = new DBase(context); this.sdb = db.getWritableDatabase(); } // Сохранение результатов в базу public void saveResulToDb(RssItemModel result) { ContentValues cv = new ContentValues(); cv.put(DBase.LINK, result.getLink()); cv.put(DBase.TITLE, result.getTitle()); cv.put(DBase.DESCRIPTION, result.getDescription()); cv.put(DBase.ICON, result.getEnclosureUrl()); cv.put(DBase.PUBDATE, result.getPubDate()); sdb.insert(DBase.TABLE_NAME, null, cv); } // Очистить базу... public void clearTable() { sdb.execSQL("delete from " + DBase.TABLE_NAME + " where 1"); } // ------------------------------------------------------- // Методы AsyncTask @Override protected Void doInBackground(Void... params) { Cursor cursor = sdb.query(DBase.TABLE_NAME, new String[] { DBase.TITLE, DBase.DESCRIPTION, DBase.PUBDATE, DBase.ICON, DBase.LINK }, null, null, null, null, null); while (cursor.moveToNext()) { RssItemModel rrsi = new RssItemModel(); rrsi.setDescription(cursor.getString(cursor .getColumnIndex(DBase.DESCRIPTION))); rrsi.setEnclosureUrl(cursor.getString(cursor .getColumnIndex(DBase.ICON))); rrsi.setLink(cursor.getString(cursor.getColumnIndex(DBase.LINK))); rrsi.setPubDate(cursor.getString(cursor .getColumnIndex(DBase.PUBDATE))); rrsi.setTitle(cursor.getString(cursor.getColumnIndex(DBase.TITLE))); myResult.add(rrsi); } cursor.close(); return null; } @Override protected void onPreExecute() { this.myResult = new ArrayList<RssItemModel>(); } @Override protected void onPostExecute(Void result) { bagItrerface.setResult(myResult); } }
package org.didierdominguez.bean; public class CreditCardPayment { private Integer id; private CreditCard creditCard; private String type; private String date; private Double amount; public CreditCardPayment(Integer id, CreditCard creditCard, String type, String date, Double amount) { this.id = id; this.creditCard = creditCard; this.type = type; this.date = date; this.amount = amount; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public CreditCard getCreditCard() { return creditCard; } public void setCreditCard(CreditCard creditCard) { this.creditCard = creditCard; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } }
package com.example.user.foodapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.LinearLayout; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { RecyclerView r1; List<Model> kereta = new ArrayList(); MyOwnAdapter ad; public void masukan() { kereta.add(new Model("Pizza","Pizza a yeasted flatbread typically topped with tomato sauce.","\nIngredients:\n" + "- 2 Siung bawang bombay.\n- 2 Buah sosis.\n- 2 Buah tomat.\n" + "- Daging cincang.\n- 1 Buah paprika.\n- 2 Siung bawang putih.\n- 1 Butir telur ayam.\n" + "\nSteps:\n" + "1. Ambil adonan roti, masukkan ke dalam teflon, ratakan, lalu tusuk - tusuk dengan garpu supaya adonan dapat mengembang.\n" + "2. Beri saus tomat pada adonan sampai rata. Taburkan topping dan lapisi lagi dengan saus tomat.\n" + "3. Kemudian beri parutan keju di bagian atas. Lalu angkat dan Pizza italia rumahan tanpa oven namun tetap enak siap untuk disajikan.", R.drawable.pizza)); kereta.add(new Model("Hamburger","Hamburger is a sandwich consisting of cooked patties.","\nIngredients:\n" + "- 4 Roti hamburger.\n- 400g Daging sapi.\n- 1 Buah tomat.\n" + "- Daun selada.\n- 1 Buah paprika.\n- 2 Siung bawang putih.\n- Acar & timun.\n" + "\nSteps:\n" + "1. Buat terlebih dahulu isi hamburger dengan cara mencampurkan cincangan daging, tepung roti, lada putih dan bawang putih kedalam wadah yang sama sambil diaduk hingga tercampur rata.\n" + "2. Bila sudah matang, angkat dan sisihkan. Beri olesan lagi kedalam wajan bekas memasak adonan daging tadi kemudian masukkan roti hamburger dan keju diatasnya dan panggang sebentar saja. Angkat.\n" + "3. Tata rapi roti haburger, isi hamburger, daun selada, tomat dan acar mentimun lalu tutup lagi dengan roti. Hidangkan.", R.drawable.hamb)); kereta.add(new Model("Chicken Nugget","Chicken Nugget is a chicken product made from chicken meat.","\nIngredients:\n" + "- 500g Daging ayam tanpa tulang.\n- 400g Daging sapi.\n- 1 Buah tomat.\n" + "- Daun selada.\n- 1 Buah paprika.\n- 2 Siung bawang putih.\n- Acar & timun.\n" + "\nSteps:\n" + "1. Buat terlebih dahulu isi hamburger dengan cara mencampurkan cincangan daging, tepung roti, lada putih dan bawang putih kedalam wadah yang sama sambil diaduk hingga tercampur rata.\n" + "2. Bila sudah matang, angkat dan sisihkan. Beri olesan lagi kedalam wajan bekas memasak adonan daging tadi kemudian masukkan roti hamburger dan keju diatasnya dan panggang sebentar saja. Angkat.\n" + "3. Tata rapi roti haburger, isi hamburger, daun selada, tomat dan acar mentimun lalu tutup lagi dengan roti. Hidangkan.", R.drawable.chick)); kereta.add(new Model("Spaghetti","Spaghetti is a long, thin, cylindrical, solid pasta.It is a staple food of traditional Italian\n","\nIngredients:\n" + "- 2 Siung bawang bombay.\n- 2 Buah sosis.\n- 1 Buah tomat.\n" + "- Daging cincang.\n- 1 Buah paprika.\n- 2 Siung bawang putih.\n- 1 Butir telur ayam.\n" + "\nSteps:\n" + "1. Ambil adonan roti, masukkan ke dalam teflon, ratakan, lalu tusuk - tusuk dengan garpu supaya adonan dapat mengembang.\n" + "2. Beri saus tomat pada adonan sampai rata. Taburkan topping dan lapisi lagi dengan saus tomat.\n" + "3. Kemudian beri parutan keju di bagian atas. Lalu angkat dan Pizza italia rumahan tanpa oven namun tetap enak siap untuk disajikan.", R.drawable.spag)); kereta.add(new Model("Shawarma","Shawarma is a Levantine meat preparation, where lamb, chicken, turkey, beef, veal, or mixed meats","\nIngredients:\n" + "- 2 Siung bawang bombay.\n- 2 Buah sosis.\n- 2 Buah tomat.\n" + "- Daging cincang.\n- 1 Buah paprika.\n- 2 Siung bawang putih.\n- 1 Butir telur ayam.\n" + "\nSteps:\n" + "1. Ambil adonan roti, masukkan ke dalam teflon, ratakan, lalu tusuk - tusuk dengan garpu supaya adonan dapat mengembang.\n" + "2. Beri saus tomat pada adonan sampai rata. Taburkan topping dan lapisi lagi dengan saus tomat.\n" + "3. Kemudian beri parutan keju di bagian atas. Lalu angkat dan Pizza italia rumahan tanpa oven namun tetap enak siap untuk disajikan.", R.drawable.shaw)); ad.notifyDataSetChanged(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); r1 = (RecyclerView) findViewById(R.id.myRecycler); ad = new MyOwnAdapter(this, kereta); r1.setAdapter(ad); r1.setLayoutManager(new LinearLayoutManager(this)); masukan(); } }
package com.zzwc.cms.common.bean.validator.group; /** * 更新数据 Group */ public interface UpdateGroup { }
package com.dodoca.create_image.constants; /** * @description: * @author: tianguanghui * @create: 2019-07-09 17:33 **/ public class ActivityType { /** 秒杀 */ public static final String SECKILL = "seckill"; /** 砍价 */ public static final String BARGAIN = "bargain"; /** 拼团 */ public static final String PINTUAN = "pintuan"; /** 帮免 */ public static final String BANGMIAN = "bangmian"; /** 套餐 */ public static final String COMBO = "combo"; /** 代付 */ public static final String PEERPAY = "peerpay"; /** 夺宝 */ public static final String SNATCH = "snatch"; }
public abstract class piece implements Runnable { //Properties public String strColour; public int PiNum; public boolean blnMove; public int sint; public boolean canMove = false; public int intCount; //Methods public abstract int[][] checkMove(int intX,int intY,piece[][] object); public String col(){ return this.strColour; } public int Num(){ return this.PiNum; } public void run(){ this.canMove=false; intCount=0; while(true){ pause(); intCount++; System.out.println(intCount); if(intCount>=30){ break; } } intCount=0; this.canMove=true; } public void pause(){ try{ Thread.sleep(1000); }catch(InterruptedException e){ } } //Constructor public piece(String strC,int pi,boolean blnMove){ this.strColour=strC; this.PiNum=pi; this.canMove=blnMove; this.sint=1; } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import USJavaAPI.USHttpsPostRequest; import USJavaAPI.USL23IndependentRefund; import USJavaAPI.USReceipt; import USJavaAPI.Addendum1; import USJavaAPI.Addendum2; public class TestL23IndependentRefund { public static void main(String args[]) throws IOException { /********************** Request Variables ****************************/ String host = "esplusqa.moneris.com"; String store_id = "monusqa002"; String api_token = "qatoken"; /********************** Transaction Variables ************************/ String order_id; // will prompt for user input String cust_id = "customer1"; String amount = "1.00"; String pan = "5454545442424242"; String expdate = "1512"; String crypt = "7"; InputStreamReader isr = new InputStreamReader( System.in ); BufferedReader stdin = new BufferedReader( isr ); System.out.print( "Please enter an order ID: " ); order_id = stdin.readLine(); /*****Level23 Data******/ /*****Addendum1 Data******/ String customer_code = "123"; String local_tax_amount = "1.00"; String discount_amount = "1.00"; String freight_amount = "1.00"; String duty_amount = "1.00"; String national_tax_amount = "1.00"; String other_tax_amount = "1.00"; String vat_invoice_ref_num = "123"; String customer_vat_registration_num = "123"; String vat_tax_amount = "1.00"; String vat_tax_rate = "0.00"; String destination_zip = "90210"; String ship_from_zip = "12345"; Addendum1 addendum1 = new Addendum1(customer_code, local_tax_amount, discount_amount, freight_amount, duty_amount, national_tax_amount, other_tax_amount, vat_invoice_ref_num, customer_vat_registration_num, vat_tax_amount, vat_tax_rate, destination_zip, ship_from_zip); /*****Addendum2 Data Item 1******/ String item_description1 = "description"; String product_code1 = "123"; String commodity_code1 = "1"; String quantity1 = "1"; String unit_cost1 = "1.00"; String ext_amount1 = "1.00"; String uom1 = "1"; String tax_collected_ind1 = "1"; String item_discount_amount1 = "1.00"; String item_local_tax_amount1 = "1.00"; String item_other_tax_amount1 = "1.00"; String item_other_tax_type1 = "1"; String item_other_tax_rate1 = "0.00"; String item_other_tax_id1 = "123"; Addendum2 item1 = new Addendum2(item_description1, product_code1, commodity_code1, quantity1, unit_cost1, ext_amount1, uom1, tax_collected_ind1, item_discount_amount1, item_local_tax_amount1, item_other_tax_amount1, item_other_tax_type1, item_other_tax_rate1, item_other_tax_id1); /*****Addendum2 Data Item 2******/ String item_description2 = "description"; String product_code2 = "123"; String commodity_code2 = "1"; String quantity2 = "1"; String unit_cost2 = "1.00"; String ext_amount2 = "1.00"; String uom2 = "1"; String tax_collected_ind2 = "1"; String item_discount_amount2 = "1.00"; String item_local_tax_amount2 = "1.00"; String item_other_tax_amount2 = "1.00"; String item_other_tax_type2 = "1"; String item_other_tax_rate2 = "0.00"; String item_other_tax_id2 = "123"; Addendum2 item2 = new Addendum2(item_description2, product_code2, commodity_code2, quantity2, unit_cost2, ext_amount2, uom2, tax_collected_ind2, item_discount_amount2, item_local_tax_amount2, item_other_tax_amount2, item_other_tax_type2, item_other_tax_rate2, item_other_tax_id2); Addendum2[] addendum2 = new Addendum2[]{item1, item2}; USHttpsPostRequest mpgReq = new USHttpsPostRequest(host, store_id, api_token, new USL23IndependentRefund(order_id, cust_id, amount, pan, expdate, crypt, addendum1, addendum2)); try { USReceipt receipt = mpgReq.getReceipt(); System.out.println("CardType = " + receipt.getCardType()); System.out.println("TransAmount = " + receipt.getTransAmount()); System.out.println("TxnNumber = " + receipt.getTxnNumber()); System.out.println("ReceiptId = " + receipt.getReceiptId()); System.out.println("TransType = " + receipt.getTransType()); System.out.println("ReferenceNum = " + receipt.getReferenceNum()); System.out.println("ResponseCode = " + receipt.getResponseCode()); System.out.println("BankTotals = " + receipt.getBankTotals()); System.out.println("Message = " + receipt.getMessage()); System.out.println("AuthCode = " + receipt.getAuthCode()); System.out.println("Complete = " + receipt.getComplete()); System.out.println("TransDate = " + receipt.getTransDate()); System.out.println("TransTime = " + receipt.getTransTime()); System.out.println("Ticket = " + receipt.getTicket()); System.out.println("TimedOut = " + receipt.getTimedOut()); } catch (Exception e) { e.printStackTrace(); } } } // end TestL23IndependentRefund
package br.com.wasys.library.widget; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.view.Window; import android.view.WindowManager; /** * Created by pascke on 20/09/16. */ public class AppAlertDialog extends Dialog { private int mIcon; private String mTitle; private String mMessage; private AppAlertDialog(Builder builder) { super(builder.context); mIcon = builder.icon; mTitle = builder.title; mMessage = builder.message; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); setTitle("???"); } public static class Builder { private int icon; private String title; private String message; private Context context; public Builder(Context context) { this.context = context; } public Builder icon(@DrawableRes int icon) { this.icon = icon; return this; } public Builder title(String title) { this.title = title; return this; } public Builder message(String message) { this.message = message; return this; } public Builder title(@StringRes int title) { return title(context.getString(title)); } public Builder message(@StringRes int message) { return message(context.getString(message)); } public AppAlertDialog build() { return new AppAlertDialog(this); } } }
package org.bindgen.processor.generators; import java.util.Collection; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.TypeElement; import org.bindgen.ContainerBinding; import org.bindgen.processor.util.BoundClass; import org.bindgen.processor.util.BoundProperty; import org.bindgen.processor.util.Util; import joist.sourcegen.GClass; import joist.sourcegen.GMethod; /** * Generates bindings for fields */ public class FieldPropertyGenerator extends AbstractGenerator implements PropertyGenerator { private final Element field; private final String fieldName; private final BoundProperty property; private final boolean isFinal; public FieldPropertyGenerator(GClass outerClass, BoundClass boundClass, TypeElement outerElement, Element field, String propertyName) throws WrongGeneratorException { super(outerClass); this.field = field; this.fieldName = this.field.getSimpleName().toString(); this.property = new BoundProperty(outerElement, boundClass, this.field, this.field.asType(), propertyName); if (this.property.shouldSkip()) { throw new WrongGeneratorException(); } this.isFinal = this.field.getModifiers().contains(javax.lang.model.element.Modifier.FINAL); } @Override public boolean hasSubBindings() { return true; } @Override protected void generateInner() { if (this.property.name.getDeclaredType() != null && !this.property.name.getDeclaredType().getTypeArguments().isEmpty()) { this.addInnerClass(); this.addInnerClassGetName(); this.addInnerClassGetParent(); this.addInnerClassGet(); this.addInnerClassGetWithRoot(); this.addInnerClassGetSafelyWithRoot(); this.addInnerClassSet(); this.addInnerClassSetWithRoot(); this.addInnerClassGetContainedTypeIfNeeded(); this.addInnerClassSerialVersionUID(); this.addInnerClassIsReadOnlyOverrideIfNeeded(); } } @Override protected void addOuterClassBindingField() { this.outerClass.getField(this.property.getName()).type(this.property.getBindingClassFieldDeclaration()); } private void addOuterOldClassGet() { GMethod fieldGet = this.outerClass.getMethod(this.property.getName() + "()"); fieldGet.setAccess(Util.getAccess(this.field)); fieldGet.returnType(this.property.getBindingClassFieldDeclaration()); fieldGet.body.line("if (this.{} == null) {", this.property.getName()); fieldGet.body.line(" this.{} = new {}();", this.property.getName(), this.property.getBindingRootClassInstantiation()); fieldGet.body.line("}"); fieldGet.body.line("return this.{};", this.property.getName()); } @Override protected void addOuterClassGet() { if (this.property.name.getDeclaredType() != null && !this.property.name.getDeclaredType().getTypeArguments().isEmpty()) { this.addOuterOldClassGet(); } else { String bindingType = this.property.getInnerClassSuperClass(); GMethod fieldGet = this.outerClass.getMethod(this.property.getName() + "()"); fieldGet.setAccess(Util.getAccess(this.field)); fieldGet.returnType(this.property.getBindingClassFieldDeclaration()); if (bindingType.contains("U1")) { fieldGet.typeParameters("U0, U1"); } else if (bindingType.contains("U0")) { fieldGet.typeParameters("U0"); } fieldGet.body.line("if (this.{} == null) {", this.property.getName()); String type; if (this.property.isForGenericTypeParameter() || this.property.isArray()) { type = "null"; } else { type = String.format("%s.class", this.property.getReturnableType()); } String setterLambda = "null /* (item, value) -> item.{}(value) */"; // if (this.hasSetterMethod()) { // setterLambda = "(item, value) -> item.{}(value)"; // } if (!this.isFinal) { setterLambda = "(item, value) -> item.{} = value"; } else { setterLambda = null; } if (!"null".equals(type)) { fieldGet.body.line( String.format(" this.{} = new {}(\"{}\", {}, this, (item) -> item.{}, %s);", setterLambda), this.property.getName(), this.property.getInnerClassSuperClass(), this.property.getName(), type, this.fieldName, this.fieldName); } else if (this.property.isArray()) { fieldGet.body.line( String.format(" this.{} = new {}(\"{}\", {}, this, (item) -> item.{}, %s);", setterLambda), this.property.getName(), this.property.getInnerClassSuperClass(), this.property.getName(), null, this.fieldName, this.fieldName); } else { fieldGet.body.line( String.format(" this.{} = new {}(\"{}\", this, (item) -> item.{}, %s);", setterLambda), this.property.getName(), this.property.getInnerClassSuperClass(), this.property.getName(), this.fieldName, this.fieldName); } fieldGet.body.line("}"); fieldGet.body.line("return this.{};", this.property.getName()); } } private void addInnerClass() { this.innerClass = this.outerClass.getInnerClass(this.property.getInnerClassDeclaration()).notStatic(); this.innerClass.setAccess(Util.getAccess(this.field)); this.innerClass.baseClassName(this.property.getInnerClassSuperClass()); if (this.property.isForGenericTypeParameter() || this.property.isArray()) { this.innerClass.getMethod("getType").returnType("Class<?>").body.line("return null;"); } else if (!this.property.shouldGenerateBindingClassForType()) { // since no binding class will be generated for the type of this // field we may not inherit getType() in MyBinding class (if, for // example, MyBinding extends GenericObjectBindingPath) and so we // have to implement it ouselves this.innerClass.getMethod("getType").returnType("Class<?>").body.line("return {}.class;", this.property.getReturnableType()); } } private void addInnerClassGetName() { GMethod getName = this.innerClass.getMethod("getName").returnType(String.class).addAnnotation("@Override"); getName.body.line("return \"{}\";", this.property.getName()); } private void addInnerClassGetParent() { GMethod getParent = this.innerClass.getMethod("getParentBinding").returnType("Binding<?>") .addAnnotation("@Override"); getParent.body.line("return {}.this;", this.outerClass.getSimpleName()); } private void addInnerClassGet() { GMethod get = this.innerClass.getMethod("get").returnType(this.property.getSetType()) .addAnnotation("@Override"); get.body.line("return {}{}.this.get().{};", // this.property.getCastForReturnIfNeeded(), this.outerClass.getSimpleName(), this.fieldName); } private void addInnerClassGetWithRoot() { GMethod getWithRoot = this.innerClass.getMethod("getWithRoot"); getWithRoot.argument(property.getBoundClass().getRootTypeArgument(), "root") .returnType(this.property.getSetType()).addAnnotation("@Override"); getWithRoot.body.line("return {}{}.this.getWithRoot(root).{};", // this.property.getCastForReturnIfNeeded(), this.outerClass.getSimpleName(), this.fieldName); } private void addInnerClassGetSafelyWithRoot() { GMethod m = this.innerClass.getMethod("getSafelyWithRoot"); m.argument(property.getBoundClass().getRootTypeArgument(), "root") .returnType(this.property.getSetType()).addAnnotation("@Override"); m.body.line("if ({}.this.getSafelyWithRoot(root) == null) {", this.outerClass.getSimpleName()); m.body.line(" return null;"); m.body.line("} else {"); m.body.line(" return {}{}.this.getSafelyWithRoot(root).{};", // this.property.getCastForReturnIfNeeded(), this.outerClass.getSimpleName(), this.fieldName); m.body.line("}"); } private void addInnerClassSet() { GMethod set = this.innerClass.getMethod("set").argument(this.property.getSetType(), this.property.getName()); set.addAnnotation("@Override"); if (this.isFinal) { set.body.line("throw new RuntimeException(this.getName() + \" is read only\");"); return; } set.body.line("{}.this.get().{} = {};", // this.outerClass.getSimpleName(), this.fieldName, this.property.getName()); } private void addInnerClassSetWithRoot() { GMethod setWithRoot = this.innerClass.getMethod("setWithRoot({} root, {} {})", property.getBoundClass().getRootTypeArgument(), this.property.getSetType(), this.property.getName() ); setWithRoot.addAnnotation("@Override"); if (this.isFinal) { setWithRoot.body.line("throw new RuntimeException(this.getName() + \" is read only\");"); return; } setWithRoot.body.line("{}.this.getWithRoot(root).{} = {};", // this.outerClass.getSimpleName(), this.fieldName, this.property.getName()); } private void addInnerClassGetContainedTypeIfNeeded() { if (this.property.isForListOrSet() && !this.property.matchesTypeParameterOfParent()) { this.innerClass.implementsInterface(ContainerBinding.class); GMethod getContainedType = this.innerClass.getMethod("getContainedType").returnType("Class<?>") .addAnnotation("@Override"); getContainedType.body.line("return {};", this.property.getContainedType()); } } private void addInnerClassSerialVersionUID() { this.innerClass.getField("serialVersionUID").type("long").setStatic().setFinal().initialValue("1L"); } private void addInnerClassIsReadOnlyOverrideIfNeeded() { if (this.isFinal) { this.innerClass.getMethod("getBindingIsReadOnly").returnType(boolean.class).body.line("return true;"); } } @Override public List<TypeElement> getPropertyTypeElements() { return Util.collectTypeElements(this.property.getType()); } @Override public String getPropertyName() { return this.property.getName(); } @Override public String toString() { return this.field.toString(); } public static class Factory implements GeneratorFactory { @Override public FieldPropertyGenerator newGenerator(GClass outerClass, BoundClass boundClass, TypeElement outerElement, Element possibleField, Collection<String> namesTaken) throws WrongGeneratorException { if (possibleField.getKind() != ElementKind.FIELD) { throw new WrongGeneratorException(); } String propertyName = possibleField.getSimpleName().toString(); if (namesTaken.contains(propertyName)) { propertyName += "Field"; } while (Util.isObjectMethodName(propertyName) || Util.isBindingMethodName(propertyName)) { propertyName += "Field"; // Still invalid } return new FieldPropertyGenerator(outerClass, boundClass, outerElement, possibleField, propertyName); } } }
package FinalPrac; import java.lang.invoke.VarHandle; public class TreeS { public static void main(String args[]) { int[] arr = {50, 30, 70, 15, 7, 62, 22, 35, 87, 31}; TreeSort TS = new TreeSort(arr[0]); System.out.println("정렬 전 : "); printArray(arr); TS.Sorting(arr); System.out.println("\n정렬 후 : "); printArray(arr); } public static void printArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.printf(" %d", arr[i]); } } } class TNode { int data; TNode left; TNode right; TNode (int value) { this.data = value; this.left = null; this.right = null; } } class TreeSort { TNode node; int count = 0; TreeSort(int value) { node = new TNode(value); } public void Sorting(int arr[]) { for (int i = 0; i < arr.length; i++) { insertBST(node, arr[i]); } inorder(node, arr); } public TNode insertBST(TNode node, int value) { if (node == null) { return new TNode(value); } if (node.data > value) { node.right = insertBST(node.right, value); } else if (node.data < value) { node.left = insertBST(node.left, value); } return node; } public void inorder(TNode node, int arr[]) { if (node != null) { inorder(node.left, arr); arr[count++] = node.data; inorder(node.right, arr); } } }
package com.gsccs.sme.plat.auth.model; public class DictGroupT { private String id; private String code; private String title; private String val; private String remark; private String status; public String getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column plat_dict_group.id * * @param id the value for plat_dict_group.id * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public void setId(String id) { this.id = id == null ? null : id.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column plat_dict_group.code * * @return the value of plat_dict_group.code * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public String getCode() { return code; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column plat_dict_group.code * * @param code the value for plat_dict_group.code * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public void setCode(String code) { this.code = code == null ? null : code.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column plat_dict_group.title * * @return the value of plat_dict_group.title * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public String getTitle() { return title; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column plat_dict_group.title * * @param title the value for plat_dict_group.title * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public void setTitle(String title) { this.title = title == null ? null : title.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column plat_dict_group.val * * @return the value of plat_dict_group.val * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public String getVal() { return val; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column plat_dict_group.val * * @param val the value for plat_dict_group.val * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public void setVal(String val) { this.val = val == null ? null : val.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column plat_dict_group.remark * * @return the value of plat_dict_group.remark * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public String getRemark() { return remark; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column plat_dict_group.remark * * @param remark the value for plat_dict_group.remark * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column plat_dict_group.status * * @return the value of plat_dict_group.status * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public String getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column plat_dict_group.status * * @param status the value for plat_dict_group.status * * @mbggenerated Wed Mar 09 16:36:37 CST 2016 */ public void setStatus(String status) { this.status = status == null ? null : status.trim(); } }
package Server; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Toolkit; import java.util.concurrent.CopyOnWriteArrayList; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import java.util.*; import util.BoundedBuffer; import util.MovePacket; import util.Snake; public class Highscores { Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); CopyOnWriteArrayList<Snake> playerList; public Highscores(CopyOnWriteArrayList<Snake> playerList, int x, int y) { this.playerList = playerList; } String[][] sortedList; public String[][] getHighestScores() { sortedList = new String[playerList.size()][2]; int counter = 0; for (Snake snake : playerList) { sortedList[counter][0] = Integer.toString(snake.getLength()); sortedList[counter][1] = snake.name; counter += 1; } Arrays.sort(sortedList, new Comparator<String[]>() { @Override public int compare(final String[] entry1, final String[] entry2) { try { final int time1 = Integer.valueOf(entry1[0]); final int time2 = Integer.valueOf(entry2[0]); return time2 - time1; } catch (NumberFormatException e) { return -1; } } }); return sortedList; } public void updateHighscores(Graphics graph) { List<String[]> list = Arrays.asList(getHighestScores()); int size = 15; int cap = 5; graph.setColor(Color.BLACK); for (int i=0; i<list.size(); i++) { if (i < cap) graph.drawString("#"+(i+1)+" | "+list.get(i)[0] + " | " + list.get(i)[1] , 0, size); size += 15; } } }
package com.wukongzou.chinarentalbicyclemap.constant; public class Constant { public static final String LOG_TAG_APP = "app"; }
package com.train.amm.service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.Message; import com.train.amm.LocalMusicAcitivity; import com.train.amm.imp.LocalMusicControl; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; public class LocalMusicService extends Service { MediaPlayer mediaPlayer; private Timer timer; /** * Return the communication channel to the service. May return null if * clients can not bind to the service. The returned * {@link IBinder} is usually for a complex interface * that has been <a href="{@docRoot}guide/components/aidl.html">described using * aidl</a>. * * <p><em>Note that unlike other application components, calls on to the * IBinder interface returned here may not happen on the main thread * of the process</em>. More information about the main thread can be found in * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and * Threads</a>.</p> * * @param intent The Intent that was used to bind to this service, * as given to {@link Context#bindService * Context.bindService}. Note that any extras that were included with * the Intent at that point will <em>not</em> be seen here. * @return Return an IBinder through which clients can call on to the * service. */ @Override public IBinder onBind(Intent intent) { return new MyMusicControl(); } @Override public void onCreate() { super.onCreate(); //创建MediaPlayer对象 mediaPlayer = new MediaPlayer(); } @Override public void onDestroy() { super.onDestroy(); //停止播放 mediaPlayer.stop(); //释放占用的资源,此时,mediaPlayer对象销毁 mediaPlayer.release(); mediaPlayer = null; if (timer != null) { timer.cancel(); timer = null; } } @Override public boolean onUnbind(Intent intent) { return super.onUnbind(intent); } class MyMusicControl extends Binder implements LocalMusicControl { @Override public void play() { LocalMusicService.this.play(); } @Override public void pause() { LocalMusicService.this.pause(); } @Override public void playAgain() { LocalMusicService.this.continuePlay(); } @Override public void seekTo(int progress) { LocalMusicService.this.seekTo(progress); } } public void play() { //重置 mediaPlayer.reset(); try { //加载多媒体资源 mediaPlayer.setDataSource("sdcard/tkdr.mp3"); mediaPlayer.prepare(); mediaPlayer.start(); addTimer(); } catch (IOException e) { e.printStackTrace(); } } public void playNetMusic() { mediaPlayer.reset(); try { mediaPlayer.setDataSource("192.168.6.238:8080/tkdr.mp3"); //异步准备 mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { //监听加载完成后,开始播放 mediaPlayer.start(); } }); } catch (IOException e) { e.printStackTrace(); } } public void continuePlay() { mediaPlayer.start(); } public void pause() { mediaPlayer.pause(); } public void seekTo(int progress){ mediaPlayer.seekTo(progress); } public void addTimer() { if (timer == null) { timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { //获取歌曲总时长 int duration = mediaPlayer.getDuration(); //获取当前的时长 int currentPosition = mediaPlayer.getCurrentPosition(); Message msg = LocalMusicAcitivity.handler.obtainMessage(); //把消息进度封装在bundle对象中 Bundle bundle = new Bundle(); bundle.putInt("duration", duration); bundle.putInt("currentPosition", currentPosition); msg.setData(bundle); LocalMusicAcitivity.handler.sendMessage(msg); } //开始计时后5毫秒后开始第一次执行run,之后每500毫秒执行一次 }, 5, 500); } } }
package controllers; import actors.ClusterSystem; import actors.GameActor; import akka.actor.ActorRef; import com.example.protocols.Commands; import com.example.protocols.Queries; import play.data.DynamicForm; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import views.html.index; public class Application extends Controller { private static ActorRef gameActor = ClusterSystem.getActorSystem().actorOf(GameActor.props()); public static Result index() { final String message = flash("message"); return ok(index.render(message)); } public static Result newTeam() { final DynamicForm requestData = Form.form().bindFromRequest(); final String teamName = requestData.get("teamName"); gameActor.tell(new Commands.NewTeam(teamName), ActorRef.noSender()); flash("message", "Team Created"); return redirect("/"); } public static Result newPlayer() { final DynamicForm requestData = Form.form().bindFromRequest(); final String teamName = requestData.get("teamName"); final String name = requestData.get("name"); final int jerseyNumber = Integer.parseInt(requestData.get("jerseyNumber")); gameActor.tell(new Commands.AddPlayer(teamName, jerseyNumber, name), ActorRef.noSender()); flash("message", "Player Added"); return redirect("/"); } public static Result score() { final DynamicForm requestData = Form.form().bindFromRequest(); final String teamName = requestData.get("teamName"); final int jerseyNumber = Integer.parseInt(requestData.get("jerseyNumber")); final int score = Integer.parseInt(requestData.get("score")); gameActor.tell(new Commands.PlayerScore(teamName, jerseyNumber, score), ActorRef.noSender()); flash("message", "Player scored"); return redirect("/"); } public static Result player() { /*return wrap(ask(gameActor, new QueryProtocols.PlayerNameRequest("Test", 1), 1000)).map(obj -> ok(Json.toJson(obj)) );*/ gameActor.tell(new Queries.PlayerNameRequest("Test", 1), ActorRef.noSender()); return ok(); } }
/* * Copyright 2002-2023 the original author or authors. * * 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 * * https://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.springframework.r2dbc.connection.init; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import io.r2dbc.spi.Connection; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.io.Resource; import org.springframework.core.io.buffer.DataBufferFactory; import org.springframework.core.io.buffer.DefaultDataBufferFactory; import org.springframework.core.io.support.EncodedResource; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Populates, initializes, or cleans up a database using SQL * scripts defined in external resources. * <ul> * <li>Call {@link #addScript} to add a single SQL script location. * <li>Call {@link #addScripts} to add multiple SQL script locations. * <li>Consult the setter methods in this class for further configuration options. * <li>Call {@link #populate} to initialize or clean up the database using the configured scripts. * </ul> * * @author Keith Donald * @author Dave Syer * @author Juergen Hoeller * @author Chris Beams * @author Oliver Gierke * @author Sam Brannen * @author Chris Baldwin * @author Phillip Webb * @author Mark Paluch * @since 5.3 * @see ScriptUtils */ public class ResourceDatabasePopulator implements DatabasePopulator { List<Resource> scripts = new ArrayList<>(); @Nullable private Charset sqlScriptEncoding; private String separator = ScriptUtils.DEFAULT_STATEMENT_SEPARATOR; private String[] commentPrefixes = ScriptUtils.DEFAULT_COMMENT_PREFIXES; private String blockCommentStartDelimiter = ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER; private String blockCommentEndDelimiter = ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER; private boolean continueOnError = false; private boolean ignoreFailedDrops = false; private DataBufferFactory dataBufferFactory = DefaultDataBufferFactory.sharedInstance; /** * Create a new {@code ResourceDatabasePopulator} with default settings. */ public ResourceDatabasePopulator() { } /** * Create a new {@code ResourceDatabasePopulator} with default settings for the supplied scripts. * @param scripts the scripts to execute to initialize or clean up the database (never {@code null}) */ public ResourceDatabasePopulator(Resource... scripts) { setScripts(scripts); } /** * Construct a new {@code ResourceDatabasePopulator} with the supplied values. * @param continueOnError flag to indicate that all failures in SQL should be * logged but not cause a failure * @param ignoreFailedDrops flag to indicate that a failed SQL {@code DROP} * statement can be ignored * @param sqlScriptEncoding the encoding for the supplied SQL scripts * (may be {@code null} or <em>empty</em> to indicate platform encoding) * @param scripts the scripts to execute to initialize or clean up the database * (never {@code null}) */ public ResourceDatabasePopulator(boolean continueOnError, boolean ignoreFailedDrops, @Nullable String sqlScriptEncoding, Resource... scripts) { this.continueOnError = continueOnError; this.ignoreFailedDrops = ignoreFailedDrops; setSqlScriptEncoding(sqlScriptEncoding); setScripts(scripts); } /** * Add a script to execute to initialize or clean up the database. * @param script the path to an SQL script (never {@code null}) */ public void addScript(Resource script) { Assert.notNull(script, "'script' must not be null"); this.scripts.add(script); } /** * Add multiple scripts to execute to initialize or clean up the database. * @param scripts the scripts to execute (never {@code null}) */ public void addScripts(Resource... scripts) { assertContentsOfScriptArray(scripts); this.scripts.addAll(Arrays.asList(scripts)); } /** * Set the scripts to execute to initialize or clean up the database, * replacing any previously added scripts. * @param scripts the scripts to execute (never {@code null}) */ public void setScripts(Resource... scripts) { assertContentsOfScriptArray(scripts); // Ensure that the list is modifiable this.scripts = new ArrayList<>(Arrays.asList(scripts)); } private void assertContentsOfScriptArray(Resource... scripts) { Assert.notNull(scripts, "'scripts' must not be null"); Assert.noNullElements(scripts, "'scripts' must not contain null elements"); } /** * Specify the encoding for the configured SQL scripts, * if different from the platform encoding. * @param sqlScriptEncoding the encoding used in scripts * (may be {@code null} or empty to indicate platform encoding) * @see #addScript(Resource) */ public void setSqlScriptEncoding(@Nullable String sqlScriptEncoding) { setSqlScriptEncoding(StringUtils.hasText(sqlScriptEncoding) ? Charset.forName(sqlScriptEncoding) : null); } /** * Specify the encoding for the configured SQL scripts, * if different from the platform encoding. * @param sqlScriptEncoding the encoding used in scripts * (may be {@code null} or empty to indicate platform encoding) * @see #addScript(Resource) */ public void setSqlScriptEncoding(@Nullable Charset sqlScriptEncoding) { this.sqlScriptEncoding = sqlScriptEncoding; } /** * Specify the statement separator, if a custom one. * <p>Defaults to {@code ";"} if not specified and falls back to {@code "\n"} * as a last resort; may be set to {@link ScriptUtils#EOF_STATEMENT_SEPARATOR} * to signal that each script contains a single statement without a separator. * @param separator the script statement separator */ public void setSeparator(String separator) { this.separator = separator; } /** * Set the prefix that identifies single-line comments within the SQL scripts. * <p>Defaults to {@code "--"}. * @param commentPrefix the prefix for single-line comments * @see #setCommentPrefixes(String...) */ public void setCommentPrefix(String commentPrefix) { Assert.hasText(commentPrefix, "'commentPrefix' must not be null or empty"); this.commentPrefixes = new String[] { commentPrefix }; } /** * Set the prefixes that identify single-line comments within the SQL scripts. * <p>Defaults to {@code ["--"]}. * @param commentPrefixes the prefixes for single-line comments */ public void setCommentPrefixes(String... commentPrefixes) { Assert.notEmpty(commentPrefixes, "'commentPrefixes' must not be null or empty"); Assert.noNullElements(commentPrefixes, "'commentPrefixes' must not contain null elements"); this.commentPrefixes = commentPrefixes; } /** * Set the start delimiter that identifies block comments within the SQL * scripts. * <p>Defaults to {@code "/*"}. * @param blockCommentStartDelimiter the start delimiter for block comments * (never {@code null} or empty) * @see #setBlockCommentEndDelimiter */ public void setBlockCommentStartDelimiter(String blockCommentStartDelimiter) { Assert.hasText(blockCommentStartDelimiter, "'blockCommentStartDelimiter' must not be null or empty"); this.blockCommentStartDelimiter = blockCommentStartDelimiter; } /** * Set the end delimiter that identifies block comments within the SQL * scripts. * <p>Defaults to <code>"*&#47;"</code>. * @param blockCommentEndDelimiter the end delimiter for block comments * (never {@code null} or empty) * @see #setBlockCommentStartDelimiter */ public void setBlockCommentEndDelimiter(String blockCommentEndDelimiter) { Assert.hasText(blockCommentEndDelimiter, "'blockCommentEndDelimiter' must not be null or empty"); this.blockCommentEndDelimiter = blockCommentEndDelimiter; } /** * Flag to indicate that all failures in SQL should be logged but not cause a failure. * <p>Defaults to {@code false}. * @param continueOnError {@code true} if script execution should continue on error */ public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } /** * Flag to indicate that a failed SQL {@code DROP} statement can be ignored. * <p>This is useful for a non-embedded database whose SQL dialect does not * support an {@code IF EXISTS} clause in a {@code DROP} statement. * <p>The default is {@code false} so that if the populator runs accidentally, it will * fail fast if a script starts with a {@code DROP} statement. * @param ignoreFailedDrops {@code true} if failed drop statements should be ignored */ public void setIgnoreFailedDrops(boolean ignoreFailedDrops) { this.ignoreFailedDrops = ignoreFailedDrops; } /** * Set the {@link DataBufferFactory} to use for {@link Resource} loading. * <p>Defaults to {@link DefaultDataBufferFactory}. * @param dataBufferFactory the {@link DataBufferFactory} to use, must not be {@code null} */ public void setDataBufferFactory(DataBufferFactory dataBufferFactory) { Assert.notNull(dataBufferFactory, "DataBufferFactory must not be null"); this.dataBufferFactory = dataBufferFactory; } @Override public Mono<Void> populate(Connection connection) { Assert.notNull(connection, "Connection must not be null"); return Flux.fromIterable(this.scripts).concatMap(resource -> { EncodedResource encodedScript = new EncodedResource(resource, this.sqlScriptEncoding); return ScriptUtils.executeSqlScript(connection, encodedScript, this.dataBufferFactory, this.continueOnError, this.ignoreFailedDrops, this.commentPrefixes, this.separator, this.blockCommentStartDelimiter, this.blockCommentEndDelimiter); }).then(); } }
package eu.doppel_helix.kerberos.kerberostest2; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class SECPKG_FLAG_Map { private static final Map<Integer, String> SEC_MAP; static { Map<Integer, String> SEC_MAP_BUILDER = new HashMap<>(); for (Field f : SspiX.class.getFields()) { if (f.getName().startsWith("SECPKG_FLAG_")) { try { SEC_MAP_BUILDER.put(f.getInt(null), f.getName()); } catch (IllegalArgumentException | IllegalAccessException ex) { throw new RuntimeException(ex); } } } SEC_MAP = SEC_MAP_BUILDER; } public static List<String> resolve(int code) { List<String> result = new ArrayList<>(); for(Entry<Integer,String> entry: SEC_MAP.entrySet()) { if((code & entry.getKey()) > 0) { result.add(entry.getValue()); } } return result; } }
package com.ass.modelQuery; import javax.persistence.Entity; import javax.persistence.Id; import com.ass.model.Category; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Entity public class CategoryReport { @Id private Category danhMuc; private long soDonHang; private double doanhThu; }
package cl.escalab.nparrado.spring.homework2_2.model; import lombok.Data; import javax.persistence.*; import javax.validation.constraints.NotNull; @Data @Entity @Table(name = "item") public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer idItem; @NotNull @Column(name = "sku", nullable = false, unique = true, length = 12) private String sku; @NotNull @Column(name = "nombre", nullable = false, length = 70) private String nombre; @NotNull @Column(name = "precio", nullable = false) private Integer precio; }
/* * Copyright (c) 2015, Werner Klieber. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA */ package pi; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; import org.hibernate.validator.constraints.NotEmpty; /** * Created by wklieber on 08.03.2015. */ public class HelloWorldConfiguration extends Configuration { @NotEmpty private String template; @NotEmpty private String defaultName = "Stranger"; @JsonProperty public String getTemplate() { return template; } @JsonProperty public void setTemplate(String template) { this.template = template; } @JsonProperty public String getDefaultName() { return defaultName; } @JsonProperty public void setDefaultName(String name) { this.defaultName = name; } }
package com.infoworks.lab.util.services; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import static org.junit.Assert.*; public class iResourceServiceTest { @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void readJson(){ iResourceService manager = iResourceService.create(); String json = manager.readAsString("data/rider-mock-data.json"); System.out.println(json); List<Map<String, Object>> jObj = manager.readAsJsonObject(json); System.out.println(jObj.toString()); } @Test public void imageAsString() throws URISyntaxException, IOException { iResourceService manager = iResourceService.create(); File imfFile = new File("data/final-architecture.png"); InputStream ios = manager.createStream(imfFile); // BufferedImage bufferedImage = manager.readAsImage(ios, BufferedImage.TYPE_INT_RGB); String base64Image = manager.readImageAsBase64(bufferedImage, iResourceService.Format.PNG); System.out.println("Message: " + base64Image); // BufferedImage decryptedImg = manager.readImageFromBase64(base64Image); System.out.println(""); } }
package com.citibank.newcpb.form; import java.io.Serializable; import java.util.ArrayList; import com.citibank.newcpb.bean.ResultTableBean; import com.citibank.newcpb.vo.DocumentsVO; import com.citibank.newcpb.vo.StatusCpfCnpjVO; public class DocumentsForm extends BaseForm implements Serializable { private static final long serialVersionUID = 1L; private String screenTitle; private String filterNumberEM; private String filterCpfCnpj; private String filterName; private String filterTitulo; private String filterArquivo; private String filterMonthYear; private String filterProcPA; private StatusCpfCnpjVO selectedRegister; private ArrayList<DocumentsVO> resultList; private boolean isUpdate; private boolean isApprove; private boolean isOnlyView; private boolean isFromApprove; private String idDiffList; //Combos da tela private ArrayList<ResultTableBean> tituloValues; public ArrayList<DocumentsVO> getResultList() { return resultList; } public void setResultList(ArrayList<DocumentsVO> resultList) { this.resultList = resultList; } public boolean isApprove() { return isApprove; } public void setApprove(boolean isApprove) { this.isApprove = isApprove; } public boolean isOnlyView() { return isOnlyView; } public void setOnlyView(boolean isOnlyView) { this.isOnlyView = isOnlyView; } public String getIdDiffList() { return idDiffList; } public void setIdDiffList(String idDiffList) { this.idDiffList = idDiffList; } public String getFilterNumberEM() { return filterNumberEM; } public void setFilterNumberEM(String filterNumberEM) { this.filterNumberEM = filterNumberEM; } public String getScreenTitle() { return screenTitle; } public void setScreenTitle(String screenTitle) { this.screenTitle = screenTitle; } public boolean isUpdate() { return isUpdate || isOnlyView; } public void setUpdate(boolean isUpdate) { this.isUpdate = isUpdate; } public String getFilterCpfCnpj() { return filterCpfCnpj; } public void setFilterCpfCnpj(String filterCpfCnpj) { this.filterCpfCnpj = filterCpfCnpj; } public String getFilterName() { return filterName; } public void setFilterName(String filterName) { this.filterName = filterName; } public boolean isFromApprove() { return isFromApprove; } public void setFromApprove(boolean isFromApprove) { this.isFromApprove = isFromApprove; } public String getFilterTitulo() { return filterTitulo; } public void setFilterTitulo(String filterTitulo) { this.filterTitulo = filterTitulo; } public String getFilterArquivo() { return filterArquivo; } public void setFilterArquivo(String filterArquivo) { this.filterArquivo = filterArquivo; } public String getFilterProcPA() { return filterProcPA; } public void setFilterProcPA(String filterProcPA) { this.filterProcPA = filterProcPA; } public String getFilterMonthYear() { return filterMonthYear; } public void setFilterMonthYear(String filterMonthYear) { this.filterMonthYear = filterMonthYear; } public ArrayList<ResultTableBean> getTituloValues() { return tituloValues; } public void setTituloValues(ArrayList<ResultTableBean> tituloValues) { this.tituloValues = tituloValues; } public StatusCpfCnpjVO getSelectedRegister() { return selectedRegister; } public void setSelectedRegister(StatusCpfCnpjVO selectedRegister) { this.selectedRegister = selectedRegister; } }
package edu.colostate.cs.cs414.soggyZebras.rollerball.Client.menu.listdisplay; import edu.colostate.cs.cs414.soggyZebras.rollerball.Game.Game; /** * a wrapper class used to display a game in the list of active games */ public class PastGameListDisplay { public Game game; private String myUsername; public PastGameListDisplay(Game game, String myUsername) { this.game = game; this.myUsername = myUsername; } @Override public int hashCode() { return game.getGameID(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PastGameListDisplay that = (PastGameListDisplay) o; return game.getGameID() == that.game.getGameID(); } @Override public String toString() { String otherUser = game.getPlayer1().getUsername().equals(myUsername) ? game.getPlayer2().getUsername() : game.getPlayer1().getUsername(); String winMessage = game.getWinner().getUsername().equals(otherUser) ? "they" : "you"; return winMessage + " won - game against " + otherUser + " - ID: " + game.getGameID(); } }
package main.java.oop.static1; // 더하기만 하는 계산기를 만들어보자. public class Calculator { public Calculator(long x, long y) { this.x = x; this.y = y; } private long x; private long y; public long getTotal() { return this.x + this.y; } }
package com.example.eventalert; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.TimeZone; public class EventAdapter extends RecyclerView.Adapter<EventAdapter.EventViewHolder> { ArrayList<Event> mEventList; LayoutInflater inflater; public EventAdapter(Context context, ArrayList<Event> events) { inflater = LayoutInflater.from(context); this.mEventList = events; } @Override public EventViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = inflater.inflate(R.layout.event_item_card, parent, false); EventViewHolder holder = new EventViewHolder(view); return holder; } @Override public void onBindViewHolder(EventViewHolder holder, int position) { Event selectedEvent = mEventList.get(position); holder.setData(selectedEvent, position); } @Override public int getItemCount() { return mEventList.size(); } class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView eventName, eventDescription, eventTime; CheckBox eventIsDone; ImageView eventImage, deleteevent; public EventViewHolder(View itemView) { super(itemView); eventName = (TextView) itemView.findViewById(R.id.event_name); eventDescription = (TextView) itemView.findViewById(R.id.event_description); eventTime = (TextView) itemView.findViewById(R.id.event_time); eventImage = (ImageView) itemView.findViewById(R.id.event_image); deleteevent = (ImageView) itemView.findViewById(R.id.delete_event); eventIsDone = (CheckBox) itemView.findViewById(R.id.is_done_checkbox); deleteevent.setOnClickListener(this); } public void setData(Event selectedProduct, int position) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); this.eventTime.setText(dateFormat.format(selectedProduct.getTime())); this.eventName.setText(selectedProduct.getName()); this.eventDescription.setText(selectedProduct.getDescription()); this.eventImage.setImageResource(selectedProduct.getImageID()); this.eventIsDone.setSelected(selectedProduct.getDone()); } @Override public void onClick(View v) { } } }