text
stringlengths
10
2.72M
package com.digitfaber.messaging.example.spring; import com.digitfaber.messaging.MessagePublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static com.digitfaber.messaging.example.spring.ExampleSubscriber.EXAMPLE_EXCHANGE_NAME; @Configuration public class ExampleConfiguration { @Bean public MessagePublisher messagePublisher() { return new MessagePublisher(EXAMPLE_EXCHANGE_NAME); } }
package bootcamp.test; import org.testng.ITestListener; import org.testng.ITestResult; public class CustomListener implements ITestListener { @Override public void onTestStart(ITestResult result) { System.out.println("Starting Test: " + result.getMethod().getMethodName()); } }
package com.example.root.myapplication; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.NumberFormat; import java.util.Locale; public class MainActivity extends Activity { private Button button,button3,button4; private EditText edt_input; private TextView textView16; double angka; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edt_input = (EditText) findViewById(R.id.edt_input); button = (Button) findViewById(R.id.button); button3 = (Button) findViewById(R.id.button3); button4 = (Button) findViewById(R.id.button4); textView16 = (TextView) findViewById(R.id.textView16); } public boolean cek(){ if (edt_input.getText().toString().isEmpty()){ Toast.makeText(this, "Silahkan masukan jumlah uang", Toast.LENGTH_SHORT).show(); return false; } return true; } public void toYen(View v){ if (!cek()){ return; } try{ angka = Double.parseDouble(edt_input.getText().toString()); }catch(Exception ex){ Toast.makeText(this, "Masukkan angka", Toast.LENGTH_SHORT).show(); } double hasil = angka / 132; textView16.setText(NumberFormat.getCurrencyInstance(Locale.JAPAN).format(hasil)); Toast.makeText(this, "1 Yen = Rp 132", Toast.LENGTH_SHORT).show(); } public void toEuro(View v){ if (!cek()){ return; } try{ angka = Double.parseDouble(edt_input.getText().toString()); }catch(Exception ex){ Toast.makeText(this, "Masukkan angka", Toast.LENGTH_SHORT).show(); } double hasil = angka / 17228; textView16.setText(NumberFormat.getCurrencyInstance(Locale.GERMANY).format(hasil)); Toast.makeText(this, "1 EURO = Rp 17228", Toast.LENGTH_SHORT).show(); } public void toUSD(View v){ if (!cek()){ return; } try{ angka = Double.parseDouble(edt_input.getText().toString()); }catch(Exception ex){ Toast.makeText(this, "Masukkan angka", Toast.LENGTH_SHORT).show(); } double hasil = angka / 14808; textView16.setText(NumberFormat.getCurrencyInstance(Locale.US).format(hasil)); Toast.makeText(this, "1 U$D = Rp 14808", Toast.LENGTH_SHORT).show(); } }
import javafx.collections.ObservableList; import javafx.scene.control.ListView; import java.io.Serializable; // contains all the data members for the server :- NOTE: METHODS NEED TO BE IMPLEMENTED IN BOTH SERVER AND CLIENT public class MorraInfo implements Serializable { // data members for player 1 private int player1Score; // stores player 1 score private int player1ActualTotal; // stores what the player thinks will be the total sum private int player1ActualGuess; // stores what he has decided to play for the round ObservableList<Integer> player1ObservableList; // for sending player1 list view to player2 if player2 wins ListView<Integer> player1ListView; // for displaying player1 list view // data members for player 2 private int player2Score; // stores player 1 score score private int player2ActualTotal; // stores what the player thinks will be the total sum private int player2ActualGuess; // stores what he has decided to play for the round ObservableList<Integer> player2ObservableList; // for sending player 2 list view to player1 if player1 wins ListView<Integer> player2ListView; // for displaying player2 list view // To keep track of game status private String gameStatus; private int roundOver; private int counter; private int winner; private int roundNumber; // data members for server boolean has2players; // checks to see if both players played before starting the game boolean player1Played; // checks to see if player one played boolean player2Played; // checks to see if player two played boolean player1Won; // checks to see if player 1 won boolean player2Won; // checks to see if player 2 won boolean player1PlayAgain; // checks to see if player one wants to play again after game is over boolean player2PlayAgain; // checks to see if player two wants to play again after game is over // setters for player 1 public void setPlayer1Score(int score) { this.player1Score = score; } public void setPlayer1ActualTotal(int expectedGuess) { this.player1ActualTotal = expectedGuess; } public void setPlayer1ActualGuess(int guess) { this.player1ActualGuess = guess; } // not sure if the GUI stuff are supposed to have setters and getters, probably not // getters for player 1 public int getPlayer1Score() { return this.player1Score; } public int getPlayer1ActualTotal() { return this.player1ActualTotal; } public int getPlayer1ActualGuess() { return this.player1ActualGuess; } // setters for player2 public void setPlayer2Score(int score) { this.player2Score = score; } public void setPlayer2ActualTotal(int expectedGuess) { this.player2ActualTotal = expectedGuess; } public void setPlayer2ActualGuess(int guess) { this.player2ActualGuess = guess; } // getters for player 2 public int getPlayer2Score() { return this.player2Score; } public int getPlayer2ActualTotal() { return this.player2ActualTotal; } public void addMove(int player, int guess) { if(player == 0 && counter == 0) { player1ActualGuess = guess; } else if(player == 1 && counter == 1) { player2ActualGuess = guess; } else if(player == 0 && counter%2 == 0) { player1ActualTotal = guess; } else if(player == 1 && counter%2 != 0) { player2ActualTotal = guess; } counter ++; } // Logic for the server to evaluate who won the round // player 1 public int evaluatePlayers () { if (player1ActualGuess == (player1ActualTotal + player2ActualTotal) && player2ActualGuess == (player1ActualTotal + player2ActualTotal)) {// Both won return 3; } if (player1ActualGuess == (player1ActualTotal + player2ActualTotal)) {// Player 1 won player1Score++; return 1; } if (player2ActualGuess == (player1ActualTotal + player2ActualTotal)) {// Player 2 won player2Score++; return 2; } // if no one won the round return 0; } // to determine if both players have finished playing public boolean roundOver() { this.roundNumber++; if (this.counter == 4) { this.counter = 0; return true; } else { return false; } } // printing the necessary information after each round is done public String printInfo () { int winner = this.winner; String s = new String(); if (winner == 0) { s+= "Server: No one won\n"; } if (winner == 1) { s+= "Server: Client#0 won\n"; } if (winner == 2) { s+= "Server: Client#1 won\n"; } if (winner == 3) { s+= "Server: No one won\n"; } return s; } // Default constructor for MorraInfo class MorraInfo() { // initializing player 1 data members this.player1Score = 0; this.player1ActualTotal = 0; this.player1ActualGuess = 0; // initializing player 2 data members this.player2Score = 0; this.player2ActualTotal = 0; this.player2ActualGuess = 0; // To see if the round is over this.roundOver = 0; this.counter = 0; this.winner = 0; this.roundNumber = 0; } // prints out the score of each client public String scoreString() { return "Client#0: " + this.player1Score + " points, Client#1: " + this.player2Score + " points"; } public int getRoundNumber() { return roundNumber; } public void setRoundNumber(int roundNumber) { this.roundNumber = roundNumber; } }
package Strings; public class DuplicateWordNOSpace { public static void main(String[] args) { String s = "testing xx code testing"; int count = 0; for (int i = 1; i < s.length()-4; i++) { if (s.substring(i - 1, i + 5).equals("testing")) { count++; } } System.out.println(count); } }
package kr.pe.ssun.bark; import com.google.firebase.auth.FirebaseUser; /** * Created by x1210x on 2016. 8. 15.. */ public class MainPresenterImpl implements MainPresenter { private MainView mMainView; private MainModel mMainModel; public MainPresenterImpl(MainView mainView, MainActivity activity) { this.mMainView = mainView; this.mMainModel = new MainModel(this, activity); } @Override public void setHelloText(String text) { mMainView.setHelloText(text); } @Override public void logOut() { mMainModel.logOut(); } @Override public FirebaseUser getCurrentUser() { return mMainView.getCurrentUser(); } @Override public void bark() { mMainModel.bark(); } @Override public void register(String token) { mMainModel.register(token); } @Override public void unregister(String token) { mMainModel.unregister(token); } }
package category.arraysandstring; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; public class DupilcateNumber { public boolean containsNearbyDuplicateII(int[] nums, int k) { Set<Integer> hash = new HashSet<Integer>(); int i=0,j=0; while(j-i<=k && j<nums.length){ if(!hash.contains(nums[j])){ hash.add(nums[j++]); }else{ return true; } } while(j<nums.length){ hash.remove(nums[i++]); if(!hash.contains(nums[j])){ hash.add(nums[j++]); }else{ return true; } } return false; } public boolean containsNearbyAlmostDuplicateIII(int[] nums, int k, int t) { if (nums == null) { return false; } TreeMap<Long, Integer> map = new TreeMap<Long, Integer>();//pair: value-index for (int i = 0; i < nums.length; i++) { if (i > k) { map.remove((long)nums[i-k-1]); } long val = (long)nums[i]; Long greater = map.ceilingKey(val); if (greater != null && greater - val <= t) { return true; } Long smaller = map.lowerKey(val); if (smaller != null && val - smaller <= t) { return true; } map.put(val, i); } return false; } }
package com.example.accounting_app.fragment; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.example.accounting_app.R; import com.example.accounting_app.listener.listener_fragment_wish; import com.yatoooon.screenadaptation.ScreenAdapterTools; /** * @Creator cetwag, yuebanquan * @Version V2.0.0 * @Time 2019.6.27 * @Description 心愿模块碎片类 */ public class fragment_wish extends Fragment { public Button btn_save_money; public Button btn_wish_list; listener_fragment_wish listener; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //inflater使将xml布局文件转换为视图的一个类,container表示在container里面显示这个视图 View view = inflater.inflate(R.layout.fragment_wish, container, false); //屏幕适配 ScreenAdapterTools.getInstance().loadView(view); return view; } /** * @parameter * @description 根据fragment的生命周期,onActivityCreated在onCreateView后执行 * @Time 2019/6/28 14:40 */ @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); init(); listener.listener_fw();//该类的监听调用 } /** * @parameter * @description view控件初始化 * @Time 2019/6/28 14:12 */ void init() { btn_save_money = getView().findViewById(R.id.btn_save_money); btn_wish_list = getView().findViewById(R.id.btn_wish_list); listener = new listener_fragment_wish(this);//该类的监听 } }
package com.geekparkhub.hadoop.order; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; /** * Geek International Park | 极客国际公园 * GeekParkHub | 极客实验室 * Website | https://www.geekparkhub.com/ * Description | Open开放 · Creation创想 | OpenSource开放成就梦想 GeekParkHub共建前所未见 * HackerParkHub | 黑客公园枢纽 * Website | https://www.hackerparkhub.com/ * Description | 以无所畏惧的探索精神 开创未知技术与对技术的崇拜 * GeekDeveloper : JEEP-711 * * @author system * <p> * OrderSortMapper * <p> */ public class OrderSortMapper extends Mapper<LongWritable, Text, OrderBean, NullWritable> { /** * Instantiated object * 实例化对象 */ OrderBean k = new OrderBean(); /** * Rewrite the map() method * 重写map()方法 * * @param key * @param value * @param context * @throws IOException * @throws InterruptedException */ @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { /** * Get a row of data * 获取一行数据 */ String line = value.toString(); /** * Cutting data * 切割数据 */ String[] fields = line.split(" "); /** * Package object * 封装对象 */ k.setOrder_id(Integer.parseInt(fields[0])); k.setOrder_money(Double.parseDouble(fields[2])); /** * Write data * 写出数据 */ context.write(k, NullWritable.get()); } }
package com.nogago.android.maps.activities; import com.bidforfix.andorid.BidForFixActivity; import com.bidforfix.andorid.BidForFixHelper; import com.nogago.android.maps.plus.OsmandApplication; public class OsmandBidForFixActivity extends BidForFixActivity { @Override public BidForFixHelper getBidForFixHelper() { return ((OsmandApplication) getApplication()).getBidForFix(); } }
package com.example.retail.users; import com.example.retail.util.CreateResponse; import com.example.retail.util.JwtUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.crypto.bcrypt.BCrypt; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value = "/api/v1/passwordManager") public class UsersPasswordManager { @Autowired CreateResponse createResponse; @Autowired JwtUtil jwtUtil; @Autowired UsersService usersService; @PostMapping(value = "/updatePassword") public ResponseEntity<?> updatePassword(@RequestBody String newPassword, HttpServletRequest httpServletRequest) { try { final String authorizationHeader = httpServletRequest.getHeader("Authorization"); final String jwt = authorizationHeader.substring(7); String requesterUserName = jwtUtil.extractUsername(jwt); BCrypt.hashpw(newPassword, BCrypt.gensalt()); Integer res = usersService.updatePassword(BCrypt.hashpw(newPassword, BCrypt.gensalt()), requesterUserName); if(res.equals(1)) { List<Object> finalRes = new ArrayList<>(); finalRes.add("/api/v1/users/authenticate"); return ResponseEntity.status(201).body( createResponse.createSuccessResponse(201, "Password update success", finalRes) ); } else { return ResponseEntity.status(500).body( createResponse.createErrorResponse(500, "Unable to update password", "Process exited with code : " + res) ); } } catch (Exception e) { return ResponseEntity.status(500).body( createResponse.createErrorResponse(500, e.getMessage(), "NA") ); } } @PostMapping(value = "/forgotPassword") public ResponseEntity<?> forgotPassword(@RequestBody String userName) { // Send email with newly generated password return null; } }
package com.shangcai.dao.common.impl; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; import com.shangcai.dao.BaseDao; import com.shangcai.dao.common.ICategoryDao; import com.shangcai.entity.common.Category; import com.shangcai.entity.common.Category.T; import com.shangcai.entity.common.Category.Type; import com.shangcai.view.common.CategoryView; import irille.pub.Log; @Repository public class CategoryDao extends BaseDao<Category> implements ICategoryDao { public static final Log LOG = new Log(CategoryDao.class); /** * 查询所有分类 */ @Override public List<Category> list() { return selectFrom(Category.class).orderBy(T.SORT.asc()).queryList(); } /** * 查询分类列表 * @return */ @Override public List<CategoryView> allList(Byte type) { List<CategoryView> viewList = new ArrayList<CategoryView>(); List<Category> firstStageList=new ArrayList<Category>(); if(type.intValue()==2) firstStageList = selectFrom(Category.class).where(Category.T.UP.isNull(), Category.T.TYPE.eq(Category.Type.designer)).orderBy(T.SORT.asc()).queryList(); else firstStageList = selectFrom(Category.class).where(Category.T.UP.isNull(), Category.T.TYPE.eq(Category.Type.company)).orderBy(T.SORT.asc()).queryList(); for (Category category : firstStageList) { CategoryView view = new CategoryView(); view.setPkey(category.getPkey()); view.setName(category.getName()); view.setSort(category.getSort()); List<CategoryView> secondViewList = new ArrayList<CategoryView>(); List<Category> secondList = selectFrom(Category.class).where(Category.T.UP.eq(category.getPkey())).queryList(); for (Category second : secondList) { CategoryView sendcondview = new CategoryView(); sendcondview.setParent(category.getPkey()); sendcondview.setPkey(second.getPkey()); sendcondview.setName(second.getName()); sendcondview.setSort(second.getSort()); secondViewList.add(sendcondview); } view.setSubs(secondViewList); viewList.add(view); } return viewList; } @Override public Category get(Integer categoryId) { return selectFrom(Category.class, categoryId); } @Override public List<Category> list(Type type, boolean isTop) { return selectFrom(Category.class).where(type != null, T.TYPE.eq(type)).where(isTop, T.UP.isNull()).orderBy(T.SORT.asc()).queryList(); } @Override public Integer countByUp(Integer categoryId) { return selectFrom(Category.class).where(T.UP.eq(categoryId)).queryCount(); } }
package com.test07; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MTest { public static void main(String[] args) { ApplicationContext factory = new ClassPathXmlApplicationContext("com/test07/applicationContext.xml"); TV lz = (TV)factory.getBean("lz"); lz.powerOn(); lz.volumeUp(); lz.volumeDown(); lz.powerOff(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pack1; /** * * @author gaurav.sharma */ public class DemoString { public static void main(String[] args) { String str1 = "hello"; String str2 = "hello"; if (str1 == str2) { System.out.println("yes"); } else { System.out.println("No"); } String str3 = new String("Hello"); String str4 = new String("hEllO"); if (str3.equalsIgnoreCase(str4)) { System.out.println("yes"); } else { System.out.println("No"); } if (str1.equals(str3)) { System.out.println("yes"); } else { System.out.println("No"); } System.out.println(str1.length()); String str11 = "hElLosdgsdfgdfSDFGSDF"; String str20 = str11.toUpperCase(); System.out.println(str11); System.out.println(str20); String str14 = " hello "; System.out.println(str14.trim()); String str15 = "java"; char ch = str15.charAt(3); System.out.println(ch); } }
package main.by.intexsoft.cassandraJpa.service; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import main.by.intexsoft.cassandraJpa.model.User; import main.by.intexsoft.cassandraJpa.repository.UserRepository; @Service public class CassandraService { @Autowired private UserRepository repository; /** * Returns all instances of the type User. * * @return List<User> */ public List<User> findAll() { return (List<User>) repository.findAll(); } /** * Saves a given entity into Cassandra database * * @param entity */ public void addUser(User entity) { repository.save(entity); } /** * Deletes a given entity from Cassandra database * * @param entity */ public void deleteUser(User entity) { repository.delete(entity); } /** * Deletes all entities managed by the Cassandra database */ public void deleteAll() { repository.deleteAll(); } /** * This method returns users where column first_name = first_name * * @param first_name * - users first name * @return List<User> */ public List<User> findByFirstname(String first_name) { return repository.findByFirstname(first_name); } /** * This method returns users where column last_name = last_name. Warning: this * column in database must have index * * @param last_name * - users last name * @return List<User> */ public List<User> findByLastname(String last_name) { return repository.findByLastname(last_name); } /** * This method return set objects from cassandra database. * * @return Set<User> */ public Set<User> getSetFromCassandra() { Set<User> cassandraSet = new HashSet<>(); cassandraSet.addAll(findAll()); return cassandraSet; } }
package app0510.event; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; //JVM이 keyevent객체를 생성하면, 아래의 리스너에게 이벤트 객체를 전달하므로, //개발자는 키보드와 관련된 원하는 작업을 아래의 클래스에서 완성지으면 된다 //아래의 keycontrol 클래스는 keylistener의 자식이므로, 키와 관련된 모든 이벤트를 청취할수있다 public class keyControl implements KeyListener{ @Override public void keyTyped(KeyEvent e) { System.out.println("keyTyped 호출"); } @Override public void keyPressed(KeyEvent e) { System.out.println("keyPressed 호출"); } @Override public void keyReleased(KeyEvent e) { System.out.println("keyReleased 호출"); } }
package com.fang.example.spring.di; /** * Created by andy on 4/3/16. */ public class RecuseDamselQuest implements Quest { public void embark() { System.out.println("recuse me"); } }
package input; import calculation.otherExpressions.Value; import org.junit.*; import calculation.*; import calculation.calculations.*; public class QueueabilityTest { static Typical typVal = NodeType.VALUE, typ2 = NodeType.EXPONENT; static Nodeable nod1, nod2, nod3; static Queuer que1; //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ @Before public void initial() { nod1 = new Value(typVal); nod2 = new Calculation_Exponentiation(typ2); nod3 = new Value(typVal); que1 = new Queuer(nod1); } @After public void terminal() { nod1 = nod2 = nod3 = null; que1 = null; } @Test public void initial_test() { Assert.assertTrue(nod1 instanceof Value); Assert.assertTrue(nod2 instanceof Calculation_Exponentiation); Assert.assertTrue(nod3 instanceof Value); } //\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\ @Test public void Queuer_head() { Assert.assertNull(que1.getHead()); } @Test public void Queuer_Tail() { Assert.assertNull(que1.getTail()); } }
package com.example.chinenzl.wintec_cbite; import android.content.Intent; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; public class Student_homePage extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_student_home_page); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.teacher: Intent i = new Intent(this, Teacher_Login.class); startActivity(i); return true; case R.id.aboutUs : Intent x = new Intent(this, AboutUs.class); startActivity(x); return true; case R.id.Disclaimer: Intent z = new Intent(this, Disclaimer.class); startActivity(z); return true; default: return super.onOptionsItemSelected(item); } } public void clickNetwork(View view){ Intent i = new Intent(this, Teacher_programmeDetail.class); startActivity(i); } public void clickSoftware(View view){ Intent i = new Intent(this, Teacher_programmeDetail.class); startActivity(i); } public void clickDatabase(View view){ Intent i = new Intent(this, Teacher_programmeDetail.class); startActivity(i); } public void clickWeb(View view){ Intent i = new Intent(this, Teacher_programmeDetail.class); startActivity(i); } }
package com.phplogin.sidag.myapplication; import android.app.Activity; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.database.DatabaseUtils; import android.os.Bundle; import android.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import com.phplogin.sidag.data.ItemProvider; import com.phplogin.sidag.data.ListDatabaseHelper; /** * A fragment representing a list of Items. * <p/> * Large screen devices (such as tablets) are supported by replacing the ListView * with a GridView. * <p/> * Activities containing this fragment MUST implement the {@link OnFragmentInteractionListener} * interface. */ public class FragmentList extends Fragment implements AbsListView.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_LIST_ID = "listid"; private static final String ARG_LIST_NAME = "listname"; // TODO: Rename and change types of parameters private String mheaderText; private OnFragmentInteractionListener mListener; /** * The fragment's ListView/GridView. */ private ListView mListView; private TextView headerText; private String list_uid; /** * The Adapter which will be used to populate the ListView/GridView with * Views. */ private CursorAdapter cAdapter; // TODO: Rename and change types of parameters public static FragmentList newInstance(String list_uid, String list_name) { FragmentList fragment = new FragmentList(); Bundle args = new Bundle(); args.putSerializable(ARG_LIST_ID, list_uid); args.putSerializable(ARG_LIST_NAME, list_name); fragment.setArguments(args); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public FragmentList() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { list_uid = getArguments().getString(ARG_LIST_ID); mheaderText = getArguments().getString(ARG_LIST_NAME); } // TODO: Change Adapter to display your content //mAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, mlist); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_item, container, false); mListView = (ListView) view.findViewById(android.R.id.list); mListView.setItemsCanFocus(true); //Set where to get the data from and where to put it String[] uiBindFrom = {ListDatabaseHelper.LIST_ITEM }; int[] uiBindTo = { R.id.ItemCaption }; //Create an empty Cursor Adapter to hold the cursor from the Database cAdapter = new SimpleCursorAdapter(getActivity() .getApplicationContext(), R.layout.item, null, uiBindFrom, uiBindTo); //Start the Cursor Loader getLoaderManager().initLoader(0, null, this); //Set the Header to the List's name headerText = (TextView) view.findViewById(R.id.header); headerText.setText(mheaderText); //Set the adapter for the ListView mListView.setAdapter(cAdapter); // Set OnItemClickListener so we can be notified on item clicks mListView.setOnItemClickListener(this); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (null != mListener) { // Notify the active callbacks interface (the activity, if the // fragment is attached to one) that an item has been selected. } } /** * The default content for this Fragment has a TextView that is shown when * the list is empty. If you would like to change the text, call this method * to supply the text it should use. */ public void setEmptyText(CharSequence emptyText) { View emptyView = mListView.getEmptyView(); if (emptyView instanceof TextView) { ((TextView) emptyView).setText(emptyText); } } //Query the database for items for the given list UID @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String[] projection = { "" + ListDatabaseHelper.LIST_ITEM_ID + " as _id", ListDatabaseHelper.LIST_ITEM}; String selection = ListDatabaseHelper.LIST_UID + "= ?"; String[] selectionArgs = {list_uid}; CursorLoader cursor = new CursorLoader(getActivity(), ItemProvider.CONTENT_URI_ITEMS, projection , selection, selectionArgs, null); return cursor; } //Swap the cursor in the cursor adapter @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { //Log.d("cursor", DatabaseUtils.dumpCursorToString(data)); cAdapter.changeCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(String id); } }
package example.payrollNoOptional; import example.money.Money; import java.time.LocalDate; import static java.util.Arrays.asList; import java.util.List; import java.util.UUID; @SuppressWarnings("ALL") public class Main { private Employer subsidiary; private LocalDate date; private PersonRepository personRepository; public static void main(String... arguments) { new Main().run(); } private void run() { personRepository = new PersonRepository() { public Person findByUuid(UUID uuid) { return null; } }; subsidiary = new Employer(); date = LocalDate.now(); List<UUID> personUuidList = asList(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); getTotalAnnualPayroll(personUuidList, subsidiary, date); } private void getTotalAnnualPayroll(List<UUID> personUuidList, Employer employer, LocalDate date) { personUuidList.stream() .map(personUuid -> getAnnualSalary(personUuid, employer, date)) .reduce(Money::plus); } private Money getAnnualSalary(UUID personUuid, Employer employer, LocalDate date) { Person person = personRepository.findByUuid(personUuid); if (person != null) { Employment employment = person.getEmployment(employer, date); if (employment != null) { return employment.getAnnualSalary(); } else { return Money.ZERO; } } else { return Money.ZERO; } } }
package com.tencent.mm.ak.a.b; import com.tencent.mm.ak.a.a.c; import com.tencent.mm.ak.a.c.f; import com.tencent.mm.ak.a.g.b; import com.tencent.mm.modelsfs.SFSContext; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.vfs.d; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public final class a implements com.tencent.mm.ak.a.c.a { private f dYd; private String a(String str, c cVar) { String str2 = cVar.dXA; if (str2 == null || str2.length() == 0) { str2 = cVar.dXB; if (!(str2 == null || str2.length() == 0)) { str2 = str2 + "/" + this.dYd.mc(str); } } if (cVar.dXx && bi.oW(r0)) { str2 = b.Pw() + "/" + this.dYd.mc(str); } if (str2 == null || str2.length() == 0) { return null; } return str2; } private String b(String str, c cVar) { String str2 = cVar.dXC; if (str2 == null || str2.length() == 0) { String str3 = cVar.dXA; if (str3 != null && str3.length() > 0) { str2 = cVar.dXB; if (str2 == null || str2.length() == 0 || !str3.startsWith(str2)) { x.e("MicroMsg.imageloader.DefaultImageDiskCache", "[johnw] SFS can't deal with absolute path: %s", new Object[]{str3}); throw new IllegalArgumentException("SFS can't deal with absolute path: " + str3); } str2 = str3.substring(str2.length()); if (str2.startsWith("/")) { str2 = str2.substring(1); } } } if (str2 == null || str2.length() == 0) { str2 = this.dYd.mc(str); } if (str2 == null || str2.length() == 0) { return null; } return str2; } public final boolean a(String str, byte[] bArr, c cVar) { SFSContext sFSContext = cVar.dXU; if (sFSContext != null) { String b = b(str, cVar); if (b == null) { return false; } OutputStream outputStream = null; try { if (sFSContext.mNativePtr == 0) { throw new IllegalArgumentException("Reuse already released SFSContext."); } String str2 = ""; if (com.tencent.mm.modelsfs.f.mP(b)) { str2 = com.tencent.mm.modelsfs.f.mS(b); b = com.tencent.mm.modelsfs.f.mQ(b); } outputStream = sFSContext.aw(b, str2); outputStream.write(bArr); try { outputStream.close(); } catch (IOException e) { } } catch (IOException e2) { if (outputStream == null) { return false; } try { outputStream.close(); return false; } catch (IOException e3) { return false; } } catch (Throwable th) { if (outputStream != null) { try { outputStream.close(); } catch (IOException e4) { } } } } else { String a = a(str, cVar); if (a == null) { return false; } com.tencent.mm.vfs.b cBW = new com.tencent.mm.vfs.b(a).cBW(); if (!(cBW == null || cBW.exists())) { cBW.mkdirs(); } cBW = new com.tencent.mm.vfs.b(a); if (!cBW.exists()) { try { cBW.createNewFile(); } catch (Throwable e5) { x.i("MicroMsg.imageloader.DefaultImageDiskCache", bi.i(e5)); } } if (bArr != null && d.b(a, bArr, bArr.length) < 0) { return false; } } return true; } public final boolean c(String str, c cVar) { SFSContext sFSContext = cVar.dXU; if (sFSContext != null) { String b = b(str, cVar); if (b == null) { return false; } return sFSContext.jy(b); } String a = a(str, cVar); if (a != null) { return new com.tencent.mm.vfs.b(a).delete(); } return false; } public final void Pu() { b.Py(); } public final InputStream d(String str, c cVar) { try { SFSContext sFSContext = cVar.dXU; String b; if (sFSContext != null) { b = b(str, cVar); if (b == null) { return null; } return sFSContext.openRead(b); } b = a(str, cVar); if (b != null) { return new com.tencent.mm.vfs.c(b); } return null; } catch (FileNotFoundException e) { return null; } } public final void a(f fVar) { this.dYd = fVar; } }
package Hub; import java.awt.Rectangle; import processing.core.PApplet; /** * small opening for player to travel between rooms * @author Emily * */ public class Door extends Rectangle { private Room adjacentRoom; private int direction; private String tag; private boolean showTag, visible; /** * * @param direction which face of a room the door is on (N, S, E, W) * @param adj adjacent room that door connects to * @param bounds rectangle boundaries of door * @param tag text that appears once player gets near door */ public Door(int direction, Room adj, Rectangle bounds, String tag) { this.setBounds(bounds); this.direction = direction; adjacentRoom = adj; this.tag = tag; showTag = false; visible = false; } /** * draws a black rectangle that represents door * @param drawer interface that draws door */ public void display(PApplet drawer) { visible = true; drawer.pushStyle(); drawer.noStroke(); drawer.fill(0); drawer.rect(x, y, width, height); if(showTag) { drawer.fill(0); drawer.textSize(10); drawer.textAlign(drawer.CENTER, drawer.TOP); drawer.text(tag, x+width/2, y+height+5); } drawer.popStyle(); } /** * * @return return access to the adjacent room this door leads to */ public Room exitTo() { return adjacentRoom; } /** * detects if player is within boundaries of door * @param player player that enters door * @return true if player intersects with door bounds; false otherwise */ public boolean hasEntered(Sprite player) { if(visible && this.intersects(player)) { showTag = true; return true; } else { showTag = false; return false; } } /** * * @return which face of the room door is on (N,S,E,W) */ public int getDirection() { return direction; } /** * stops door from displaying on window */ public void invisible() { visible = false; } }
/** * Date: 2018年10月23日 20:31 <br/> * * @author lcc * @see * @since */ package com.example.spring.integration;
package de.zarncke.lib.io; import java.io.IOException; import java.io.InputStream; import org.joda.time.DateTime; import de.zarncke.lib.err.Warden; import de.zarncke.lib.time.Clock; import de.zarncke.lib.time.JavaClock; /** * This stream wraps another stream and tracks the time since creation and throws TimeoutException when a specified timeout * occurs before the stream is closed. * Note: Time is checked relative to the {@link Clock}. * * @author Gunnar Zarncke */ public class TimeoutInputStream extends InputStream { public static class TimeoutException extends IOException { private static final long serialVersionUID = 1L; public TimeoutException(final String msg) { super(msg); } } private final InputStream decorated; private final long timeoutTimeMs; /** * @param decorated to delegate to * @param timeoutTimeMs the absolute time in ms after which timeout exceptions occur */ public TimeoutInputStream(final InputStream decorated, final long timeoutTimeMs) { this.decorated = decorated; this.timeoutTimeMs = timeoutTimeMs; } @Override public int read() throws IOException { int b = this.decorated.read(); checkTimeout(); return b; } @Override public int hashCode() { return this.decorated.hashCode(); } @Override public int read(final byte[] b) throws IOException { int r = this.decorated.read(b); checkTimeout(); return r; } @Override public boolean equals(final Object obj) { return this.decorated.equals(obj); } @Override public int read(final byte[] b, final int off, final int len) throws IOException { int r = this.decorated.read(b, off, len); checkTimeout(); return r; } @Override public long skip(final long n) throws IOException { long r = this.decorated.skip(n); checkTimeout(); return r; } private void checkTimeout() throws IOException { long now = JavaClock.getTheClock().getCurrentTimeMillis(); if (now > this.timeoutTimeMs) { throw Warden.spot(new TimeoutException("timeout at " + new DateTime(now) + " > " + new DateTime(this.timeoutTimeMs) + " for " + this.decorated)); } } @Override public String toString() { return this.decorated.toString(); } @Override public int available() throws IOException { checkTimeout(); return this.decorated.available(); } @Override public void close() throws IOException { this.decorated.close(); } @Override public synchronized void mark(final int readlimit) { this.decorated.mark(readlimit); } @Override public synchronized void reset() throws IOException { this.decorated.reset(); } @Override public boolean markSupported() { return this.decorated.markSupported(); } }
package com.mod.authservice.security.jwt; import com.mod.authservice.security.services.UserDetailsImpl; import com.mod.authservice.security.services.UserDetailsServiceImpl; import com.mod.authservice.service.AuthService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; @Component public class JwtReqFilter extends OncePerRequestFilter { private final JwtTokenUtil jwtTokenUtil; private final UserDetailsServiceImpl userDetailsService; @Autowired private AuthService authService; @Autowired public JwtReqFilter(JwtTokenUtil jwtTokenUtil, UserDetailsServiceImpl userDetailsService) { this.jwtTokenUtil = jwtTokenUtil; this.userDetailsService = userDetailsService; } @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { final String authorization = httpServletRequest.getHeader("Authorization"); Cookie[] cookies = httpServletRequest.getCookies(); String cookieJWT = null; if (cookies != null) { cookieJWT = Arrays.stream(cookies) .map(Cookie::getValue).findFirst().orElse(null); } String username = null; String jwt = null; if (authorization != null && authorization.startsWith("Bearer ")) { jwt = authorization.substring(7); username = jwtTokenUtil.getUsernameFromToken(jwt); } else if (cookieJWT != null) { username = jwtTokenUtil.getUsernameFromToken(cookieJWT); } if(!(authService.handleRequest(username,httpServletRequest.getRequestURL().toString(),jwt))) { httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized..."); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetailsImpl userDetails = (UserDetailsImpl) userDetailsService.loadUserByUsername(username); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities() ); usernamePasswordAuthenticationToken .setDetails( new WebAuthenticationDetailsSource().buildDetails(httpServletRequest) ); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } filterChain.doFilter(httpServletRequest, httpServletResponse); } }
package com.testing.class10_HomeWork; public class bicycle implements lunTai { @Override public void ganghua() { System.out.println("自行车 轮胎需要有钢材料"); } @Override public void suliao() { System.out.println("自行车 轮胎需要有塑料用品"); } }
package org.crama.burrhamilton.repository; import javax.transaction.Transactional; import org.crama.burrhamilton.model.Question; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository("questionRepository") public interface QuestionRepository extends JpaRepository<Question, Long> { @Modifying @Transactional @Query("delete from Question q where q.id = ?") void deleteQuestion(Long id); }
package analysis.experiments; import analysis.utils.AnalysisUtils; import analysis.utils.CsvWriter; import datastructures.interfaces.IList; public class Experiment3 { public static final int NUM_TRIALS = 5; public static final int NUM_TIMES_TO_REPEAT = 1000; public static final long MAX_LIST_SIZE = 20000; public static final long STEP = 100; public static void main(String[] args) { IList<Long> indices = AnalysisUtils.makeDoubleLinkedList(0L, MAX_LIST_SIZE, STEP); System.out.println("Starting experiment 3"); IList<Long> testResults = AnalysisUtils.runTrials(indices, Experiment3::test, NUM_TRIALS); System.out.println("Saving results to file"); CsvWriter writer = new CsvWriter(); writer.addColumn("InputIndices", indices); writer.addColumn("TestResults", testResults); writer.writeToFile("experimentdata/experiment3.csv"); System.out.println("All done!"); } /** * We will call test on all indices in the indices IList constructed above. * So indices will have values 0 to MAX_LIST_SIZE, in increments of 100. * Your prediction should estimate what the overall trends of the plot will look like, * and address what indices (when passed to the get method) you would expect to be faster or slower. * * @param index The index of the DoubleLinkedList that we want to get. This will the the x-axis of your plot. * @return the amount of time it takes to return the element of a DoubleLinkedList at * the index specified in the parameter, in milliseconds. */ public static long test(long index) { // We don't include the cost of constructing the list when running this test IList<Long> list = AnalysisUtils.makeDoubleLinkedList(0L, MAX_LIST_SIZE, 1L); long start = System.currentTimeMillis(); // We try getting the same thing multiple times mainly because a single get, by itself, // is too fast to reliably measure. By testing the same amount of .get()s for each // index, we come up with a kind of "average" runtime of .get() for that index. long temp = 0L; for (int i = 0; i < NUM_TIMES_TO_REPEAT; i++) { temp += list.get((int) index); } // Returns time elapsed. This will end up being the real-world amount of time // it took to get that index of the DoubleLinkedList return System.currentTimeMillis() - start; } }
package com.youthchina.domain.Qinghong; import com.youthchina.dto.applicant.SkillsRequestDTO; import java.sql.Timestamp; public class AdvantageLabel { private Integer label_id; private String label_code; private Integer stu_id; private Integer is_delete; private Timestamp is_delete_time; private LabelInfo labelInfo; public AdvantageLabel() { } public AdvantageLabel(SkillsRequestDTO skillsRequestDTO) { this.label_code = skillsRequestDTO.getLabel_code(); } public Integer getLabel_id() { return label_id; } public void setLabel_id(Integer label_id) { this.label_id = label_id; } public String getLabel_code() { return label_code; } public void setLabel_code(String label_code) { this.label_code = label_code; } public Integer getStu_id() { return stu_id; } public void setStu_id(Integer stu_id) { this.stu_id = stu_id; } public Integer getIs_delete() { return is_delete; } public void setIs_delete(Integer is_delete) { this.is_delete = is_delete; } public Timestamp getIs_delete_time() { return is_delete_time; } public void setIs_delete_time(Timestamp is_delete_time) { this.is_delete_time = is_delete_time; } public LabelInfo getLabelInfo() { return labelInfo; } public void setLabelInfo(LabelInfo labelInfo) { this.labelInfo = labelInfo; } }
package model; import controller.Controller; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.stage.Stage; public class NovaPorukaBtnEvent implements EventHandler<javafx.event.ActionEvent> { private Scene scene3; private Stage primaryStage; public NovaPorukaBtnEvent() { } @Override public void handle(ActionEvent arg0) { Controller.getInstance().getScenaTreca().setKorisnik(Controller.getInstance().getKorisnik()); scene3 = Controller.getInstance().getSceneThree(); primaryStage = Controller.getInstance().getPrimaryStage(); primaryStage.setScene(scene3); primaryStage.show(); } }
package de.fhb.ott.pagetox.util; import de.fhb.ott.pagetoxjava.service.PhantomService; import org.openqa.selenium.server.RemoteControlConfiguration; import org.openqa.selenium.server.SeleniumServer; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.io.IOException; /** * @author Christoph Ott */ @WebListener public class StartupListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent contextEvent) { try { PropertyLoader.loadPropertyToSystemProp("properties"); } catch (IOException e) { e.printStackTrace(); } PhantomService.getInstance(); } @Override public void contextDestroyed(ServletContextEvent contextEvent) { PhantomService.getInstance().quitDriversAndServices(); } }
package org.opentosca.planbuilder.prephase.plugin.scriptiaonlinux.handler; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.opentosca.planbuilder.model.tosca.AbstractArtifactReference; import org.opentosca.planbuilder.model.tosca.AbstractDeploymentArtifact; import org.opentosca.planbuilder.model.tosca.AbstractImplementationArtifact; import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate; import org.opentosca.planbuilder.plugins.commons.Properties; import org.opentosca.planbuilder.plugins.context.TemplatePlanContext; import org.opentosca.planbuilder.plugins.context.TemplatePlanContext.Variable; import org.opentosca.planbuilder.provphase.plugin.invoker.Plugin; import org.opentosca.planbuilder.utils.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * This class contains logic to upload files to a linux machine. Those files * must be available trough a openTOSCA Container * </p> * Copyright 2013 IAAS University of Stuttgart <br> * <br> * * @author Kalman Kepes - kepeskn@studi.informatik.uni-stuttgart.de * */ public class Handler { private final static Logger LOG = LoggerFactory.getLogger(Handler.class); private Plugin invokerPlugin = new Plugin(); private ResourceHandler res; /** * Constructor */ public Handler() { try { this.res = new ResourceHandler(); } catch (ParserConfigurationException e) { Handler.LOG.error("Couldn't initialize internal ResourceHandler", e); } } /** * Adds necessary BPEL logic trough the given context that can upload the * given DA unto the given InfrastructureNode * * @param context a TemplateContext * @param da the DeploymentArtifact to deploy * @param nodeTemplate the NodeTemplate which is used as InfrastructureNode * @return true iff adding logic was successful */ public boolean handle(TemplatePlanContext context, AbstractDeploymentArtifact da, AbstractNodeTemplate nodeTemplate) { List<AbstractArtifactReference> refs = da.getArtifactRef().getArtifactReferences(); return this.handle(context, refs, da.getName(), nodeTemplate); } /** * Adds necessary BPEL logic through the given context that can upload the * given IA unto the given InfrastructureNode * * @param context a TemplateContext * @param ia the ImplementationArtifact to deploy * @param nodeTemplate the NodeTemplate which is used as InfrastructureNode * @return true iff adding logic was successful */ public boolean handle(TemplatePlanContext context, AbstractImplementationArtifact ia, AbstractNodeTemplate nodeTemplate) { // fetch references List<AbstractArtifactReference> refs = ia.getArtifactRef().getArtifactReferences(); return this.handle(context, refs, ia.getArtifactType().getLocalPart() + "_" + ia.getOperationName() + "_IA", nodeTemplate); } /** * Adds necessary BPEL logic through the given Context, to deploy the given * ArtifactReferences unto the specified InfrastructureNode * * @param context a TemplateContext * @param refs the ArtifactReferences to deploy * @param artifactName the name of the artifact, where the references * originate from * @param nodeTemplate a NodeTemplate which is a InfrastructureNode to * deploy the AbstractReferences on * @return true iff adding the logic was successful */ private boolean handle(TemplatePlanContext templateContext, List<AbstractArtifactReference> refs, String artifactName, AbstractNodeTemplate nodeTemplate) { // fetch server ip of the vm this apache http php module will be // installed on Variable serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP); if (serverIpPropWrapper == null) { serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP, true); if (serverIpPropWrapper == null) { serverIpPropWrapper = templateContext.getPropertyVariable(Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_SERVERIP, false); } } if (serverIpPropWrapper == null) { Handler.LOG.warn("No Infrastructure Node available with ServerIp property"); return false; } // find sshUser and sshKey Variable sshUserVariable = templateContext.getPropertyVariable("SSHUser"); if (sshUserVariable == null) { sshUserVariable = templateContext.getPropertyVariable("SSHUser", true); if (sshUserVariable == null) { sshUserVariable = templateContext.getPropertyVariable("SSHUser", false); } } // if the variable is null now -> the property isn't set properly if (sshUserVariable == null) { return false; } else { if (Utils.isVariableValueEmpty(sshUserVariable, templateContext)) { // the property isn't set in the topology template -> we set it // null here so it will be handled as an external parameter sshUserVariable = null; } } Variable sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey"); if (sshKeyVariable == null) { sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey", true); if (sshKeyVariable == null) { sshKeyVariable = templateContext.getPropertyVariable("SSHPrivateKey", false); } } // if variable null now -> the property isn't set according to schema if (sshKeyVariable == null) { return false; } else { if (Utils.isVariableValueEmpty(sshKeyVariable, templateContext)) { // see sshUserVariable.. sshKeyVariable = null; } } // add sshUser and sshKey to the input message of the build plan, if // needed if (sshUserVariable == null) { LOG.debug("Adding sshUser field to plan input"); templateContext.addStringValueToPlanRequest("sshUser"); } if (sshKeyVariable == null) { LOG.debug("Adding sshKey field to plan input"); templateContext.addStringValueToPlanRequest("sshKey"); } // find the ubuntu node and its nodeTemplateId String templateId = nodeTemplate.getId(); if (templateId.equals("")) { Handler.LOG.warn("Couldn't determine NodeTemplateId of Ubuntu Node"); return false; } // adds field into plan input message to give the plan it's own address // for the invoker PortType (callback etc.). This is needed as WSO2 BPS // 2.x can't give that at runtime (bug) LOG.debug("Adding plan callback address field to plan input"); templateContext.addStringValueToPlanRequest("planCallbackAddress_invoker"); // add csarEntryPoint to plan input message LOG.debug("Adding csarEntryPoint field to plan input"); templateContext.addStringValueToPlanRequest("csarEntrypoint"); LOG.debug("Handling DA references:"); for (AbstractArtifactReference ref : refs) { // upload da ref and unzip it this.invokerPlugin.handleArtifactReferenceUpload(ref, templateContext, serverIpPropWrapper, sshUserVariable, sshKeyVariable, templateId); } return true; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ftp_server; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPReply; /** * * @author Mahesh Rathnayaka */ public class FileUpload { public void fileSelecting() throws IOException { File f = new File("D:\\jpg"); FilenameFilter textfile = new FilenameFilter() { @Override public boolean accept(File dir, String name) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. return name.toLowerCase().endsWith(".jpg"); } }; File[] files = f.listFiles(textfile); for (File file : files) { if (file.isDirectory()) { System.out.println("Directory"); } else { System.out.println("File : "); } System.out.println(file.getAbsolutePath()); System.out.println(file.getCanonicalPath()); System.out.println(file.getName()); } } public void uploading() { FTPClient client = new FTPClient(); FileInputStream fis = null; try { client.connect("shamalmahesh.net78.net"); client.login("a9959679", "9P3IckDo"); client.setFileType(FTP.BINARY_FILE_TYPE); int reply = client.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { System.out.println("Uploading...."); } else { System.out.println("Failed connect to the server!"); } // String filename = "DownloadedLook1.txt"; String path = "D:\\jpg\\"; // String filename = "1.jpg"; String filename = "appearance.jpg"; System.out.println(path+filename); fis = new FileInputStream(path + filename); System.out.println(fis.toString()); boolean status = client.storeFile("/public_html/testing/" + filename, fis); System.out.println("Status : " + status); System.out.println("Done!"); client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } public void uploadingWithProgress() { FTPClient ftp = new FTPClient(); FileInputStream fis = null; try { ftp.connect("shamalmahesh.net78.net"); ftp.login("a9959679", "9P3IckDo"); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.changeWorkingDirectory("/public_html/testing"); int reply = ftp.getReplyCode(); if (FTPReply.isPositiveCompletion(reply)) { System.out.println("Uploading...."); } else { System.out.println("Failed connect to the server!"); } File f1 = new File("D:\\jpg\\1.jpg"); // fis = new FileInputStream(ftp.storeFile("one.jpg", fis)); System.out.println("Done!"); } catch (IOException e) { e.printStackTrace(); } } }
//Problem:112. Path Sum /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { return findIfPossible(root, sum, 0); } boolean findIfPossible(TreeNode node, int req, int cur) { if(node == null) { return false; } cur += node.val; if(req == cur && node.left == null && node.right == null) { return true; } return findIfPossible(node.left, req, cur) || findIfPossible(node.right, req, cur); } }
package com.tencent.mm.plugin.nearby.ui; import android.content.DialogInterface; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import android.widget.TextView; import com.tencent.mm.R; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.be.a; import com.tencent.mm.k.g; import com.tencent.mm.model.au; import com.tencent.mm.plugin.nearby.a.c; import com.tencent.mm.sdk.platformtools.BackwardSupportUtil; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ba; import com.tencent.mm.storage.bb; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.base.n.d; import com.tencent.mm.ui.base.p; import com.tencent.mm.ui.tools.k; public class NearbySayHiListUI extends MMActivity implements e { private int daw = 0; private ListView eIM; private View eLM; private d hlb = new 3(this); private c lBD; private bb lCu = null; private a lCv; private int lCw = 0; private int lCx = 0; private boolean lCy; private long lCz; private int limit = 0; private p tipDialog = null; static /* synthetic */ void j(NearbySayHiListUI nearbySayHiListUI) { if (nearbySayHiListUI.lCw == 0) { TextView textView = (TextView) nearbySayHiListUI.findViewById(R.h.empty_msg_tip_tv); textView.setText(R.l.say_hi_non); textView.setVisibility(0); nearbySayHiListUI.enableOptionMenu(false); } } public void onCreate(Bundle bundle) { int i; NearbySayHiListUI nearbySayHiListUI; super.onCreate(bundle); this.daw = bi.WU(g.AT().getValue("ThresholdToCleanLocation")); this.lCy = getIntent().getBooleanExtra("show_clear_header", false); this.lCu = com.tencent.mm.az.d.SG(); setMMTitle(R.l.say_hi_list_lbs_title); this.lCx = this.lCu.axd(); this.lCw = this.lCu.getCount(); if (a.cbf()) { i = this.lCw; nearbySayHiListUI = this; } else if (this.lCx == 0) { i = 8; nearbySayHiListUI = this; } else { i = this.lCx; nearbySayHiListUI = this; } nearbySayHiListUI.limit = i; this.lCu.cma(); initView(); } protected void onResume() { super.onResume(); if (this.lCw != this.lCu.getCount()) { this.lCw = this.lCu.getCount(); if (this.lCw == 0) { TextView textView = (TextView) findViewById(R.h.empty_msg_tip_tv); textView.setText(R.l.say_hi_non); textView.setVisibility(0); enableOptionMenu(false); } this.lCv.WT(); } this.lCv.notifyDataSetChanged(); au.DF().a(148, this); } public void onDestroy() { this.lCv.aYc(); super.onDestroy(); } public void onPause() { au.DF().b(148, this); super.onPause(); } protected final int getLayoutId() { return R.i.lbs_say_hi_list; } public boolean onKeyDown(int i, KeyEvent keyEvent) { return super.onKeyDown(i, keyEvent); } protected final void initView() { this.eIM = (ListView) findViewById(R.h.say_hi_lv); if (!a.cbf()) { View inflate = getLayoutInflater().inflate(R.i.say_hi_list_footer, null); inflate.setOnClickListener(new 1(this, inflate)); if (this.lCw > 0 && this.limit < this.lCw) { this.eIM.addFooterView(inflate); } } addTextOptionMenu(0, getString(R.l.app_clear), new 5(this)); if (this.lCw == 0) { TextView textView = (TextView) findViewById(R.h.empty_msg_tip_tv); textView.setText(R.l.say_hi_non); textView.setVisibility(0); enableOptionMenu(false); } if (this.lCy && this.daw != 0 && this.lCx >= this.daw && bi.fU(this)) { this.eLM = new CleanLocationHeaderView(this); this.eLM.setOnClickListener(new 6(this)); this.eIM.addHeaderView(this.eLM); } this.lCv = new a(this, this, this.lCu, this.limit); this.lCv.setGetViewPositionCallback(new 7(this)); this.lCv.setPerformItemClickListener(new 8(this)); this.lCv.a(new 9(this)); this.eIM.setAdapter(this.lCv); this.eIM.setOnItemLongClickListener(new 10(this, new k(this))); this.eIM.setOnItemClickListener(new 11(this)); setBackBtn(new 12(this)); AnonymousClass2 anonymousClass2 = new OnClickListener() { public final void onClick(View view) { BackwardSupportUtil.c.a(NearbySayHiListUI.this.eIM); } }; } public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenuInfo contextMenuInfo) { AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo) contextMenuInfo; ba baVar = (ba) this.lCv.getItem(adapterContextMenuInfo.position); if (baVar == null) { x.e("MicroMsg.SayHiListUI", "onItemLongClick, item is null, pos = " + adapterContextMenuInfo.position); return; } contextMenu.add(0, 0, 0, R.l.app_delete); this.lCz = baVar.field_svrid; } public void onBackPressed() { setResult(0); super.onBackPressed(); } public final void a(int i, int i2, String str, l lVar) { x.i("MicroMsg.SayHiListUI", "onSceneEnd: errType=%d, errCode=%d, errMsg=%s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); if (this.tipDialog != null) { this.tipDialog.dismiss(); this.tipDialog = null; } if (i != 0 || i2 != 0) { x.w("MicroMsg.SayHiListUI", "[cpan] clear location failed."); } else if (((c) lVar).Oh() == 2) { h.a(this.mController.tml, getString(R.l.nearby_friend_clear_location_ok), "", new DialogInterface.OnClickListener() { public final void onClick(DialogInterface dialogInterface, int i) { NearbySayHiListUI.this.setResult(-1); NearbySayHiListUI.this.finish(); } }); this.lBD = null; } } }
package com.rails.ecommerce.admin.api.bean; import java.io.Serializable; /** * Class Name: CarDate.java * Function:订单表 * * Modifications: * * @author gxl DateTime 2015-1-9 上午10:08:46 * @version 1.0 */ public class CarDate implements Serializable { private static final long serialVersionUID = 1L; private String Yyrq; private String DisplayYyrq; private String DisplayWeek; public String getYyrq() { return Yyrq; } public void setYyrq(String yyrq) { Yyrq = yyrq; } public String getDisplayYyrq() { return DisplayYyrq; } public void setDisplayYyrq(String displayYyrq) { DisplayYyrq = displayYyrq; } public String getDisplayWeek() { return DisplayWeek; } public void setDisplayWeek(String displayWeek) { DisplayWeek = displayWeek; } }
package org.gmart.devtools.java.serdes.codeGen.javaGen.model.old_referenceResolution; ///******************************************************************************* // * Copyright 2020 Grégoire Martinetti // * // * Licensed under the Apache License, Version 2.0 (the "License"); you may not // * use this file except in compliance with the License. You may obtain a copy // * of the License at // * // * http://www.apache.org/licenses/LICENSE-2.0 // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // * License for the specific language governing permissions and limitations under // * the License. // ******************************************************************************/ //package org.gmart.codeGen.javaGen.model.old_referenceResolution; // //import java.util.List; //import java.util.Optional; //import java.util.function.Function; // //import org.gmart.codeGen.javaGen.model.DeserialContext; //import org.gmart.codeGen.javaGen.model.TypeExpression; //import org.gmart.codeGen.javaGen.model.classTypes.AbstractClassDefinition; // //import api_global.logUtility.L; // //public class AccessorBuilderFromConstructorArgument extends AbstractAccessorBuilder { // // private final Function<Function<List<Object>, Optional<Object>>, Function<List<Object>, Optional<Object>>> accessor; // private final int paramIndex; // public AccessorBuilderFromConstructorArgument(AbstractClassDefinition hostClass, List<String> path, int paramIndex){ // super(); // this.accessor = makeAccessorBuilder( // ((AccessorConstructorParameter)hostClass.getConstructorParameters().get(paramIndex)).getOutputTypeParameter(), // path.subList(1, path.size()), // this.toFillWithIOTypesForValidation // ); // this.paramIndex = paramIndex; // //the call of the current constructor in superclass factory method ensure that the following // //hostClass.getConstructorParameters().stream().filter(param -> param.getName().equals(path.get(0))).findFirst(); // } // private Function<Function<List<Object>, Optional<Object>>, Function<List<Object>, Optional<Object>>> makeAccessorBuilder(TypeExpression accessorParamOutputType, List<String> path, AccessPathKeyAndOutputTypes toFillWithIOTypesForValidation) { // L.l("accessorParamOutputType.getReferenceJPoetTypeName(false):" + accessorParamOutputType.getReferenceJPoetTypeName(false)); // L.l("accessorParamOutputType:" + accessorParamOutputType); // L.l("path:" + path); // Function<Object, Function<List<Object>, Optional<Object>>> accessor = accessorParamOutputType.makeAccessorBuilder(path, toFillWithIOTypesForValidation); // L.l("path2:" + path); // return keysToObj -> { // return keys -> { // return keysToObj.apply(keys).map(accessor); // }; // }; // } // public Function<List<Object>, Optional<Object>> makeAccessor(DeserialContext ctx) { // Function<List<Object>, Optional<Object>> constrArg = ctx.getHostClassContext().getArgs().get(paramIndex); // return this.accessor.apply(constrArg); // } //}
package com.example.retrofit_firebase; import java.util.List; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.GET; import retrofit2.http.PATCH; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; public interface ApiInterface { @GET("/movies/{new}.json") Call<Movie> getMovie(@Path("new") String s1); @POST("/movies/{new}.json") Call<List<Movie>> setMovie(@Path("new") String s1, @Body Movie movie); @PUT("/movies/{new}.json") Call<List<Movie>> setMovieWithoutRandomness(@Path("new") String s1, @Body Movie movie); @DELETE("/movies/{new}.json") Call<List<Movie>> deleteMovie(@Path("new") String s1); @PATCH("/movies/{new}.json") Call<List<Movie>> updateMovie(@Path("new") String s1, @Body Movie movie ); }
package algorithm.baekjoon.BruteForce; /* * 10448 - 유레카 이론 * 시작: 14:30 * 끝: 16:00 * 시간: 1시간 30분... <실수로인해 잡아먹은 시간이 너무 크다!! * * [ 고쳐야할 점 ] * - 문제를 정확히 파악하고 설계한 후 코드로 옮겨야 한다 * - 이 문제같은 경우 막연히 삼각수 세개를 더한 값을 구한다고 생각해서 '연속된'세개의 합만 구하다보니 미궁에 빠진 문제다... * 제발 설계를 먼저 해보고 코드로 옮기자 ㅠㅠ 이런 실수는 너무 치명적이다 */ import java.util.*; public class _10448_EurekaTheory { static int num[]; static void triCheck(List<Integer> samgak) { // int[] t = new int[3]; // 연속한 것이 아니다!! // t[0] = n * (n + 1) / 2; // t[1] = (n + 1) * (n + 2) / 2; // t[2] = (n + 2) * (n + 3) / 2; // if (t[0] + t[0] + t[0] > 1000) // return; for (int i = 0; i < samgak.size(); i++) { for (int j = 0; j < samgak.size(); j++) { for (int k = 0; k < samgak.size(); k++) { if (samgak.get(i) + samgak.get(j) + samgak.get(k) > 1000) continue; num[samgak.get(i) + samgak.get(j) + samgak.get(k)] = 1; // int T = t[i] + t[j] + t[k]; // if (T > 1000) // continue; // if (num[T] == 1) // continue; // System.out.println("T" + (n + i)+"("+t[i]+")" + " + " + "T" + (n + j)+"("+t[j]+")" + " + " + "T" + (n + k) +"("+t[k]+")" + " = " + T); // num[T] = 1; } } } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> nl = new ArrayList<>(); for (int i = 0; i < n; i++) { nl.add(sc.nextInt()); } // 삼각수를 구한다 List<Integer> samgak = new ArrayList<>(); for (int i = 1; i < 45; i++) { samgak.add(i * (i + 1) / 2); } // System.out.println(samgak); num = new int[1001]; Arrays.fill(num, 0); triCheck(samgak); for (int _nl : nl) { System.out.println(num[_nl]); } } }
package com.ic.SysAgenda.resource; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.ic.SysAgenda.exception.NaoEncontradoException; import com.ic.SysAgenda.model.Compromisso; import com.ic.SysAgenda.service.CompromissoService; @RestController @RequestMapping("/compromisso") public class CompromissoResource { @Autowired private CompromissoService compromissoService; @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Compromisso> salvar(@RequestBody Compromisso compromisso) { Compromisso aux = this.compromissoService.salvar(compromisso); return new ResponseEntity<Compromisso>(aux, HttpStatus.OK); } @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<Compromisso>> listarTodos() { List<Compromisso> aux = this.compromissoService.listarTodos(); return new ResponseEntity<List<Compromisso>>(aux, HttpStatus.OK); } @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<Compromisso> atualizar(@RequestBody Compromisso compromisso) { try { Compromisso c = this.compromissoService.atualizar(compromisso); return new ResponseEntity<Compromisso>(c, HttpStatus.OK); } catch (NaoEncontradoException e) { return new ResponseEntity<Compromisso>(HttpStatus.NOT_FOUND); } } @DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> deletar(@PathVariable Long id) { try { return new ResponseEntity<String>(this.compromissoService.deletar(id), HttpStatus.OK); } catch (NaoEncontradoException e) { return new ResponseEntity<String>("Compromisso não encontrado", HttpStatus.NOT_FOUND); } } }
package com.zhowin.miyou.mine.adapter; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.zhowin.base_library.model.UserLevelInfo; import com.zhowin.base_library.model.UserRankInfo; import com.zhowin.base_library.utils.GlideUtils; import com.zhowin.base_library.utils.SetDrawableHelper; import com.zhowin.miyou.R; import com.zhowin.miyou.main.utils.GenderHelper; import com.zhowin.miyou.mine.callback.OnAttentionOrFansClickListener; import com.zhowin.miyou.mine.model.AttentionUserList; /** * author : zho * date :2020/9/1 * desc : */ public class AttentionAndFansAdapter extends BaseQuickAdapter<AttentionUserList, BaseViewHolder> { private int adapterType = 1; private OnAttentionOrFansClickListener onAttentionOrFansClickListener; public void setOnAttentionOrFansClickListener(OnAttentionOrFansClickListener onAttentionOrFansClickListener) { this.onAttentionOrFansClickListener = onAttentionOrFansClickListener; } public AttentionAndFansAdapter() { super(R.layout.include_attention_and_fans_item_view); } public void setAdapterType(int adapterType) { this.adapterType = adapterType; notifyDataSetChanged(); } @Override protected void convert(@NonNull BaseViewHolder helper, AttentionUserList item) { helper.setGone(R.id.tvCreateTime, 3 == adapterType) .setGone(R.id.tvMutualAttention, 3 != adapterType); GlideUtils.loadUserPhotoForLogin(mContext, item.getProfilePictureKey(), helper.getView(R.id.civUserHeadPhoto)); helper.setText(R.id.tvUserNickName, item.getAvatar()) .setBackgroundRes(R.id.tvUserSex, GenderHelper.getSexBackground(item.getGender())) .setText(R.id.tvUserSex, String.valueOf(item.getAge())) .setText(R.id.tvMutualAttention, 1 == item.getRelation() ? "取消关注" : "互相关注") .getView(R.id.civUserHeadPhoto).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onAttentionOrFansClickListener != null) { onAttentionOrFansClickListener.onItemHeaderPhotoClick(item.getUserId()); } } }); helper.getView(R.id.tvMutualAttention).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (onAttentionOrFansClickListener != null) { onAttentionOrFansClickListener.onItemAttentionOrFanClick(helper.getAdapterPosition(), item.getRelation(), item.getUserId()); } } }); TextView tvUserSex = helper.getView(R.id.tvUserSex); SetDrawableHelper.setLeftDrawable(mContext, tvUserSex, TextUtils.equals("男", item.getGender()), 2, R.drawable.man_icon, R.drawable.girl_icon); UserLevelInfo userItemLevelInf = item.getLevelObj(); if (userItemLevelInf != null) { helper.setGone(R.id.tvUserLevel, 0 != userItemLevelInf.getLevel()) .setText(R.id.tvUserLevel, "v" + userItemLevelInf.getLevel()); } UserRankInfo itemUserRank = item.getRank(); if (itemUserRank != null) { helper.setGone(R.id.tvKnighthood, true) .setText(R.id.tvKnighthood, itemUserRank.getRankName()); } else { helper.setGone(R.id.tvKnighthood, false); } } }
package com.org.web; import com.org.NotFoundException; import com.org.po.Type; import com.org.service.BlogService; import com.org.service.TagService; import com.org.service.TypeService; import com.org.vo.BlogQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @author MengXi * @Controller 用于表示层的注解,作用与@Component注解一样,表明将该资源交给spring进行管理 * String value : 指定bean的id,如果不屑,默认为该类的类名(且将其首字母小写) */ @Controller public class IndexController { /** * @GetMapping 建立请求url和处理请求方法之间的映射关系,配置在类上为一级注解,配置在方法上为二级注解 * String value : 指定请求的url * String method :指定请求的方法 * String params : 限制请求参数的条件,支持简单的表达式 * * Restful风格的参数获取:url + 请求方式 * 在url中使用占位符进行参数绑定,同时在方法中使用@PathVariable注解与占位符进行匹配,参数名称要一致。 */ @Autowired private BlogService blogService; @Autowired private TypeService typeService; @Autowired private TagService tagService; /** * 分页获取博客内容 * @param pageable * @param model * @return */ @GetMapping("/") public String index(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable ,Model model) { model.addAttribute("page", blogService.listBlog(pageable)); model.addAttribute("types", typeService.listTypeTop(6)); model.addAttribute("tags", tagService.listTagTop(10)); model.addAttribute("recommendBlogs", blogService.listRecommendBlogTop(8)); return "index"; } @PostMapping("/search") public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable , @RequestParam String query, Model model) { model.addAttribute("page", blogService.listBlog("%" + query + "%", pageable)); model.addAttribute("query", query); return "search"; } @GetMapping("/blog/{id}") public String blog(@PathVariable Long id, Model model) { model.addAttribute("blog", blogService.getAndConvert(id)); return "blog"; } /** * 刷新底部的博客推荐 * @param model * @return */ @GetMapping("/footer/newblog") public String newblogs(Model model) { model.addAttribute("newblogs", blogService.listRecommendBlogTop(3)); return "_fragments :: newblogList"; } }
package singleton; import java.io.Serializable; public class SingletonLesson implements Serializable{ enum MySingleton{ INSTANCE; public void doJob(){ } } private static final SingletonLesson singleton=new SingletonLesson(); private SingletonLesson() { } private Object readResolve(){return singleton;} public static SingletonLesson getInstance(){return singleton;} public static void main(String[] args) { // singleton.someMethod(); // somOtherLocalMethod(singleton); SingletonLesson.getInstance(); } }
package hw.zoo; import hw.zoo.model.*; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Scanner; import java.util.stream.IntStream; public class ParserCommand { ZooFactory zooFactory = new ZooFactory(); Zoo zoo = new Zoo(Integer.parseInt(Files.readAllLines(Paths.get("C:\\UNC-Source-Code-main\\src\\hw\\Species.txt")).get(0))); Scanner keyboard = new Scanner(System.in); public ParserCommand() throws IOException { } public void getResult() throws IOException { while (true) { String command = keyboard.nextLine(); String[] word = command.split("\\s"); String c = word[0]; switch (c) { case "check-in" -> { try { Species.getSpecies(word[1]); } catch (IOException e) { System.out.println(e.getMessage()); getResult(); } zoo.checkInAnimal(zooFactory.createAnimal(Species.getSpecies(word[1]), word[2])); } case "check-out" -> { try { Species.getSpecies(word[1]); } catch (IOException e) { System.out.println(e.getMessage()); getResult(); } zoo.checkOutAnimal(zooFactory.createAnimal(Species.getSpecies(word[1]), word[2])); } case "log" -> log(zoo.getHistory()); case "exit" -> System.exit(1); default -> System.out.println("Incorrect command. Try again."); } } } public void log(List<InhibitionLog> inhibitionLogs) { for (InhibitionLog inhibitionLog : inhibitionLogs) { System.out.print(inhibitionLog); } } }
package animatronics.network; import java.util.List; import animatronics.Animatronics; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.World; public class PacketSender { public static void sendPacketToAllAround(World world,Packet packet, int x, int y, int z, int dimId, double distance) { List <EntityPlayer> playerLst = world.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.getBoundingBox(x-0.5D, y-0.5D, z-0.5D, x+0.5D, y+0.5D, z+0.5D).expand(distance, distance, distance)); if(!playerLst.isEmpty()) { for(Object player : playerLst) { if(player instanceof EntityPlayerMP) { if(packet instanceof S35PacketUpdateTileEntity) { NBTTagCompound tileTag = new NBTTagCompound(); world.getTileEntity(x, y, z).writeToNBT(tileTag); Animatronics.packetSender.sendTo(new IMessageDataPacket(tileTag,-10), (EntityPlayerMP) player); } else { if(((EntityPlayerMP) player).dimension == dimId) ((EntityPlayerMP)player).getServerForPlayer().func_73046_m().getConfigurationManager().sendPacketToAllPlayers(packet); } } else { Animatronics.logger.debug("Trying to send packet "+packet+" to all around on Client side, probably a bug, ending the packet send try"); } } } } public static void sendPacketToAll(World w,Packet pkt) { List<EntityPlayer> playerLst = w.playerEntities; if(!playerLst.isEmpty()) { for(Object player : playerLst) { if(player instanceof EntityPlayerMP) { ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(pkt); } else { Animatronics.logger.debug("Trying to send packet "+pkt+" to all on Client side, probably a bug, ending the packet send try"); } } } } public static void sendPacketToAllInDim(World w,Packet pkt, int dimId) { List<EntityPlayer> playerLst = w.playerEntities; if(!playerLst.isEmpty()) { for(Object player : playerLst) { if(player instanceof EntityPlayerMP) { if(((EntityPlayerMP) player).dimension == dimId) ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(pkt); } else { Animatronics.logger.debug("Trying to send packet "+pkt+" to all in dimension "+dimId+" on Client side, probably a bug, ending the packet send try"); } } } } public static void sendPacketToPlayer(World w,Packet pkt,EntityPlayer player) { if(player instanceof EntityPlayerMP) { ((EntityPlayerMP)player).playerNetServerHandler.sendPacket(pkt); } else { Animatronics.logger.debug("Trying to send packet "+pkt+" to player "+player+"||"+player.getDisplayName()+" on Client side, probably a bug, ending the packet send try"); } } }
/** * Copyright (C) 2009 BonitaSoft S.A. * BonitaSoft, 31 rue Gustave Eiffel - 38000 Grenoble * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2.0 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bonitasoft.studio.diagram.custom.actions; import org.bonitasoft.studio.common.ExpressionConstants; import org.bonitasoft.studio.common.emf.tools.ModelHelper; import org.bonitasoft.studio.common.gmf.tools.GMFTools; import org.bonitasoft.studio.common.repository.RepositoryManager; import org.bonitasoft.studio.common.repository.model.IRepository; import org.bonitasoft.studio.diagram.custom.Messages; import org.bonitasoft.studio.diagram.custom.repository.DiagramFileStore; import org.bonitasoft.studio.diagram.custom.repository.DiagramRepositoryStore; import org.bonitasoft.studio.model.expression.Expression; import org.bonitasoft.studio.model.process.AbstractProcess; import org.bonitasoft.studio.model.process.CallActivity; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart; import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.PlatformUI; /** * @author Mickael Istria * */ public class OpenLatestSubprocessCommand extends AbstractHandler { private DiagramRepositoryStore diagramSotre; /* * (non-Javadoc) * * @see * org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands. * ExecutionEvent) */ public Object execute(ExecutionEvent event) throws ExecutionException { IRepository repository = RepositoryManager.getInstance().getCurrentRepository() ; diagramSotre = (DiagramRepositoryStore) repository.getRepositoryStore(DiagramRepositoryStore.class) ; try { IStructuredSelection selection = (IStructuredSelection) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); Object item = selection.getFirstElement(); CallActivity subProcess = (CallActivity) ((GraphicalEditPart) item).resolveSemanticElement(); final Expression calledProcessName = subProcess.getCalledActivityName(); String subprocessName = null ; if(calledProcessName != null && calledProcessName.getContent() != null && calledProcessName.getType().equals(ExpressionConstants.CONSTANT_TYPE)){ subprocessName = calledProcessName.getContent() ; } final Expression calledProcessVersion = subProcess.getCalledActivityVersion(); String subprocessVersion = null ; if(calledProcessVersion != null && calledProcessVersion.getContent() != null && calledProcessVersion.getType().equals(ExpressionConstants.CONSTANT_TYPE)){ subprocessVersion = calledProcessVersion.getContent() ; } if(subprocessName != null){ AbstractProcess subProcessParent = ModelHelper.findProcess(subprocessName,subprocessVersion, diagramSotre.getAllProcesses()); if (subProcessParent == null) { /* we don't find the process so we can't open it */ return null; } Resource r = subProcessParent.eResource() ; if(r != null){ String fileName = r.getURI().lastSegment() ; DiagramFileStore store = diagramSotre.getChild(URI.decode(fileName)) ; // if the diagram is already opened if(store.getOpenedEditor()!=null){ for(IEditorReference ref : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getEditorReferences()){ if(ref.getEditorInput().getName().equals(store.getName())){ PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(ref.getPart(true)); break; } } }else{ //if the diagram referenced is not opened store.open() ; } final DiagramEditor editor = (DiagramEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor(); final IGraphicalEditPart findEditPart = GMFTools.findEditPart(editor.getDiagramEditPart(), subProcessParent); if(findEditPart != null){ editor.getDiagramGraphicalViewer().select(findEditPart); } } else { MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), Messages.errorSubprocessNotFound, Messages.errorSubprocessDoesNotExist); throw new ExecutionException("Could not open specified subprocess, it probably doesn't exist"); } } } catch (Exception e) { // TODO: handle exception } return null; } /* * (non-Javadoc) * * @see org.eclipse.core.commands.AbstractHandler#isEnabled() */ @Override public boolean isEnabled() { IStructuredSelection selection = (IStructuredSelection) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection(); Object item = selection.getFirstElement(); EObject element = ((GraphicalEditPart) item).resolveSemanticElement(); return element instanceof CallActivity && ((CallActivity) element).getCalledActivityName() != null; } }
import java.util.ArrayList; /** * Test Person class, Student class, Employee class, and Manager Class. Also use ArrayList in Test. * @version 1.8.0 09-16-2017 * @author Aaron Lam */ public class Test { public static void main(String args[]){ //test the Person and Student ArrayList<Person> people = new ArrayList<>(); people.add(new Student("Michael", "computer science")); people.add(new Employee("Devin", 50000, 1989, 10, 1)); for(Person p : people) System.out.println(p.getName() + ", " + p.getDescription()); //test the Manager and Employee Manager boss = new Manager("David", 150000, 1987, 12, 15); boss.setBonus(5000); ArrayList<Employee> staff = new ArrayList<>(); staff.add(new Employee("Aaron", 120000, 2017, 6, 24)); staff.add(new Employee("Harry", 40000)); staff.add(new Employee(60000)); staff.add(new Employee()); staff.add(boss); for (Employee aEmployee : staff) System.out.println(aEmployee); //test the raise salary System.out.println(); System.out.println("After raising the salary: "); for (Employee e : staff){ e.raiseSalary(12); System.out.println(e.getName() + ": " + e.getSalary()); } } }
package org.ravi.helloworld; public class Hello { public String displayHelloMessage(String message){ String msg; if(message != null && !message.isEmpty()){ msg = message; } else { msg = "hi";} return msg; } }
package MutuallyExclusiveThreads; public class Pressure extends Thread{ void raisePressure() { if(P.pressureGuage < P.safetyLimit - 15) { try { sleep(100); } catch(Exception e){} P.pressureGuage += 15; } else; } public void run() { raisePressure(); } }
package com.yixin.kepler.common.enums; /** * 微众银行车辆类型枚举类 * @author YixinCapital -- chenjiacheng * 2018年07月09日 17:17 **/ public enum WBCarTypeEnum { NEW_CAR("1","新车"), USED_CAR("2","二手车"); private String value; private String name; WBCarTypeEnum(String value, String name) { this.value = value; this.name = name; } public String getValue() { return value; } public String getName() { return name; } }
package com.wenxc.jsfunction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.wenxc.afdc.FunctionHelper; import com.wenxc.afdc.inte.AFDC; /** * Created by wenxc on 2016/4/8. */ public class BaseActivity extends AppCompatActivity implements AFDC { protected FunctionHelper functionHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initFunction(); } @Override public FunctionHelper getFunctionHelper() { return functionHelper; } @Override public void setEnableAFDC(boolean enable) { functionHelper.setEnableAFCallback(enable); } @Override public boolean isEnableAFDC() { return functionHelper.isEnableAFDC(); } @Override public void initFunction() { functionHelper = new FunctionHelper(false); } }
/** * Paintroid: An image manipulation application for Android. * Copyright (C) 2010-2013 The Catrobat Team * (<http://developer.catrobat.org/credits>) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.catrobat.paintroid.command.implementation; import org.catrobat.paintroid.PaintroidApplication; import org.catrobat.paintroid.tools.helper.floodfill.QueueLinearFloodFiller; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.util.Log; public class FillCommand extends BaseCommand { private static final float SELECTION_THRESHOLD = 50.0f; private static final int EMPTY_COMMAND_LIST_LENGTH = 1; private Point mClickedPixel; public FillCommand(Point clickedPixel, Paint currentPaint) { super(currentPaint); mClickedPixel = clickedPixel; } @Override public void run(Canvas canvas, Bitmap bitmap) { notifyStatus(NOTIFY_STATES.COMMAND_STARTED); if (mClickedPixel == null) { setChanged(); notifyStatus(NOTIFY_STATES.COMMAND_FAILED); return; } if (PaintroidApplication.savedPictureUri == null && PaintroidApplication.commandManager.getNumberOfCommands() == EMPTY_COMMAND_LIST_LENGTH + 1) { canvas.drawColor(mPaint.getColor()); Log.w(PaintroidApplication.TAG, "Fill Command color: " + mPaint.getColor()); } else { int colorToReplace = bitmap.getPixel(mClickedPixel.x, mClickedPixel.y); int pixels[] = new int[bitmap.getWidth() * bitmap.getHeight()]; bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); QueueLinearFloodFiller.floodFill(pixels, bitmap.getWidth(), bitmap.getHeight(), mClickedPixel, colorToReplace, mPaint.getColor(), SELECTION_THRESHOLD); bitmap.setPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight()); } notifyStatus(NOTIFY_STATES.COMMAND_DONE); } }
package jie.android.ip.screen.menu; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import jie.android.ip.CommonConsts.PackConfig; import jie.android.ip.common.actor.BaseGroupAccessor; import jie.android.ip.common.actor.ButtonActor; import jie.android.ip.common.actor.ScreenGroup; import jie.android.ip.playservice.PlayService; import jie.android.ip.screen.BaseScreen; import jie.android.ip.screen.menu.MenuConfig.Const; import jie.android.ip.screen.menu.MenuConfig.Image; public class PlayServicePanelGroup extends ScreenGroup { private final TextureAtlas textureAtlas; private final Skin skin; private final TweenManager tweenManager; private final PlayService playService; private boolean show = false; public PlayServicePanelGroup(final BaseScreen screen) { super(screen); this.textureAtlas = super.resources.getTextureAtlas(PackConfig.SCREEN_MENU); this.skin = new Skin(this.textureAtlas); this.tweenManager = this.screen.getTweenManager(); this.playService = this.screen.getGame().getPlayService(); initStage(); } @Override protected void initStage() { this.setBounds(Const.PlayService.BASE_X, Const.PlayService.BASE_Y, Const.PlayService.WIDTH, Const.PlayService.HEIGHT); final ButtonActor achieve = new ButtonActor(new Button.ButtonStyle(skin.getDrawable(Image.PlayService.ACHIEVE_UP), skin.getDrawable(Image.PlayService.ACHIEVE_DOWN), null)); achieve.setPosition(Const.PlayService.X_ACHIEVE, Const.PlayService.Y_ACHIEVE); achieve.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { onAchieveClicked(); } }); this.addActor(achieve); final ButtonActor board = new ButtonActor(new Button.ButtonStyle(skin.getDrawable(Image.PlayService.BOARD_UP), skin.getDrawable(Image.PlayService.BOARD_DOWN), null)); board.setPosition(Const.PlayService.X_BOARD, Const.PlayService.Y_BOARD); board.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { onBoardClicked(); } }); this.addActor(board); this.screen.addActor(this); } public boolean isShowing() { return show; } public void show() { if (show || (playService != null && playService.isSignedIn())) { show(null); } } public void show(final TweenCallback callback) { show = !show; if (show) { Tween.to(this, BaseGroupAccessor.POSITION_X, 0.1f).target(Const.PlayService.TARGET_X) .setCallback(callback) .start(tweenManager); } else { Tween.to(this, BaseGroupAccessor.POSITION_X, 0.1f).target(Const.PlayService.BASE_X) .setCallback(callback) .start(tweenManager); } } protected void onAchieveClicked() { playService.showAchievements(); } protected void onBoardClicked() { playService.showAllLeaderboards(); } }
package com.example.demo.controller;//package com.wangan.springdata.controller; // // // //@RestController //public class UserController { // // @RequestMapping("/hello") // public String hello(){ // return "hello"; // } // //}
package io.ygg.common; import io.ygg.packet.Packet; import io.ygg.tcp.TcpProcessor; import java.io.IOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.UUID; /* * Copyright (c) 2015 * Christian Tucker. All rights reserved. * * The use of OGServer is free of charge for personal and commercial use. * * * THIS SOFTWARE IS PROVIDED 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * * * Policy subject to change. */ /** * A {@link Session} is a container class holding information about a * networking session. * * @author Christian Tucker */ public class Session { /** * The total amount of bytes that have been received by the server. */ public static long bytesIn; /** * The total amount of bytes received by the server in the last 1000ms. */ public static long bytesInCurrent; /** * The total amount of bytes that have been sent by the server. */ public static long bytesOut; /** * The total amount of bytes sent by the server in the last 1000ms. */ public static int bytesOutCurrent; /** * A {@link HashSet} containing a collection of active {@link Session} * instances. */ private static Set<Session> currentSessions = new HashSet<>(); /** * A {@link HashMap} containing a collection of active {@link Session}'s * sorted by their respected {@link #sessionKey}. */ private static HashMap<UUID, Session> sessionMap = new HashMap<>(); /** * The {@link SelectionKey} relative to the {@link Session}. */ private SelectionKey key; /** * A {@link ByteBuffer} that contains all of the bytes for incoming * network data. */ private ByteBuffer inputBuffer; /** * A {@link UUID} that will identify each session when exchanging data over * a UDP connection. */ private UUID sessionKey; /** * A boolean value containing rather or not the TcpStream has been * segmented between multiple reads of the {@link SelectionKey}. * This value is always false during the first read of a packet. */ private boolean segmented; /** * The mark relative to the sessions {@link #inputBuffer}, used by the * {@link TcpProcessor} when the sessions {@link #segmented} state is true. */ private int mark; /** * A boolean value containing rather or not the TcpStream has * decoded the header relative to the incoming {@link Packet}. */ private boolean header; /** * A numerical representation of the amount of bytes the current incoming {@link Packet} * for this session contains. */ private int blockSize; /** * A {@link Object} that is attached to the {@link Session}. */ private Object attachment; /** * Constructs a new {@link Session} instance. * * @param key The key relative to the {@link Session} */ public Session(SelectionKey key) throws IOException { this.key = key; this.inputBuffer = ByteBuffer.allocate(Config.tcpBufferAllocation); this.sessionKey = UUID.randomUUID(); currentSessions.add(this); sessionMap.put(sessionKey, this); Log.info("New connection was established, session key: " + sessionKey); if (Config.enableUDP) { Packet.send(Packet.PacketType.TCP, this, 0, sessionKey.getMostSignificantBits(), sessionKey.getLeastSignificantBits()); } } /** * Returns a {@link HashSet} containing a collection of active {@link Session} * instances. * * @return The {@link HashSet}. */ public static Set<Session> getSessions() { return currentSessions; } /** * Returns a {@link HashMap} containing a collection of active {@link Session}'s * sorted by their {@link #sessionKey}. * * @return The {@link HashMap}. */ public static HashMap<UUID, Session> getSessionMap() { return sessionMap; } /** * Removes all references to the session from collections and closes the * associated buffers and channels. */ public void close() throws IOException { currentSessions.remove(this); sessionMap.remove(sessionKey); inputBuffer = null; try { getChannel().close(); }catch(NullPointerException ignored){ //Channel seems to be null in certain cases, if it is null then we don't have to close it, // and thus we avoid the exception. } key.attach(null); } /** * Returns the {@link Object} attached to this session. * * @return The object. */ public Object getAttachment() { return attachment; } /** * Sets the {@link Session}'s attachment to the specified {@link Object}. * * @param attatchment The {@link Object}. */ public void attach(Object attachment) { this.attachment = attachment; } /** * Tells the session to release all data pertaining to the {@link TcpProcessor}. * Calling this method will set the following values to false (or 0): * <p> * <li> {@link #header}. * <li> {@link #segmented}. * <li> {@link #blockSize}. * <li> {@link #mark}. * <p> * This will also clear the current content in the {@link #inputBuffer}. */ public void release() throws IOException { this.header = false; this.segmented = false; this.blockSize = 0; this.mark = 0; if (this.inputBuffer != null) {//If the session is still opened on client-side this.inputBuffer.clear(); } else { this.close(); } } /** * Returns a numerical representation of the amount of bytes the current incoming {@link Packet} * for this session. * * @return The amount of incoming bytes. */ public int blockSize() { return blockSize; } /** * Sets the value of {@link #blockSize} to the specified value. * * @param blockSize The value. */ public void setBlockSize(int blockSize) { this.blockSize = blockSize; } /** * returns a boolean value containing rather or not the TcpStream has * decoded the header relative to the incoming {@link Packet}. * * @return rather or not the TcpStream has decoded the header. */ public boolean header() { return header; } /** * Sets the current {@link #header} state to true, identifying that the * TcpStream has decoded the header. */ public void prime() { this.header = true; } /** * Returns the mark relative to the sessions {@link #inputBuffer}, used by the * {@link TcpProcessor} when the sessions {@link #segmented} state is true. * * @return The mark. */ public int mark() { return mark; } /** * Sets the current {@link #mark} to equal the value provided. * * @param mark The new mark. */ public void mark(int mark) { this.mark = mark; } /** * Returns a boolean value containing rather or not the TcpStream has been * segmented between multiple reads of the {@link SelectionKey}. * This value is always false during the first read of a packet. * * @return The value of {@link #segmented} */ public boolean segmented() { return segmented; } /** * Tells the {@link Session} that the Tcp stream is segmented and should persist * data throughout multiple reads to gather the data required to decode the income * {@link Packet}. */ public void segment() { this.segmented = true; } /** * Returns a {@link UUID} that identifies a session. * * @return The {@link UUID}. */ public UUID getSessionKey() { return sessionKey; } /** * Returns a {@link ByteBuffer} that contains all of the bytes for incoming * network data. * * @return The {@link ByteBuffer}. */ public ByteBuffer getInputBuffer() { return inputBuffer; } /** * Returns the {@link SelectionKey} relative to the {@link Session}. * * @return The {@link SelectionKey}. */ public SelectionKey getKey() { return key; } /** * Returns the {@link Channel} relative to the {@link Session}. * * @return The {@link Channel}. */ public SocketChannel getChannel() { return (SocketChannel) key.channel(); } /** * Returns the {@link InetAddress} relative to the {@link Session}. * * @return The {@link InetAddress}. */ public InetAddress getHost() { return getChannel().socket().getLocalAddress(); } /** * Only for testing purpose at the moment. * Sets the current input buffer to null. */ public void removeBuffer(){ this.inputBuffer = null; } }
package com.tencent.mm.plugin.appbrand.jsapi; import android.content.Intent; import com.tencent.mm.plugin.appbrand.jsapi.JsApiLaunchApplication.1.1; import com.tencent.mm.plugin.appbrand.jsapi.JsApiLaunchApplication.a; import com.tencent.mm.pluginsdk.model.app.g; import com.tencent.mm.protocal.c.aoh; class JsApiLaunchApplication$1$1$2 implements Runnable { final /* synthetic */ 1 fGa; final /* synthetic */ aoh fGb; final /* synthetic */ a fGc; final /* synthetic */ Intent val$intent; JsApiLaunchApplication$1$1$2(1 1, Intent intent, aoh aoh, a aVar) { this.fGa = 1; this.val$intent = intent; this.fGb = aoh; this.fGc = aVar; } public final void run() { this.fGc.cJ(g.a(this.fGa.fFZ.fCl.getContext(), this.val$intent, null, this.fGb.rQQ, this.fGc, this.fGa.fFZ.fFU)); } }
package com.tencent.mm.plugin.voip.video; import android.os.Looper; import com.tencent.mm.plugin.voip.model.v2protocal; import com.tencent.mm.sdk.platformtools.ag; import java.util.ArrayList; public final class k { public ArrayList<a> hfT = new ArrayList(); public int mRotateAngle = 0; public v2protocal oMN = new v2protocal(new ag(Looper.myLooper())); public boolean oVv = false; public int oVw; public int oVx; }
import java.util.*; class Invoker { private List<Command> history; public Invoker() { this.history = new LinkedList<>(); } public void storeAndExecute(Command command) { this.history.add(command); command.execute(); } }
package com.summer.web.basic.client.dto; import java.io.Serializable; import java.util.List; /** * Bo层返回体 * * @author luke * @date 2019/06/03 */ public class PageOut<T extends Serializable> { /** * 记录总数 */ private Long total; /** * 当前页码 */ private Integer pageNo; /** * 页面条数 */ private Integer pageSize; /** * 数据集合 */ private List<T> items; /** * 总页数 */ private Long totalPage; public Long getTotalPage() { if (total == null || pageSize == null || pageSize == 0) { return 0L; } if (total % pageSize == 0) { return total / pageSize; } long temp = total / pageSize; return temp + 1; } public PageOut() { } public Long getTotal() { return this.total; } public Integer getPageNo() { return this.pageNo; } public Integer getPageSize() { return this.pageSize; } public List<T> getItems() { return this.items; } public void setTotal(final Long total) { this.total = total; } public void setPageNo(final Integer pageNo) { this.pageNo = pageNo; } public void setPageSize(final Integer pageSize) { this.pageSize = pageSize; } public void setItems(final List<T> items) { this.items = items; } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference // Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2018.08.03 at 02:15:07 PM CEST // package life.qbic.xml.study; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.tuple.Pair; import life.qbic.xml.manager.StudyXMLParser; /** * <p> * Java class for anonymous complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="qcontlevel" maxOccurs="unbounded"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="entity_id" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;attribute name="value" use="required" type="{http://www.w3.org/2001/XMLSchema}double" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="label" use="required" type="{}variable_name_format" /> * &lt;attribute name="unit" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = {"qcontlevel"}) public class Qcontinuous { @XmlElement(required = true) protected List<Qcontlevel> qcontlevel; @XmlAttribute(name = "label", required = true) protected String label; @XmlAttribute(name = "unit", required = true) protected String unit; /** * Gets the value of the qcontlevel property. * * <p> * This accessor method returns a reference to the live list, not a snapshot. Therefore any * modification you make to the returned list will be present inside the JAXB object. This is why * there is not a <CODE>set</CODE> method for the qcontlevel property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getQcontlevel().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Qcontlevel } * * */ public List<Qcontlevel> getQcontlevel() { if (qcontlevel == null) { qcontlevel = new ArrayList<Qcontlevel>(); } return this.qcontlevel; } /** * Gets the value of the label property. * * @return possible object is {@link String } * */ public String getLabel() { return label; } /** * Sets the value of the label property. * * @param value allowed object is {@link String } * */ public void setLabel(String value) { this.label = value; } /** * Gets the value of the unit property. * * @return possible object is {@link String } * */ public String getUnit() { return unit; } /** * Sets the value of the unit property. * * @param value allowed object is {@link String } * */ public void setUnit(String value) { this.unit = value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((qcontlevel == null) ? 0 : qcontlevel.hashCode()); result = prime * result + ((unit == null) ? 0 : unit.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Qcontinuous other = (Qcontinuous) obj; if (label == null) { if (other.label != null) return false; } else if (!label.equals(other.label)) return false; if (qcontlevel == null) { if (other.qcontlevel != null) return false; } else if (!qcontlevel.equals(other.qcontlevel)) return false; if (unit == null) { if (other.unit != null) return false; } else if (!unit.equals(other.unit)) return false; return true; } public Qcontlevel getLevelOrNull(String value) { for (Qcontlevel level : getQcontlevel()) { if (level.getValue().equals(value)) { return level; } } return null; } public void createLevels(Map<Pair<String, String>, List<String>> levels) { for (Pair<String, String> valunit : levels.keySet()) { createLevel(valunit.getLeft(), levels.get(valunit)); } } private void createLevel(String value, List<String> ids) { Qcontlevel contLvl = StudyXMLParser.factory.createQcontlevel(); contLvl.setValue(value); contLvl.getEntityId().addAll(ids); getQcontlevel().add(contLvl); } public void update(Map<Pair<String, String>, List<String>> levels) { for (Pair<String, String> level : levels.keySet()) { List<String> ids = levels.get(level); String value = level.getLeft(); // first remove all identifiers from other levels since they can't be part of multiple levels removeIDsFromOldLevels(ids, value); Qcontlevel xmlLevel = getLevelOrNull(value); if (xmlLevel == null) { // if level exists, add all new identifiers on this level to the set, if not create it and // also set value createLevel(value, ids); } else { xmlLevel.getEntityId().addAll(ids); } } } /** * remove new ids from every old level with the wrong level value * * @param ids * @param newValue */ private void removeIDsFromOldLevels(List<String> ids, String newValue) { Set<Qcontlevel> levelsToRemove = new HashSet<>(); for (Qcontlevel oldLevel : getQcontlevel()) { if (!oldLevel.getValue().equals(newValue)) { oldLevel.getEntityId().removeAll(ids); // remove empty level completely if (oldLevel.getEntityId().isEmpty()) { levelsToRemove.add(oldLevel); } } } getQcontlevel().removeAll(levelsToRemove); } }
public class MergeSort extends SortTpl { private static Comparable[] item; private static void sort(Comparable[] list, int start, int end) { if (start >= end) { return; } int middle = (start + end)/2; sort(list, start, middle); sort(list, middle+1, end); // merge merge(list, start, middle, end); } private static void merge(Comparable[] list, int start, int middle, int end) { int left = start; int right = middle+1; for (int i = start; i <= end; i++) { // 左侧列表空 取右侧 if (left > middle) { item[i] = list[right++]; } else if (right > end) { // 右侧列表空 取得左侧 item[i] = list[left++]; } else if (less(list[left], list[right])) { // 左侧节点小于右侧节点 取出左侧节点 item[i] = list[left++]; } else { // 取出右侧节点 item[i] = list[right++]; } } // 回填到原数组中 for (int i = start; i <= end; i++) { list[i] = item[i]; } } public static void sort(Comparable[] data) { item = new Comparable[data.length]; sort(data, 0, data.length-1); } }
package org.sagebionetworks.repo.manager; import java.util.List; import org.sagebionetworks.repo.model.UserInfo; /** * This manager supports sending system generated messages to users, the messages are sent from a noreply address * and delivery failures are ignored (e.g. no delivery failure notification is sent back to the original sender). * * @author brucehoff * */ public interface NotificationManager { /** * Send the given list of messages, the generated message will be send as a notification (from a system noreply sender). * <p/> * Notifications are sent asynchronously, if the messages could not be delivered failure notifications are ignored * * @param userInfo The user requesting the notification to be sent * @param messages The list of messages to be sent */ public void sendNotifications(UserInfo userInfo, List<MessageToUserAndBody> messages); }
package LightProcessing.common.item; import LightProcessing.common.render.ModelHarvester; import LightProcessing.common.tile.TileEntityHarvester; import net.minecraft.item.ItemStack; import net.minecraftforge.client.IItemRenderer; public class ItemHarvesterRenderer implements IItemRenderer { private ModelHarvester HarvesterModel; public ItemHarvesterRenderer() { HarvesterModel = new ModelHarvester(); } @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { return true; } @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return true; } @Override public void renderItem(ItemRenderType type, ItemStack item, Object... data) { TileEntityRenderer.instance.renderTileEntityAt(new TileEntityHarvester(), 0.0D, 0.0D, 0.0D, 0.0F); } }
package application; import java.net.URL; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; public class deleteController implements Initializable{ //DB here TaskManager tm = new TaskManager("tm"); @FXML private TableView<Habit> table; @FXML private TableColumn<Habit, String> habitColumn; @FXML private TableColumn<Habit, String> daysColumn; public void initialize(URL url, ResourceBundle rb) { habitColumn.setCellValueFactory(new PropertyValueFactory<Habit, String>("habit")); daysColumn.setCellValueFactory(new PropertyValueFactory<Habit, String>("goal")); //load dummy data table.setItems(getHabits()); } public ObservableList<Habit> getHabits() { ObservableList<Habit> result = FXCollections.observableArrayList(tm.getHabits()); return result; } @FXML public void sendToDelete() { ObservableList<Habit> selectedRows; ObservableList<Habit> allHabits; //this gives us all the rows try { allHabits = table.getItems(); //this gives us all the rows that were selected selectedRows = table.getSelectionModel().getSelectedItems(); for(Habit h: selectedRows) { if(allHabits.size() >= 1) { allHabits.remove(h); //***delete habit from the DB tm.deleteHabit(h); } } } catch(Exception e) { e.printStackTrace(); } } }
package com.zhouyi.business.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** * @author 李秸康 * @ClassNmae: SysDataLogConditionsDto * @Description: TODO * @date 2019/8/19 16:12 * @Version 1.0 **/ @ApiModel(value = "数据日志条件") @Data public class SysDataLogConditionsDto extends PageDto{ @ApiModelProperty(value = "对象姓名") private String personName; @ApiModelProperty(value = "采集人姓名") private String userName; @ApiModelProperty(value = "IP地址") private String addreIp; }
package com.tt.miniapp.route; import android.content.Context; import android.text.TextUtils; import com.tt.frontendapiinterface.ApiCallResult; import com.tt.miniapp.AppConfig; import com.tt.miniapp.AppbrandApplicationImpl; import com.tt.miniapp.AppbrandServiceManager; import com.tt.miniapp.LifeCycleManager; import com.tt.miniapp.LifeCycleManager.LifecycleInterest; import com.tt.miniapp.page.AppbrandViewWindowRoot; import com.tt.miniapp.util.PageUtil; import com.tt.miniapphost.AppbrandContext; public class PageRouter extends AppbrandServiceManager.ServiceBase { private AppbrandViewWindowRoot mAppbrandPageRoot; private final Context mContext = (Context)AppbrandContext.getInst().getApplicationContext(); public PageRouter(AppbrandApplicationImpl paramAppbrandApplicationImpl) { super(paramAppbrandApplicationImpl); } public AppbrandViewWindowRoot getViewWindowRoot() { return this.mAppbrandPageRoot; } @LifecycleInterest({LifeCycleManager.LifeCycleEvent.ON_APP_CREATE}) public void onAppCreate() { this.mAppbrandPageRoot = new AppbrandViewWindowRoot(this.mContext, this.mApp); } public boolean onBackPressed() { this.mApp.getLifeCycleManager().notifyAppRoute(); return this.mAppbrandPageRoot.onBackPressed(); } public void reLaunchByUrl(String paramString) { this.mApp.getLifeCycleManager().notifyAppRoute(); if (TextUtils.isEmpty(paramString)) return; PageUtil.PageRouterParams pageRouterParams = new PageUtil.PageRouterParams(); pageRouterParams.url = paramString; int i = paramString.indexOf("?"); String str = paramString; if (i > 0) str = paramString.substring(0, i); pageRouterParams.path = str; route("reLaunch", pageRouterParams); } public ApiCallResult.a route(String paramString, PageUtil.PageRouterParams paramPageRouterParams) { this.mApp.getLifeCycleManager().notifyAppRoute(); return "navigateTo".equals(paramString) ? this.mAppbrandPageRoot.navigateTo(paramPageRouterParams) : ("navigateBack".equals(paramString) ? this.mAppbrandPageRoot.navigateBack(paramPageRouterParams) : ("redirectTo".equals(paramString) ? this.mAppbrandPageRoot.redirectTo(paramPageRouterParams) : ("reLaunch".equals(paramString) ? this.mAppbrandPageRoot.reLaunch(paramPageRouterParams) : ("switchTab".equals(paramString) ? this.mAppbrandPageRoot.switchTab(paramPageRouterParams) : null)))); } public void setup(AppConfig paramAppConfig, String paramString) { this.mAppbrandPageRoot.setupLaunch(paramAppConfig, paramString); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\route\PageRouter.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.example.lib.db; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; /** * @Author jacky.peng * @Date 2021/4/14 9:19 AM * @Version 1.0 */ @Entity(tableName = DBParams.EVENT_TABLE_NAME) public class EventEntity { @PrimaryKey(autoGenerate = true) private int id; @ColumnInfo(name = "create_time") private long create_time; @ColumnInfo(name = "data") private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } public int getId() { return id; } public void setId(int id) { this.id = id; } public long getCreate_time() { return create_time; } public void setCreate_time(long create_time) { this.create_time = create_time; } }
package com.lti.handson2; import java.util.Scanner; public class Palindrome { public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.println("Enter the string:"); String s=sc.next(); String x=""; for(int i=s.length()-1;i>=0;i--) { x=x+s.charAt(i); } if(s.equals(x)) { System.out.println(s+ "is a Palindrome"); } else { System.out.println(s+ "is not a Palindrome"); } } }
package edu.stanford.iftenney; import java.io.*; import java.util.*; import edu.stanford.nlp.io.*; import edu.stanford.nlp.ling.*; import edu.stanford.nlp.pipeline.*; import edu.stanford.nlp.util.*; import edu.stanford.nlp.ling.CoreAnnotations.*; import org.json.simple.*; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; /** * Created by iftenney on 11/15/14. */ public class JSONAnnotator { public static class CustomFulltextAnnotation implements CoreAnnotation<String> { public Class<String> getType() { return String.class; } } public static class CustomLabelAnnotation implements CoreAnnotation<String> { public Class<String> getType() { return String.class; } } public static class CustomGUIDAnnotation implements CoreAnnotation<String> { public Class<String> getType() { return String.class; } } // Extract tag lists from a list of CoreLabel tokens public static List<String> getTagList(List<CoreLabel> tokens, Class<? extends TypesafeMap.Key<String>> key) { List<String> taglist = new ArrayList<>(); for (CoreLabel token : tokens) { taglist.add(token.get(key)); } return taglist; } public static void main(String[] args) throws IOException { String infile = args[0]; // Load data from JSON JSONParser jp = new JSONParser(); Object obj = null; try { EncodingFileReader fileReader = new EncodingFileReader(infile); obj = jp.parse(fileReader); } catch (ParseException e) { System.out.printf("Error type: %d%n", e.getErrorType()); System.out.printf("Position: %d%n", e.getPosition()); System.out.printf("Unexpected: %s%n", e.getUnexpectedObject()); e.printStackTrace(); System.exit(1); } JSONObject dataset = (JSONObject)obj; // Make list of sentences List<Annotation> sentences = new ArrayList<>(dataset.size()); for (Object key : dataset.keySet()) { String guid = (String)key; JSONArray ja = (JSONArray)dataset.get(guid); Annotation a = new Annotation((String)ja.get(0)); a.set(CustomGUIDAnnotation.class, guid); // store ID a.set(CustomFulltextAnnotation.class, (String)ja.get(0)); // store unmodified fulltext JSONArray labels = null; try { labels = (JSONArray)ja.get(1); } catch (ClassCastException e) { labels = new JSONArray(); labels.add(ja.get(1)); //labels.put(ja.get(1)); } a.set(CustomLabelAnnotation.class, labels.toString()); // store custom label // a.set(CustomLabelAnnotation.class, (String)ja.get(1)); // store custom label sentences.add(a); //String out = String.format("%s -> %s", ja.get(0), ja.get(1)); //System.out.println(out); } // Set up CoreNLP pipeline to pre-annotate Properties props = new Properties(); props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner"); StanfordCoreNLP pipeline = new StanfordCoreNLP(props); // Run pipeline long startTime = System.currentTimeMillis(); pipeline.annotate(sentences); long duration = System.currentTimeMillis() - startTime; System.out.println(String.format( "Annotated %d sentences in %.02f seconds", sentences.size(), duration/1000.0 )); // Output writer //PrintWriter jsonOut = new PrintWriter(infile+".tagged.json"); //for(Annotation a: sentences) { // pipeline.jsonPrint(a, jsonOut); //} // Generate compact JSON representation String outfile = infile+".tagged.json"; PrintWriter jsonOut = new PrintWriter(outfile); int counter = 0; for (Annotation a: sentences) { JSONObject jobj = new JSONObject(); List<CoreLabel> tokens = a.get(TokensAnnotation.class); jobj.put("word",getTagList(tokens, TextAnnotation.class)); jobj.put("lemma", getTagList(tokens, LemmaAnnotation.class)); jobj.put("pos", getTagList(tokens, PartOfSpeechAnnotation.class)); jobj.put("ner", getTagList(tokens, NamedEntityTagAnnotation.class)); jobj.put("__LABEL__", a.get(CustomLabelAnnotation.class)); jobj.put("__ID__", a.get(CustomGUIDAnnotation.class)); jobj.put("__TEXT__", a.get(CustomFulltextAnnotation.class)); System.out.println("Writing tagged sentence " + a.get(CustomGUIDAnnotation.class)); String json = jobj.toJSONString() + "\n"; jsonOut.write(json); jsonOut.flush(); counter++; } System.out.println(String.format("Wrote %d sentences to %s", counter, outfile)); } }
package myn; import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.TextArea; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.UIManager; public class PALETTE { private JFrame frame; private JTextArea textArea_1; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { PALETTE window = new PALETTE(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public static JProgressBar progressBar ; public static TextArea textArea; public static JLabel num; public PALETTE() { initialize(); this.frame.setSize(2048, 1134); //设置位置 this.frame. setLocation(50, 50); //背景图片的路径。(相对路径或者绝对路径。本例图片放于"java项目名"的文件下) String path = "./image/background.jpg"; // 背景图片 ImageIcon background = new ImageIcon(path); // 把背景图片显示在一个标签里面 JLabel label = new JLabel(background); // 把标签的大小位置设置为图片刚好填充整个面板 label.setBounds(0, 0, this.frame.getWidth(), this.frame.getHeight()); // 把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明 JPanel imagePanel = (JPanel) this.frame.getContentPane(); frame.getContentPane().setLayout(null); JFileChooser fileChooser = new JFileChooser(); fileChooser.setBounds(863, 306, 666, 402); frame.getContentPane().add(fileChooser); fileChooser.setVisible(false); fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); JLabel lblNewLabel = new JLabel("\u91CD\u590D\u6587\u4EF6\u67E5\u91CD\u5668(by:mayining)"); lblNewLabel.setForeground(new Color(255, 250, 240)); lblNewLabel.setFont(new Font("方正静蕾简体加粗版", Font.BOLD, 72)); lblNewLabel.setBounds(491, 77, 1181, 98); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("\u8BF7\u9009\u62E9\u8981\u68C0\u67E5\u7684\u6587\u4EF6\u5939"); lblNewLabel_1.setForeground(new Color(100, 149, 237)); lblNewLabel_1.setFont(new Font("Aunt-沉魅体", Font.BOLD, 50)); lblNewLabel_1.setBounds(139, 208, 550, 74); frame.getContentPane().add(lblNewLabel_1); textArea = new TextArea(); textArea.setEditable(true); textArea.setFont(new Font("Monospaced", Font.PLAIN, 32)); textArea.setText("\u8BF7\u9009\u62E9\u8DEF\u5F84\u540E\u70B9\u51FB\u5F00\u59CB\u6309\u94AE\u3002"); textArea.setBounds(10, -12, 1684, 552); frame.getContentPane().add(textArea); JScrollPane jsp = new JScrollPane( textArea); jsp.setBounds(246, 395, 1684, 552); //设置 JScrollPane 宽100,高200 frame.getContentPane().add(jsp); JLabel label_1 = new JLabel("\u5904\u7406\u5982\u4E0B\uFF1A"); label_1.setForeground(new Color(100, 149, 237)); label_1.setFont(new Font("Aunt-沉魅体", Font.BOLD, 50)); label_1.setBounds(139, 306, 255, 74); frame.getContentPane().add(label_1); textArea_1 = new JTextArea(); textArea_1.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { } }); textArea_1.setBackground(UIManager.getColor("TextField.caretForeground")); textArea_1.setForeground(new Color(255, 255, 255)); textArea_1.setFont(new Font("方正静蕾简体加粗版", Font.PLAIN, 40)); textArea_1.setText("\u8BF7\u70B9\u51FB\u8FD9\u91CC\u8F93\u5165\u6216\u8005\u70B9\u51FB\u53F3\u4FA7\u6309\u94AE\u9009\u62E9"); textArea_1.setBounds(718, 226, 858, 63); frame.getContentPane().add(textArea_1); imagePanel.setOpaque(false); // 把背景图片添加到分层窗格的最底层作为背景 this.frame.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE)); //设置可见 frame.setVisible(true); //点关闭按钮时退出 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); JButton btnNewButton = new JButton("\u9009\u62E9"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fileChooser.setVisible(true); int returnVal = fileChooser.showOpenDialog( fileChooser); if( returnVal==fileChooser.CANCEL_OPTION){ } else if( returnVal==fileChooser.APPROVE_OPTION){ File file = fileChooser.getSelectedFile(); textArea_1.setText(file.getAbsolutePath()); } } }); btnNewButton.setToolTipText(""); btnNewButton.setForeground(new Color(250, 250, 210)); btnNewButton.setBackground(new Color(0, 0, 0)); btnNewButton.setFont(new Font("海派腔调禅大黑简2.0", Font.PLAIN, 44)); btnNewButton.setBounds(1607, 226, 162, 57); frame.getContentPane().add(btnNewButton); progressBar = new JProgressBar(); progressBar.setBounds(430, 323, 1146, 39); frame.getContentPane().add(progressBar); progressBar.setVisible(false); JButton btnStart = new JButton("\u5F00\u59CB"); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(num.getText().contains("完成")||num.getText().contains("...")) progressBar.setVisible(true); Thread my=new Thread(new Runnable(){ public void run(){ DuplicateFile temp = new DuplicateFile(); File o=new File(textArea_1.getText()); PALETTE.textArea.setText(""); temp.run(o); } }); if(num.getText().contains("完成")||num.getText().contains("...")){ System.out.println("run!"); my.start(); } } }); btnStart.setToolTipText(""); btnStart.setForeground(new Color(250, 250, 210)); btnStart.setFont(new Font("海派腔调禅大黑简2.0", Font.PLAIN, 44)); btnStart.setBackground(Color.BLACK); btnStart.setBounds(1802, 225, 162, 57); frame.getContentPane().add(btnStart); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(1933, 747, -336, -349); frame.getContentPane().add(scrollPane); num = new JLabel("..."); num.setForeground(UIManager.getColor("TextArea.background")); num.setFont(new Font("方正静蕾简体加粗版", Font.PLAIN, 50)); num.setBounds(1607, 306, 393, 57); frame.getContentPane().add(num); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.getContentPane().setEnabled(false); frame.setAutoRequestFocus(false); } }
package com.techelevator.dao; import java.util.ArrayList; import java.util.List; import com.techelevator.dao.model.Product; import com.techelevator.dao.model.ProductFilter; import com.techelevator.dao.model.ProductSortOrder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; public class JdbcProductDaoTest extends DaoIntegrationTest { private JdbcTemplate jdbcTemplate; private JdbcProductDao productDao; @Before public void setup() { jdbcTemplate = new JdbcTemplate(super.getDataSource()); productDao = new JdbcProductDao(super.getDataSource()); jdbcTemplate.execute("INSERT INTO categories (id, name) VALUES (1, 'TEST1')"); } @Test public void getAll_returns_all_products() { List<Product> products = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Product product = createProduct("TEST PRODUCT " + i, 1, i + ".png", "Test product " + i + "is wonderful!", 0, false, i, 5.00); products.add(product); insertProduct(product); } List<Product> actualProducts = productDao.getAll(); assertThat(actualProducts, hasSize(10)); assertThat(actualProducts, equalTo(products)); } @Test public void getAll_returns_products_within_priceRange() { Product productBelowMinPrice = createProduct("$0.99 Product", 1, "99-cent-product", "Product that costs $0.99", 1, false, 0, 0.99); insertProduct(productBelowMinPrice); Product productAtMinPrice = createProduct("$1.00 Product", 1, "1-dollar-product", "Product that costs $1.00", 1, false, 0, 1.00); insertProduct(productAtMinPrice); Product productAtMaxPrice = createProduct("$2.00 Product", 1, "2-dollar-product", "Product that costs $2.00", 1, false, 0, 2.00); insertProduct(productAtMaxPrice); Product productAboveMaxPrice = createProduct("$2.01 Product", 1, "2-01-dollar-product", "Product that costs $2.01", 1, false, 0, 2.01); insertProduct(productAboveMaxPrice); ProductFilter filter = new ProductFilter(); filter.setMinPrice(1.00); filter.setMaxPrice(2.00); List<Product> actualProducts = productDao.getAll(filter, null); assertThat(actualProducts, hasSize(2)); assertThat(actualProducts, containsInAnyOrder(new Product[] { productAtMinPrice, productAtMaxPrice })); } @Test public void getAll_returns_products_greater_than_or_equal_to_minPrice() { Product productBelowMinPrice = createProduct("$0.99 Product", 1, "99-cent-product", "Product that costs $0.99", 1, false, 0, 0.99); insertProduct(productBelowMinPrice); Product productAtMinPrice = createProduct("$1.00 Product", 1, "1-dollar-product", "Product that costs $1.00", 1, false, 0, 1.00); insertProduct(productAtMinPrice); Product productAtMaxPrice = createProduct("$2.00 Product", 1, "2-dollar-product", "Product that costs $2.00", 1, false, 0, 2.00); insertProduct(productAtMaxPrice); Product productAboveMaxPrice = createProduct("$2.01 Product", 1, "2-01-dollar-product", "Product that costs $2.01", 1, false, 0, 2.01); insertProduct(productAboveMaxPrice); ProductFilter filter = new ProductFilter(); filter.setMinPrice(2.0); List<Product> actualProducts = productDao.getAll(filter, null); assertThat(actualProducts, hasSize(2)); assertThat(actualProducts, containsInAnyOrder(new Product[] { productAtMaxPrice, productAboveMaxPrice })); } @Test public void getAll_returns_products_less_than_or_equal_to_maxPrice() { Product productBelowMinPrice = createProduct("$0.99 Product", 1, "99-cent-product", "Product that costs $0.99", 1, false, 0, 0.99); insertProduct(productBelowMinPrice); Product productAtMinPrice = createProduct("$1.00 Product", 1, "1-dollar-product", "Product that costs $1.00", 1, false, 0, 1.00); insertProduct(productAtMinPrice); Product productAtMaxPrice = createProduct("$2.00 Product", 1, "2-dollar-product", "Product that costs $2.00", 1, false, 0, 2.00); insertProduct(productAtMaxPrice); Product productAboveMaxPrice = createProduct("$2.01 Product", 1, "2-01-dollar-product", "Product that costs $2.01", 1, false, 0, 2.01); insertProduct(productAboveMaxPrice); ProductFilter filter = new ProductFilter(); filter.setMaxPrice(1.0); List<Product> actualProducts = productDao.getAll(filter, null); assertThat(actualProducts, hasSize(2)); assertThat(actualProducts, containsInAnyOrder(new Product[] { productAtMinPrice, productBelowMinPrice })); } @Test public void getAll_returns_all_products_if_no_filters_are_provided() { List<Product> products = new ArrayList<>(); for (int i = 1; i <= 10; i++) { Product product = createProduct("TEST PRODUCT " + i, 1, i + ".png", "Test product " + i + "is wonderful!", 0, false, i, 5.00); products.add(product); insertProduct(product); } List<Product> actualProducts = productDao.getAll(null, null); assertThat(actualProducts, hasSize(10)); assertThat(actualProducts, equalTo(products)); } @Test public void getAll_returns_products_filtered_by_category() { jdbcTemplate.execute("INSERT INTO categories (id, name) VALUES (2, 'TEST-CATEGORY-2')"); Product productNotInCategory = createProduct("Not in category", 1, "not-in-category", "Not in the category", 0, false, 0, 0); insertProduct(productNotInCategory); Product productInCategory = createProduct("In category", 2, "in-category", "In the category", 0, false, 0, 0); insertProduct(productInCategory); ProductFilter filter = new ProductFilter(); filter.setCategoryName("TEST-CATEGORY-2"); List<Product> actualProducts = productDao.getAll(filter, null); assertThat(actualProducts, hasSize(1)); assertThat(actualProducts, contains(productInCategory)); } @Test public void getAll_returns_products_filtered_by_rating() { Product productAtMinRating = createProduct("At min rating", 1, "at min rating", "At the min rating", 1.0, false, 0, 0); insertProduct(productAtMinRating); Product productAboveMinRating = createProduct("Above min rating", 1, "above min rating", "Above the min rating", 1.1, false, 0, 0); insertProduct(productAboveMinRating); Product productBelowMinRating = createProduct("Below min rating", 1, "below min rating", "Below the min rating", 0.9, false, 0, 0); insertProduct(productBelowMinRating); ProductFilter filter = new ProductFilter(); filter.setMinRating(1.0); List<Product> actualProducts = productDao.getAll(filter, null); assertThat(actualProducts, hasSize(2)); assertThat(actualProducts, contains(new Product[] { productAtMinRating, productAboveMinRating })); } @Test public void getAll_with_multiple_filters_returns_expected_results() { jdbcTemplate.execute("INSERT INTO categories (id, name) VALUES (2, 'TEST-CATEGORY-2')"); Product productNotInCategory = createProduct("Not in category", 1, "not-in-category", "Not in the category", 0, false, 0, 0); insertProduct(productNotInCategory); Product productInCategory = createProduct("In category", 2, "in-category", "In the category", 0, false, 0, 0); insertProduct(productInCategory); Product productBelowMinPrice = createProduct("$0.99 Product", 1, "99-cent-product", "Product that costs $0.99", 1, false, 0, 0.99); insertProduct(productBelowMinPrice); Product productAtMinPrice = createProduct("$1.00 Product", 2, "1-dollar-product", "Product that costs $1.00", 1, false, 0, 1.00); insertProduct(productAtMinPrice); Product productAtMaxPrice = createProduct("$2.00 Product", 1, "2-dollar-product", "Product that costs $2.00", 1, false, 0, 2.00); insertProduct(productAtMaxPrice); Product productAboveMaxPrice = createProduct("$2.01 Product", 1, "2-01-dollar-product", "Product that costs $2.01", 2, false, 0, 2.01); insertProduct(productAboveMaxPrice); ProductFilter filter = new ProductFilter(); filter.setMinPrice(1.00); filter.setMaxPrice(2.00); filter.setCategoryName("TEST-CATEGORY-2"); List<Product> actualProducts = productDao.getAll(filter, null); assertThat(actualProducts, hasSize(1)); assertThat(actualProducts, contains(productAtMinPrice)); } @Test public void getById_returns_the_product_with_the_associated_id() { Product product = createProduct("PRODUCT 1", 1, "PRODUCT-1", "PRODUCT 1 DESC", 0.5, true, 1, 59.95); insertProduct(product); Product actualProduct = productDao.getById(product.getId()); assertThat(actualProduct, equalTo(product)); } @Test public void getById_returns_null_if_the_product_id_is_not_valid() { Product product = createProduct("PRODUCT 1", 1, "PRODUCT-1", "PRODUCT 1 DESC", 0.5, true, 1, 59.95); insertProduct(product); Product actualProduct = productDao.getById(product.getId() + 1); assertThat(actualProduct, nullValue()); } @Test public void getAll_returns_products_sorted_by_priceHighToLow() { Product productBelowMinPrice = createProduct("$0.99 Product", 1, "99-cent-product", "Product that costs $0.99", 1, false, 0, 0.99); insertProduct(productBelowMinPrice); Product productAtMinPrice = createProduct("$1.00 Product", 1, "1-dollar-product", "Product that costs $1.00", 1, false, 0, 1.00); insertProduct(productAtMinPrice); Product productAtMaxPrice = createProduct("$2.00 Product", 1, "2-dollar-product", "Product that costs $2.00", 1, false, 0, 2.00); insertProduct(productAtMaxPrice); ProductSortOrder sortOrder = ProductSortOrder.PRICE_HIGH_TO_LOW; List<Product> actualProducts = productDao.getAll(null, sortOrder); assertThat(actualProducts, containsInRelativeOrder( new Product[] { productAtMaxPrice, productAtMinPrice, productBelowMinPrice })); } @Test public void getAll_returns_products_sorted_by_priceLowToHigh() { Product productBelowMinPrice = createProduct("$0.99 Product", 1, "99-cent-product", "Product that costs $0.99", 1, false, 0, 0.99); insertProduct(productBelowMinPrice); Product productAtMinPrice = createProduct("$1.00 Product", 1, "1-dollar-product", "Product that costs $1.00", 1, false, 0, 1.00); insertProduct(productAtMinPrice); Product productAtMaxPrice = createProduct("$2.00 Product", 1, "2-dollar-product", "Product that costs $2.00", 1, false, 0, 2.00); insertProduct(productAtMaxPrice); ProductSortOrder sortOrder = ProductSortOrder.PRICE_LOW_TO_HIGH; List<Product> actualProducts = productDao.getAll(null, sortOrder); assertThat(actualProducts, containsInRelativeOrder( new Product[] { productBelowMinPrice, productAtMinPrice, productAtMaxPrice })); } @Test public void getAll_returns_products_sorted_by_ratingHighToLow() { List<Product> products = new ArrayList<>(); for (int i = 1; i <= 3; i++) { Product product = createProduct("TEST PRODUCT " + i, 1, i + ".png", "Test product " + i + " is wonderful!", i, false, i, 5.00); products.add(product); insertProduct(product); } ProductSortOrder sortOrder = ProductSortOrder.RATING_HIGH_TO_LOW; List<Product> actualProducts = productDao.getAll(null, sortOrder); assertThat(actualProducts, containsInRelativeOrder(products.get(2), products.get(1), products.get(0))); } private Product createProduct(String name, int categoryId, String imageName, String description, double averageRating, boolean isTopSeller, int quantity, double price) { Product product = new Product(); product.setName(name); product.setCategoryId(categoryId); product.setImageName(imageName); product.setDescription(description); product.setAverageRating(averageRating); product.setTopSeller(isTopSeller); product.setRemainingStock(quantity); product.setPrice(price); return product; } private Product insertProduct(Product product) { SqlRowSet results = jdbcTemplate.queryForRowSet( "INSERT INTO products (category_id, name, image_name, description, average_rating, is_top_seller, quantity, price) VALUES " + "(?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", product.getCategoryId(), product.getName(), product.getImageName(), product.getDescription(), product.getAverageRating(), product.isTopSeller(), product.getRemainingStock(), product.getPrice()); if (results.next()) { product.setId(results.getInt("id")); } return product; } }
package org.dmonix.io.filters; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; /** * Simple filter that accepts all files regardless of path and name. * <p> * Copyright: Copyright (c) 2004 * </p> * <p> * Company: dmonix.org * </p> * * @author Peter Nerg * @since 1.0 */ public class AcceptAllFilter implements FileFilter, FilenameFilter { /** * Always returns true. * * @param pathname * The file path * @return Always true */ public boolean accept(File pathname) { return true; } /** * Always returns true. * * @param dir * The file directory * @param name * The file name * @return Always true */ public boolean accept(File dir, String name) { return true; } }
package ctx; public interface Session { }
package com.katsura.repository; import javax.transaction.Transactional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import com.katsura.model.WebPage; import com.katsura.model.WebPage.Status; public interface WebPageRepository extends JpaRepository<WebPage, String> { WebPage findTopByStatus(Status status); @Modifying @Transactional @Query("update WebPage w set w.status = ?1") void resetStatus(Status status); }
package com.yksoul.pay.payment.ways; import com.google.auto.service.AutoService; import com.yksoul.pay.api.IPaymentStrategy; import com.yksoul.pay.api.IPaymentWay; import com.yksoul.pay.domain.enums.WxPaymentEnum; import com.yksoul.pay.domain.model.PayModel; import com.yksoul.pay.exception.EasyPayException; import com.yksoul.pay.payment.AbstractWxPay; import com.yksoul.pay.utils.ResponseUtils; import com.yksoul.pay.utils.ServerUtils; import java.io.IOException; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * 微信扫码支付 * * @author yk * @version 1.0 * @date 2018-04-24 */ @AutoService(IPaymentStrategy.class) public class WxPayScanCode extends AbstractWxPay { /** * 执行支付操作 * * @param payModel * @throws Exception */ @Override public String onPay(PayModel payModel) throws EasyPayException { try { Map<String, Object> data = new HashMap<>(8); data.put("body", payModel.getSubject()); data.put("out_trade_no", payModel.getOrderSn()); data.put("detail", payModel.getBody()); data.put("total_fee", toFen(new BigDecimal(payModel.getTotalAmount()))); data.put("attach", payModel.getPayment().getPayment()); data.put("spbill_create_ip", ServerUtils.getServerIp(wxPayConfig.getRequest())); data.put("notify_url", wxPayConfig.getPayCallback()); data.put("trade_type", "NATIVE"); Map<String, Object> map = unifiedOrder(data, false); String codeUrl = (String) map.get("code_url"); ResponseUtils.response(wxPayConfig.getResponse(), codeUrl); return null; } catch (IOException e) { throw new EasyPayException(e); } } /** * 对应哪种支付 * * @return */ @Override public IPaymentWay supportsPayment() { return WxPaymentEnum.WXPAY_SCAN_CODE; } }
/* * LocalDateTimeXMLAdapter.java * This file was last modified at 2018.12.03 20:05 by Victor N. Skurikhin. * $Id$ * This is free and unencumbered software released into the public domain. * For more information, please refer to <http://unlicense.org> */ package ru.otus.adapters.xml; import javax.xml.bind.annotation.adapters.XmlAdapter; import java.time.LocalDateTime; public class LocalDateTimeXMLAdapter extends XmlAdapter<String, LocalDateTime> { @Override public LocalDateTime unmarshal(String v) throws Exception { return LocalDateTime.parse(v); } @Override public String marshal(LocalDateTime v) throws Exception { return v.toString(); } } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package com.fancy.ownparking.ui.main; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.design.internal.NavigationMenuView; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.text.TextUtils; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.fancy.ownparking.R; import com.fancy.ownparking.data.local.LocalDatabase; import com.fancy.ownparking.data.local.entity.User; import com.fancy.ownparking.data.model.UserModel; import com.fancy.ownparking.data.pref.OwnParkingSharedPreferences; import com.fancy.ownparking.ui.settings.SettingsFragment; import com.fancy.ownparking.ui.auth.AuthActivity; import com.fancy.ownparking.ui.base.BaseActivity; import com.fancy.ownparking.ui.base.BaseFragment; import com.fancy.ownparking.ui.base.BaseListFragment; import com.fancy.ownparking.ui.car.CarFragment; import com.fancy.ownparking.ui.company.CompanyFragment; import com.fancy.ownparking.ui.request.RequestFragment; import com.fancy.ownparking.ui.statistics.StatisticsFragment; import com.fancy.ownparking.ui.user.UserFragment; import com.fancy.ownparking.utils.FragmentUtils; public class MainActivity extends BaseActivity implements MainContract.View, BaseListFragment.OnActionBarHomeButtonListener { private static final String TAG = MainActivity.class.getSimpleName(); private static final String STATE_TITLE = "STATE_TITLE"; private static final String STATE_USER = "STATE_USER"; private MainPresenter mPresenter; private String mTitle; //Nav drawer private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerListener; private NavigationView mNavigationView; private BaseFragment mFragment; private int mUserId; private UserModel mUserModel; private User mUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPresenter = new MainPresenter(this, LocalDatabase.getInstance(this)); mPresenter.setSharedPreferences(new OwnParkingSharedPreferences(this)); mUserId = mPresenter.getSharedPreferences().getUserId(); bind(); mTitle = getString(R.string.msg_active); if (savedInstanceState != null) { mTitle = savedInstanceState.getString(STATE_TITLE); mUserModel = savedInstanceState.getParcelable(STATE_USER); } //Toolbar getToolbar().setTitle(mTitle); getToolbar().setNavigationOnClickListener(v -> mDrawerLayout.openDrawer(GravityCompat.START)); getSupportActionBar().setDisplayHomeAsUpEnabled(false); //Nav drawer mDrawerListener.syncState(); mNavigationView.setCheckedItem(R.id.nav_car_active); if (mUserModel == null) { getIntentUser(); } else { setNavHeader(); } } private void getIntentUser() { if (getIntent() != null) { if (mUserModel == null) { mPresenter.getUser(mUserId); } else { userLoad(mUserModel); } } } @Override public void bind() { mDrawerLayout = findViewById(R.id.drawer_layout); mNavigationView = findViewById(R.id.navigation_layout); setNavDrawer(); disableNavigationViewScrollbars(mNavigationView); } @Override public void userLoad(UserModel userModel) { mUserModel = userModel; mUser = mUserModel.getUser(); if (userModel.getUser().getRoleId() == 1) { mFragment = RequestFragment.newInstance(mUserModel, RequestFragment.ACTIVE_REQUEST); } else { mFragment = RequestFragment.newInstance(mUserModel, RequestFragment.ACTIVE_REQUEST); Menu menu = mNavigationView.getMenu(); menu.setGroupVisible(R.id.nav_group_admin, false); } setNavHeader(); FragmentUtils.changeFragment(getSupportFragmentManager(), mFragment, R.id.frame_fragment); } @Override public void userNotFound() { exit(); } private void setNavDrawer() { mDrawerListener = new ActionBarDrawerToggle(this, mDrawerLayout, getToolbar(), R.string.navigation_drawer_open, R.string.navigation_drawer_close) { public void onDrawerClosed(View v) { super.onDrawerClosed(v); } public void onDrawerOpened(View v) { super.onDrawerOpened(v); InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); if (inputMethodManager != null) { if (getCurrentFocus() != null) { inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } } }; mDrawerLayout.addDrawerListener(mDrawerListener); mDrawerListener.syncState(); setNavHeader(); mNavigationView.setNavigationItemSelectedListener(item -> { switch (item.getItemId()) { case R.id.nav_parking: //mTitle = getString(R.string.msg_parking); // TODO: 31.05.2018 Parking break; case R.id.nav_car_active: mTitle = getString(R.string.msg_active); mFragment = RequestFragment.newInstance(mUserModel, RequestFragment.ACTIVE_REQUEST); break; case R.id.nav_car_archive: mTitle = getString(R.string.msg_car_archived); mFragment = RequestFragment.newInstance(mUserModel, RequestFragment.ARCHIVE_REQUEST); break; case R.id.nav_car: mTitle = getString(R.string.msg_cars); mFragment = new CarFragment(); break; case R.id.nav_user: mTitle = getString(R.string.msg_users); mFragment = new UserFragment(); break; case R.id.nav_company: mTitle = getString(R.string.msg_companies); mFragment = new CompanyFragment(); break; case R.id.nav_settings: mTitle = getString(R.string.msg_settings); mFragment = new SettingsFragment(); break; } getToolbar().setTitle(mTitle); if (mFragment != null) { FragmentUtils.changeFragment(getSupportFragmentManager(), mFragment, R.id.frame_fragment); } mDrawerLayout.closeDrawers(); return true; }); } private void setNavHeader() { if (mUserModel != null) { mUser = mUserModel.getUser(); View header = mNavigationView.getHeaderView(0); TextView userName = header.findViewById(R.id.text_user_full_name); TextView userRole = header.findViewById(R.id.text_user_access_rights); String fullName = String.format("%s %s", mUser.getLastName(), mUser.getFirstName()); if (TextUtils.isEmpty(mUser.getLastName()) && TextUtils.isEmpty(mUser.getFirstName())) { fullName = mUser.getLogin(); } userName.setText(fullName); userRole.setText(mUser.getRole()); header.setOnClickListener(view -> { mTitle = getString(R.string.msg_statistics); mFragment = new StatisticsFragment(); getToolbar().setTitle(mTitle); if (mFragment != null) { FragmentUtils.changeFragment(getSupportFragmentManager(), mFragment, R.id.frame_fragment); } mDrawerLayout.closeDrawers(); }); } } private void exit() { mPresenter.getSharedPreferences().setAuth(-1, false); Intent i = new Intent(this, AuthActivity.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); finish(); } private void disableNavigationViewScrollbars(NavigationView navigationView) { if (navigationView != null) { NavigationMenuView navigationMenuView = (NavigationMenuView) navigationView.getChildAt(0); if (navigationMenuView != null) { navigationMenuView.setVerticalScrollBarEnabled(false); } } } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(Gravity.START)) { mDrawerLayout.closeDrawers(); return; } else if (mFragment instanceof BaseListFragment && ((BaseListFragment) mFragment).isSelectionEnabled()) { ((BaseListFragment) mFragment).setSelectionEnabled(false); return; } super.onBackPressed(); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putString(STATE_TITLE, mTitle); outState.putParcelable(STATE_USER, mUserModel); super.onSaveInstanceState(outState); } @Override protected void onDestroy() { mPresenter.dispose(); mDrawerLayout.removeDrawerListener(mDrawerListener); super.onDestroy(); } @Override public void onIconChanged(boolean enabled) { if (enabled) { mDrawerLayout.requestDisallowInterceptTouchEvent(true); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mDrawerListener.setDrawerIndicatorEnabled(false); } else { mDrawerLayout.requestDisallowInterceptTouchEvent(false); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); mDrawerListener.setDrawerIndicatorEnabled(true); getToolbar().setNavigationOnClickListener(view -> mDrawerLayout.openDrawer(Gravity.START)); } } }
package dia30enero; import java.util.Scanner; public class arreglosEjercicio1 { public static void main(String[] args) { // TODO Auto-generated method stub int cantidad; cantidad =2; String Usuario[]; Scanner Teclado = new Scanner(System.in); Usuario = new String [cantidad]; Usuario[0]= "Pablo, 23, Masculino"; Usuario[1]= "Carla, 45, Femenino"; for (int i = 0; i < 2; i++) { System.out.printf("\n%s",Usuario[i]); } } }
package Creational.Prototype; import java.util.HashMap; import java.util.Map; /** * * A registry that holds prototypes. * * * It creates a shallow copy of the object. * Meaning it just copies values & references as is in the new object. * * So for example, new object will refer to the same ArrayList object. * * For Deep copy, in the clone method, create a new instance & set values member wise */ public class Registry { Map<String, Movie> movies = new HashMap<>(); public Registry(){ loadMap(); } private void loadMap() { Movie movie = new Movie(); movie.setName("Default"); movie.setTime("Night"); System.out.println(movie.hashCode()); System.out.println(movie.getTime()); System.out.println(movie.getName()); movies.put("Movie",movie); } public Movie createMovie(){ try { return (Movie)movies.get("Movie").clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ejercicio_3; import java.util.Scanner; /** * * @author jrodriguez */ public class Ejercicio_3 { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner entrada =new Scanner (System.in); int dolares, luis, guillermo,juan, cantidad; System.out.println("Ingresar Cantidad de Dolares"); dolares = entrada.nextInt(); guillermo = dolares; luis = dolares /2; juan = (luis+guillermo)/2; cantidad = guillermo + luis + juan; System.out.println("\nGuillerno tiene: "+guillermo); System.out.println("\nluis tiene: "+luis); System.out.println("\nJuan tiene: "+juan); System.out.println("\nCantidad de dinero: "+cantidad); } }
package com.puxtech.reuters.rfa.RelayServer; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lmax.disruptor.EventHandler; import com.puxtech.reuters.rfa.Filter.Filter; public class QuoteEventFilterHandler implements EventHandler<QuoteEvent> { private static final Log offsetLog = LogFactory.getLog("offsetLog"); private Map<String, List<Filter>> filterMaps = new HashMap<String, List<Filter>>(); public void resetFilterBenchMark(String exchangeCode){ List<Filter> filterList = this.filterMaps.get(exchangeCode); if(filterList != null){ for(Filter filter : filterList){ filter.resetBenchMark(); } } } public void putFilterList(String exchangeCode, List<Filter> filterList){ this.filterMaps.put(exchangeCode, filterList); } public Map<String, List<Filter>> getFilterMaps() { return filterMaps; } @Override public void onEvent(QuoteEvent event, long sequence, boolean endOfBatch) throws Exception { List<Filter> filterList = this.filterMaps.get(event.getValue().exchangeCode); if(filterList != null){ // moniterLog.info("filterList size=" + filterList.size()); for(Filter filter : filterList){ filter.filte(event.getValue()); } } if(event != null && event.getValue() != null){ event.getValue().setFilterHandled(); } } }
package by.epam.pia.learning.algorithmization.arraysofarrays; //2. Дана квадратная матрица. Вывести на экран элементы, стоящие на диагонали. import java.util.Arrays; import java.util.Random; import java.util.Scanner; public class Task2 { private static final int RANGE = 20; public static void main(String[] args) { int n; int[][] a; do { n = input("Введите размерность матрицы n(>1)="); } while (n < 2); a = createSquareMatrix(n); for (int i = 0; i < n; i++) { System.out.println("Элемент " + i + " - " + i + " = " + a[i][i]); } } private static int[][] createSquareMatrix(int n) { Random random; random = new Random(); int[][] a; a = new int[n][n]; System.out.println("Инициализация матрицы:"); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = random.nextInt(RANGE) - 10; } System.out.println(Arrays.toString(a[i])); } return a; } private static int input(String prompt) { Scanner scanner; scanner = new Scanner(System.in); System.out.print(prompt); while (!scanner.hasNextInt()) { scanner.nextLine(); } return scanner.nextInt(); } }
package com.zafodB.ethwalletp5.UI; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.zafodB.ethwalletp5.Crypto.WalletWrapper; import com.zafodB.ethwalletp5.FragmentChangerClass; import com.zafodB.ethwalletp5.MainActivity; import com.zafodB.ethwalletp5.R; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * Created by filip on 14/12/2017. */ public class EnterPinFragment extends Fragment { TextView enterPin; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.enter_pin_fragment, container, false); enterPin = view.findViewById(R.id.enter_pin_field); Button createPinBtn = view.findViewById(R.id.create_pin_btn); Button singInBtn = view.findViewById(R.id.sign_in_button); if (walletsExist()) { createPinBtn.setVisibility(View.INVISIBLE); } else { createPinBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { CreatePinFragment createPinFrag = new CreatePinFragment(); WalletWrapper walletWrapper = new WalletWrapper(); System.out.println(walletWrapper.getWalletFileAsString(getContext(), "normal")); FragmentChangerClass.FragmentChanger changer = (FragmentChangerClass.FragmentChanger) getActivity(); changer.ChangeFragments(createPinFrag); } }); } singInBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String pin = enterPin.getText().toString(); if (!verifyPin(pin)) { Toast.makeText(getActivity(), "Pin is wrong!", Toast.LENGTH_SHORT).show(); enterPin.setText(""); } else { MainActivity.setUserPin(pin); FragmentChangerClass.FragmentChanger changer = (FragmentChangerClass.FragmentChanger) getActivity(); FrontPageFragment frontPageFrag = new FrontPageFragment(); changer.ChangeFragments(frontPageFrag); } } }); return view; } private boolean verifyPin(String input) { try { InputStream in = getContext().openFileInput("pinStorage"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String pin = reader.readLine(); // TODO PIN should be secured reader.close(); return pin.equals(input); } catch (IOException e) { e.printStackTrace(); // TODO Handle UI return false; } } boolean walletsExist() { File walletFile = new File(getContext().getFilesDir().getAbsolutePath() + "/" + "pinStorage"); return walletFile.exists(); } }
public class Utilizador extends Object{ String nome; String estado; TipoUtilizador tipoUtilizador; public Utilizador(String nome_, String estado_ , TipoUtilizador tipoUtilizador_) { this.nome = nome_; this.estado = estado_; this.tipoUtilizador = tipoUtilizador_; } public String getEstado() { return this.estado; } public String getNome() { return this.nome; } public TipoUtilizador getTipoUtilizador() { return this.tipoUtilizador; } public void setNome(String nome) { this.nome = nome; } public void setEstado(String estado) { this.estado = estado; } public void setTipoUtilizador(TipoUtilizador tipoUtilizador) { this.tipoUtilizador = tipoUtilizador; } }
package com.smxknife.java2.generics; import com.smxknife.java2.generics._class.Group; /** * @author smxknife * 2019-04-17 */ public class ArrayGeneric { public static void main(String[] args) { // Group<String>[] groups = new Group<String>[10];// 编译报错,不能创建确切类型的范型数组,因为java的泛型运行期是类型擦除,都是Object类型 Group<String> [] groups = new Group[10]; Group<?>[] groups1 = new Group<?>[10]; Group<Integer>[] groupIntegers = (Group<Integer>[]) new Group[10];// 这是可以的 // Group<Integer>[] integerGroups = new Group<?>[10]; // 编译报错,前后类型不匹配 Group<Integer>[] groupIntegers2 = (Group<Integer>[]) new Group<?>[10];// 这样是可以的,但是结果不安全 // ------------------------- 第二轮 Group<String> mygroups = new Group<String>(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.przemo.wicketguicontrols.windows.panels; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.panel.Panel; /** * * @author Przemo */ public class ModalWindowContentPanel extends Panel { private static final String CONTENT_PLACEHOLDER="content"; private static final String BUTTONS_PLACEHOLDER ="buttons"; private final Panel cp, bp; public ModalWindowContentPanel(String id, Panel contentPanel, Panel buttonsPanel) { super(id); this.cp=contentPanel; this.bp=buttonsPanel; add(new WebMarkupContainer(CONTENT_PLACEHOLDER).add(contentPanel)); add(new WebMarkupContainer(BUTTONS_PLACEHOLDER).add(buttonsPanel)); } }
package com.nmit; import java.io.*; import java.util.Hashtable; public class Services { public long ReadPointer(int intcn) { long num = 0; File f1 = null; try { try { f1=new File("C:\\Users\\LENOVO\\workspace\\Servlet\\User's_Pointer_File\\P"+intcn+".txt"); if(!f1.exists()) throw new PointerException(); } catch(PointerException e) { System.out.println(e.toString()); return num; } FileInputStream fis=new FileInputStream(f1); ObjectInputStream oi=new ObjectInputStream(fis); Hashtable usertable1= (Hashtable) oi.readObject(); num=(long) usertable1.get(intcn); oi.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } return num; } }
package poo; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Informe o primeiro número:"); Double n1 = sc.nextDouble(); System.out.println("Informe o segundo número:"); Double n2 = sc.nextDouble(); Calculadora calc = new Calculadora(); calc.setOp01(n1); calc.setOp02(n2); calc.imprimeOperacoes(); } }
package emailApp; import java.util.Scanner; public class Email { private String firstName; private String lastName; private String department; private String password; private String email; private int defaultPasswordLength=8; private int emailBoxCapacity; private String alternateEmail; // constructor for firstName and lastName public Email(String firstName, String lastName) { // super(); this.firstName = firstName; this.lastName = lastName; System.out.println("\nEmail for " + this.firstName + " " + this.lastName + " " + "is created.\n"); // call the method for setting department name this.department=setDepartment(); System.out.println("\n"+this.firstName+" "+this.lastName+" "+"selected "+this.department +" department"); //call method for setting a random password this.password=setPassword(defaultPasswordLength); System.out.println("\nThe Email Password is set as:" + this.password+"\n"); //call method to set the email syntax as fname.lname@dept.company.com System.out.println(this.email=this.firstName.toLowerCase()+"."+this.lastName.toLowerCase()+"@"+this.department.toLowerCase()+"."+"ucmo.com"); } // set the alternate Email public void setAlternateEmail(String email) { this.alternateEmail=email; } //set password capacity public void setEmailBoxCapacity(int capacity) { this.emailBoxCapacity=capacity; } // get the department private String setDepartment() { System.out.print("Department Codes are:\n \n1 SALES\n2 ACCOUNTING\n3 DEVELOPING\n0 NONE\n\nPlease enter your Departement Code:"); Scanner s= new Scanner(System.in); int deptID=s.nextInt(); if(deptID==1) {return "SALES";} else if(deptID==2) {return "ACCOUNTING";} else if(deptID==3) {return "DEVELOPING";} else {return " ";} } // set the random password private String setPassword(int length) { String pass = "ABCDEFGHIJKLMNOPQRSTUVZ0123456789!@#$%&"; char[] password =new char[length]; for(int i=0;i<length;i++) { int rand=(int)(Math.random()*pass.length()); password[i]=pass.charAt(rand); } return new String(password); } // change the password public void setChangePassword(String password) { this.password=password; } public String getAlternateEmail(){return alternateEmail;} public String getChangedPassword() {return password;} public int getEmailBoxCapacity() {return emailBoxCapacity;} //Show the info of name, capacity and email public String showInfo() { return this.firstName + this.lastName + "with the email capacity of "+this.emailBoxCapacity +" MB with the syntax "+this.email; } }
package com.huawei.esdk.demo.utils; import java.lang.reflect.Field; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; public class BeanToJsonUtils { public static String beanToJson(Object bean) { JSONObject jsonObject = JSONObject.fromObject(bean); return jsonObject.toString(); } public static String beanToJson(Object bean, String[] _nory_changes, boolean nory) { JSONObject json = null; if (nory) {// 转换_nory_changes里的属性 Field[] fields = bean.getClass().getDeclaredFields(); StringBuilder sb = new StringBuilder(); for (Field field : fields) { System.out.println(field.getName()); sb.append(":" + field.getName()); } fields = bean.getClass().getSuperclass().getDeclaredFields(); for (Field field : fields) { System.out.println(field.getName()); sb.append (":" + field.getName()); } sb.append( ":"); String str = sb.toString(); for (String s : _nory_changes) { str = str.replace(":" + s + ":", ":"); } json = JSONObject.fromObject(bean, configJson(str.split(":"))); } else { // 转换除了_nory_changes里的属性 json = JSONObject.fromObject(bean, configJson(_nory_changes)); } return json.toString(); } private static JsonConfig configJson(String[] excludes) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(excludes); jsonConfig.setIgnoreDefaultExcludes(false); return jsonConfig; } }
public class Keyqueue { // head und tail = 0 private Node head = null, tail = null; // totalitems = 0 private int totalItems = 0; public Keyqueue() { } // push item in queue public void push(byte b) { // erstelle neues Node objekt Node newNode = new Node(b); // wenn die queue liste leer ist sind head und tail gleich dem neuen Node objekt if (head == null) head = tail = newNode; // wenn die Liste nicht leer ist else { //letztes objekt = nächstes objekt = neues objekt tail.next = newNode; // neues objekt = vorheriges objekt = letztes objekt(tail) newNode.prev = tail; // tail pointer zeigt auf neues Objekt tail = newNode; } /** increase total items count */ // erhöhe total items um 1 totalItems += 1; } // entfernt ein item von der Liste und gibt es aus public byte pop() { // setup objekt wird wiedergegeben byte result = 0x00; // wenn die liste nicht leer ist if (tail != null) { // kopiere die daten des letzten items result = tail.data; /// letztes item wird zu vorheriges item tail = tail.prev; // wenn die lsite nicht leer ist setzte letztens item auf 0 if (tail != null) tail.next = null; // wenn die liste leer ist dann head = tail = 0 else head = tail; // minimiere total items um -1 totalItems -= 1; } // gebe letztes objekt wieder return result; } /** * Removes all instances of an item * @param b byte to be removed */ public void removeItems(byte b) { /** create temporary node and set it to point to head */ Node temp = head; /** loop while end of list not reached */ while (temp != null) { /** if current pointed to object's data is equal to parameter */ if (temp.data == b) { /** reset object's previous link */ if (temp.prev != null) temp.prev.next = temp.next; /** reset object's next link */ if (temp.next != null) temp.next.prev = temp.prev; /** if object is the head of list then reset head */ if (temp == head) head = temp.next; /** if object is the tail of list then reset tail */ if (temp == tail) tail = temp.prev; /** decrease total items count */ totalItems -= 1; } // hole dir das näcshte item aus der liste temp = temp.next; } } // entferne alle elemente public void removeAll() { head = tail = null; } // gebe größe der liste wieder public int size() { return totalItems; } //gebe letztes item aus der liste wieder public byte getLastItem() { // gebe setup daten wieder byte result = 0x00; // wenn due liste leer ist kopiere die letzten item daten if (tail != null) result = tail.data; // gebe daten zurück return result; } //gebe wieder egal ob ein item in der lsite ist oder nicht public boolean contains(byte b) { // setup daten werden wiedergeben (default = false) boolean result = false; // erstelle temporaryx node für navifation Node temp = head; // wiederhole solange bis das Ende der lsite erreicht wurde while (temp != null) { // wenn daten ncith gefunden gehe raus aus der liste if (temp.data == b) { result = true; break; } // hole dir näcshtes item aus der liste temp = temp.next; } // gebe result wieder return result; } // daten für die objekt queue private class Node { // key daten public byte data = 0x00; // pointers auf null setzten public Node prev = null, next = null; // kosntrukt mit daten public Node(byte b) { // setzte daten = b data = b; } // kopiere konstruktor public Node(Node n) { // kopiere daten data = n.data; // kopiere links prev = n.prev; next = n.next; } } }
package com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.activities; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.PorterDuff; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.ShapeDrawable; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ProgressBar; import android.widget.SearchView; import android.widget.TextView; import android.widget.Toast; import com.furestic.alldocument.office.ppt.lxs.docx.pdf.viwer.reader.free.R; import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.adapters.AdapterFilesHolder; import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.constant.Constant; import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.interfaces.OnRecyclerItemClickLister; import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.models.ModelFilesHolder; import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.officereader.AppActivity; import com.furestic.office.ppt.lxs.docx.pdf.viwer.reader.free.pdfViewerModule.PdfViewer; import com.google.android.gms.ads.AdListener; import java.io.File; import java.util.ArrayList; public class ActivityFilesHolder extends ActivityBase { private Toolbar toolbar; private TextView toolBarTitleTv; private CheckBox selectAllMenuItem; private ProgressBar loadingBar; private RecyclerView recyclerView; private TextView noFileTV; private AdapterFilesHolder adapter; private ArrayList<ModelFilesHolder> itemsList; private LinearLayoutManager layoutManager; private String TAG = "ActivityFilesHolder"; private Intent intent; private String checkFileFormat; public boolean isContextualMenuOpen = false; private ArrayList<ModelFilesHolder> multiSelectedItemList; private String selected; private int adCounter = 0; public Drawable scrollBars; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_files_holder); if (!hasStoragePermission()) { checkStoragePermission(); } if (haveNetworkConnection()) { requestBanner((FrameLayout) findViewById(R.id.acFilesHolder_bannerContainer)); } intent = getIntent(); if (intent != null) { checkFileFormat = intent.getStringExtra(Constant.KEY_SELECTED_FILE_FORMAT); } initViews(); setUpToolBar(); initRecyclerView(); getDocumentFiles(); reqNewInterstitial(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_ac_filesholder_parent_view, menu); MenuItem searchitem = menu.findItem(R.id.menu_filesHolder_parentView_search); SearchView searchView = (SearchView) searchitem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); SearchView.OnCloseListener closeListener = new SearchView.OnCloseListener() { @Override public boolean onClose() { getDocumentFiles(); adapter.updateData(itemsList); return false; } }; searchView.setOnCloseListener(closeListener); Log.d(TAG, "onCreateOptionsMenu: Called"); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.menu_filesHolder_parentView_shareUs: shareUs(); return true; case R.id.menu_filesHolder_parentView_rateUs: rateUs(); return true; case R.id.menu_contextual_btnDelete: if (!multiSelectedItemList.isEmpty()) { deleteMultipleDialoge(); } else { showToast("Please select any file first."); } return true; case R.id.menu_contextual_btnShare: if (!multiSelectedItemList.isEmpty()) { shareMultipleFile(); } else { Toast.makeText(this, "Please select any item first", Toast.LENGTH_SHORT).show(); } return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { if (isContextualMenuOpen) { closeContextualMenu(); } else { setResult(RESULT_OK); finish(); super.onBackPressed(); } } private void setUpToolBar() { selected = " " + getResources().getString(R.string.selected); setSupportActionBar(toolbar); toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); toolBarTitleTv = (TextView) findViewById(R.id.toolBar_title_tv); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); setGradientToToolBar(); updateToolBarTitle(checkFileFormat); } private void updateToolBarTitle(String title) { toolBarTitleTv.setText(title); } public void setGradientToToolBar() { if (checkFileFormat.equals(getString(R.string.allDocs))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_allDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_allDoc_upper), this.getResources().getColor(R.color.color_cardBg_allDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_allDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.pdf_files))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_pdfDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_pdfDoc_upper), this.getResources().getColor(R.color.color_cardBg_pdfDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_pdfDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.word_files))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_wordDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_wordDoc_upper), this.getResources().getColor(R.color.color_cardBg_wordDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_wordDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.txtFiles))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_txtDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_txtDoc_upper), this.getResources().getColor(R.color.color_cardBg_txtDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_txtDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.ppt_files))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_pptDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_pptDoc_upper), this.getResources().getColor(R.color.color_cardBg_pdfDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_pptDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.html_files))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_htmlDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_htmlDoc_upper), this.getResources().getColor(R.color.color_cardBg_htmlDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_htmlDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.xmlFiles))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_xmlDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_xmlDoc_upper), this.getResources().getColor(R.color.color_cardBg_xmlDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_xmlDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.sheet_files))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_sheetDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_sheetDoc_upper), this.getResources().getColor(R.color.color_cardBg_sheetDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_sheetDoc_upper)); } else if (checkFileFormat.equals(getString(R.string.rtf_files))) { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_rtfDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_rtfDoc_upper), this.getResources().getColor(R.color.color_cardBg_rtfDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_rtfDoc_upper)); } else { loadingBar.getIndeterminateDrawable().setColorFilter(this.getResources().getColor(R.color.color_cardBg_allDoc_upper), PorterDuff.Mode.MULTIPLY); toolbar.setBackground(getGradient( this.getResources().getColor(R.color.color_cardBg_allDoc_upper), this.getResources().getColor(R.color.color_cardBg_allDoc_lower))); noFileTV.setTextColor(this.getResources().getColor(R.color.color_cardBg_allDoc_upper)); } } private GradientDrawable getGradient(int color1, int color2) { int[] colors = {Integer.parseInt(String.valueOf(color1)), Integer.parseInt(String.valueOf(color2)) }; GradientDrawable gd = new GradientDrawable( GradientDrawable.Orientation.RIGHT_LEFT, colors); return gd; } private void initViews() { toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.acFilesHolder_toolbar); loadingBar = (ProgressBar) findViewById(R.id.acFilesHolder_loadingBar); loadingBar.setVisibility(View.INVISIBLE); noFileTV = findViewById(R.id.acFilesHolder_noFileTv); } private void initRecyclerView() { itemsList = new ArrayList<>(); recyclerView = findViewById(R.id.acFilesHolder_RecyclerView); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(layoutManager); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { scrollBars = recyclerView.getHorizontalScrollbarThumbDrawable(); } } private void buildRecyclerView() { if (itemsList != null) { adapter = new AdapterFilesHolder(ActivityFilesHolder.this, ActivityFilesHolder.this, itemsList); if (itemsList.isEmpty()) { noFileTV.setVisibility(View.VISIBLE); } else { noFileTV.setVisibility(View.GONE); } } adapter.notifyDataSetChanged(); recyclerView.setAdapter(adapter); adapter.setOnItemClickListener(new OnRecyclerItemClickLister() { @Override public void onItemClicked(int position) { if (hasStoragePermission()) { intentOnItemClick(position); } else { checkStoragePermission(); } } @Override public void onItemShareClicked(int position) { File file = new File(itemsList.get(position).getFileUri()); if (file.exists()) { shareFile(file); } } @Override public void onItemDeleteClicked(int position) { File file = new File(itemsList.get(position).getFileUri()); if (file.exists()) { deleteFileDialog(file, position); } } @Override public void onItemRenameClicked(int position) { dialogRename(position); } @Override public void onItemLongClicked(int position) { openContextualMenu(); } @Override public void onItemCheckBoxClicked(View view, int position) { doSingleSelection(view, position); } }); } private void intentOnItemClick(int position) { adCounter++; if (itemsList.get(position).getFileName().endsWith(".pdf")) { final Intent intent = new Intent(ActivityFilesHolder.this, PdfViewer.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Constant.KEY_SELECTED_FILE_URI, itemsList.get(position).getFileUri()); intent.putExtra(Constant.KEY_SELECTED_FILE_NAME, itemsList.get(position).getFileName()); if (adCounter > 2) { adCounter = 0; if (mInterstitialAd.isLoaded() && !myPreferences.isItemPurchased()) { mInterstitialAd.show(); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); startActivity(intent); } }); } else { reqNewInterstitial(this); startActivity(intent); } } else { startActivity(intent); } } else { final Intent intent = new Intent(ActivityFilesHolder.this, AppActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(Constant.KEY_SELECTED_FILE_URI, itemsList.get(position).getFileUri()); intent.putExtra(Constant.KEY_SELECTED_FILE_NAME, itemsList.get(position).getFileName()); if (adCounter > 2) { adCounter = 0; if (mInterstitialAd.isLoaded() && !myPreferences.isItemPurchased()) { mInterstitialAd.show(); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); startActivity(intent); } }); } else { reqNewInterstitial(this); startActivity(intent); } } else { startActivity(intent); } } } private GradientDrawable bgRenameDialogBtn(int color1) { int height = (int) getResources().getDimension(R.dimen._25sdp); float radius = getResources().getDimension(R.dimen._20sdp); int[] colors = {Integer.parseInt(String.valueOf(color1)), Integer.parseInt(String.valueOf(color1)) }; GradientDrawable gd = new GradientDrawable( GradientDrawable.Orientation.RIGHT_LEFT, colors); gd.setShape(GradientDrawable.RECTANGLE); gd.setSize(height, height); gd.setCornerRadius(radius); return gd; } private void dialogRename(final int position) { final AlertDialog dialogBuilder = new AlertDialog.Builder(this).create(); LayoutInflater inflater = this.getLayoutInflater(); View dialogView = inflater.inflate(R.layout.dialog_edit_text, null); final EditText editText = (EditText) dialogView.findViewById(R.id.dialog_etFileName); Button btnRename = (Button) dialogView.findViewById(R.id.dialogBtn_rename); Button btnCancel = (Button) dialogView.findViewById(R.id.dialgBtn_Cancel); try { if (checkFileFormat.equals(getString(R.string.allDocs))) { btnRename.setBackground(bgRenameDialogBtn(this.getResources().getColor(R.color.color_cardBg_allDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(this.getResources().getColor(R.color.color_cardBg_allDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.pdf_files))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_pdfDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_pdfDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.word_files))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_wordDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_wordDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.txtFiles))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_txtDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_txtDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.ppt_files))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_pptDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_pptDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.html_files))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_htmlDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_htmlDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.xmlFiles))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_xmlDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_xmlDoc_upper))); } else if (checkFileFormat.equals(getString(R.string.sheet_files))) { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_sheetDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_sheetDoc_upper))); } else { btnRename.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_allDoc_upper))); btnCancel.setBackground(bgRenameDialogBtn(getResources().getColor(R.color.color_cardBg_allDoc_upper))); } } catch (Exception e) { Log.d(TAG, "dialogRename: ", e); } editText.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); btnRename.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { renameFile(itemsList.get(position).getFileUri(), itemsList.get(position).getFileName(), editText.getText().toString()); dialogBuilder.dismiss(); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); if (mInterstitialAd.isLoaded() && !myPreferences.isItemPurchased()) { mInterstitialAd.show(); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); dialogBuilder.dismiss(); } }); } else { dialogBuilder.dismiss(); } } }); dialogBuilder.setView(dialogView); dialogBuilder.show(); } private void renameFile(final String filePath, final String oldFileName, final String newFileName) { new AsyncTask<Void, Void, Void>() { private String completeNewFileName = ""; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... voids) { if (oldFileName.endsWith(".pdf")) { completeNewFileName = newFileName + ".pdf"; } else if (oldFileName.endsWith(".doc")) { completeNewFileName = newFileName + ".doc"; } else if (oldFileName.endsWith(".docx")) { completeNewFileName = newFileName + ".docx"; } else if (oldFileName.endsWith(".ppt")) { completeNewFileName = newFileName + ".ppt"; } else if (oldFileName.endsWith(".txt")) { completeNewFileName = newFileName + ".txt"; } else if (oldFileName.endsWith(".xml")) { completeNewFileName = newFileName + ".xml"; } else if (oldFileName.endsWith(".html")) { completeNewFileName = newFileName + ".html"; } else if (oldFileName.endsWith(".xls")) { completeNewFileName = newFileName + ".xls"; } else if (oldFileName.endsWith(".xlsx")) { completeNewFileName = newFileName + ".xlsx"; } else { } File oldPath = new File(filePath); File parentFileName = new File(oldPath.getParent()); File from = new File(parentFileName.toString(), oldFileName); File to = new File(parentFileName.toString(), completeNewFileName); from.renameTo(to); Log.d(TAG, "renameFile: parentFileName:" + parentFileName + " oldFileName:" + oldFileName + "newFileName:" + completeNewFileName); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); showToast("File renamed successfully with '" + completeNewFileName + "'"); getDocumentFiles(); } }.execute(); } /* private void openContextualMenu() { multiSelectedItemList = new ArrayList<>(); isContextualMenuOpen = true; isSelectAll = false; toolbar.getMenu().clear(); toolbar.inflateMenu(R.menu.menu_ac_filesholder_contextual); toolbar.setNavigationIcon(R.drawable.ic_cross); selectAllMenuItem = (CheckBox) toolbar.getMenu().findItem(R.id.menu_contextual_btnSelecAll).getActionView(); selectAllMenuItem.setChecked(false); updateToolBarTitle("0" + selected); adapter.notifyDataSetChanged(); selectAllMenuItem.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (isChecked) { selectAllItems(true); isSelectAll = true; } else { selectAllItems(false); isSelectAll = false; } } }); } private void selectAllItems(boolean isSelectAll) { if (isSelectAll) { if (!multiSelectedItemList.isEmpty()) { multiSelectedItemList.removeAll(itemsList); multiSelectedItemList.clear(); } for (int i = 0; i < itemsList.size(); i++) { multiSelectedItemList.add(itemsList.get(i)); } String text = multiSelectedItemList.size() + selected; updateToolBarTitle(text); } else { multiSelectedItemList.removeAll(itemsList); multiSelectedItemList.clear(); String text = multiSelectedItemList.size() + selected; updateToolBarTitle(text); } adapter.notifyDataSetChanged(); } private void closeContextualMenu() { multiSelectedItemList.removeAll(itemsList); multiSelectedItemList.clear(); isContextualMenuOpen = false; isSelectAll = false; toolbar.getMenu().clear(); toolbar.inflateMenu(R.menu.menu_ac_filesholder_parent_view); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); updateToolBarTitle(checkFileFormat); adapter.notifyDataSetChanged(); }*/ private void openContextualMenu() { multiSelectedItemList = new ArrayList<>(); isContextualMenuOpen = true; toolbar.getMenu().clear(); toolbar.inflateMenu(R.menu.menu_ac_filesholder_contextual); toolbar.setNavigationIcon(R.drawable.ic_cross); selectAllMenuItem = (CheckBox) toolbar.getMenu().findItem(R.id.menu_contextual_btnSelecAll).getActionView(); selectAllMenuItem.setChecked(false); String text = selected + " " + multiSelectedItemList.size() + "/" + itemsList.size(); updateToolBarTitle(text); adapter.notifyDataSetChanged(); selectAllMenuItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (((CheckBox) view).isChecked()) { doSelectAll(true); } else { doSelectAll(false); } } }); } private void doSingleSelection(View view, int position) { try { if (((CheckBox) view).isChecked()) { itemsList.get(position).setSelected(true); multiSelectedItemList.add(itemsList.get(position)); if (multiSelectedItemList.size() == itemsList.size()) { selectAllMenuItem.setChecked(true); } else { selectAllMenuItem.setChecked(false); } } else { itemsList.get(position).setSelected(false); multiSelectedItemList.remove(itemsList.get(position)); if (multiSelectedItemList.size() != itemsList.size()) { selectAllMenuItem.setChecked(false); } } String text = selected + " " + multiSelectedItemList.size() + "/" + itemsList.size(); updateToolBarTitle(text); } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "onItemCheckBoxClicked: " + e); } } private void doSelectAll(boolean isSelectAll) { if (isSelectAll) { if (!multiSelectedItemList.isEmpty()) { multiSelectedItemList.removeAll(itemsList); multiSelectedItemList.clear(); } for (int i = 0; i < itemsList.size(); i++) { itemsList.get(i).setSelected(true); multiSelectedItemList.add(itemsList.get(i)); } } else { for (int i = 0; i < itemsList.size(); i++) { itemsList.get(i).setSelected(false); } multiSelectedItemList.removeAll(itemsList); multiSelectedItemList.clear(); } adapter.notifyDataSetChanged(); String text = selected + " " + multiSelectedItemList.size() + "/" + itemsList.size(); updateToolBarTitle(text); } private void closeContextualMenu() { multiSelectedItemList.removeAll(itemsList); multiSelectedItemList.clear(); isContextualMenuOpen = false; toolbar.getMenu().clear(); toolbar.inflateMenu(R.menu.menu_activity_main); toolbar.setNavigationIcon(R.drawable.ic_arrow_back); updateToolBarTitle(checkFileFormat); for (int i = 0; i < itemsList.size(); i++) { itemsList.get(i).setSelected(false); } onCreateOptionsMenu(toolbar.getMenu()); adapter.notifyDataSetChanged(); } private void getDocumentFiles() { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { super.onPreExecute(); loadingBar.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); if (!itemsList.isEmpty() || itemsList.size() > 0) { itemsList.clear(); } } @Override protected Void doInBackground(Void... voids) { File parentFile = new File(String.valueOf(Environment.getExternalStorageDirectory())); if (checkFileFormat.equals(getString(R.string.allDocs))) { allDocsFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.pdf_files))) { pdfFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.word_files))) { wordFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.txtFiles))) { textFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.ppt_files))) { pptFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.html_files))) { htmlFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.xmlFiles))) { xmlFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.sheet_files))) { sheetFiles(parentFile); } else if (checkFileFormat.equals(getString(R.string.rtf_files))) { rtfFiles(parentFile); } else { allDocsFiles(parentFile); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); new Handler().postDelayed(new Runnable() { @Override public void run() { recyclerView.setVisibility(View.VISIBLE); buildRecyclerView(); loadingBar.setVisibility(View.INVISIBLE); } }, 100); } }.execute(); } private void pdfFiles(File parentFile) { int id = R.drawable.ic_svg_file_type_pdf; File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { pdfFiles(files[i]); } else { if (files[i].getName().endsWith(".pdf")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void wordFiles(File parentFile) { int id = R.drawable.ic_svg_file_type_pdf; File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { wordFiles(files[i]); } else { if (files[i].getName().endsWith(".doc") || files[i].getName().endsWith(".docx")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void sheetFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { sheetFiles(files[i]); } else { if (files[i].getName().endsWith("xls") || files[i].getName().endsWith("xlsx")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void pptFiles(File parentFile) { int id = R.drawable.ic_svg_file_type_pdf; File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { pptFiles(files[i]); } else { if (files[i].getName().endsWith("ppt") || files[i].getName().endsWith("pptx")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void textFiles(File parentFile) { int id = R.drawable.ic_svg_file_type_pdf; File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { textFiles(files[i]); } else { if (files[i].getName().endsWith(".txt")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void xmlFiles(File parentFile) { int id = R.drawable.ic_svg_file_type_pdf; File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { xmlFiles(files[i]); } else { if (files[i].getName().endsWith(".xml")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void htmlFiles(File parentFile) { int id = R.drawable.ic_svg_file_type_pdf; File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { htmlFiles(files[i]); } else { if (files[i].getName().endsWith(".html")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void rtfFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { rtfFiles(files[i]); } else { if (files[i].getName().endsWith("rtf")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void allDocsFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { allDocsFiles(files[i]); } else { if (files[i].getName().endsWith(".pdf") || files[i].getName().endsWith(".doc") || files[i].getName().endsWith(".docx") || files[i].getName().endsWith(".ppt") || files[i].getName().endsWith(".xlsx") || files[i].getName().endsWith(".xls") || files[i].getName().endsWith(".html") || files[i].getName().endsWith(".pptx") || files[i].getName().endsWith(".txt") || files[i].getName().endsWith(".xml") || files[i].getName().endsWith(".rtf")) { if (!itemsList.contains(files[i])) { itemsList.add(new ModelFilesHolder(files[i].getName(), files[i].getAbsolutePath(), false)); } } } } } } private void deleteFileDialog(final File LocalFile, final int position) { new AlertDialog.Builder(ActivityFilesHolder.this) .setTitle("Delete Alert") .setMessage(R.string.delete_msg) .setPositiveButton(getResources().getString(R.string.delete), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mInterstitialAd.isLoaded() && !myPreferences.isItemPurchased()) { mInterstitialAd.show(); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); LocalFile.delete(); itemsList.remove(position); adapter.notifyItemRemoved(position); showToast("File deleted successfully."); } }); } else { LocalFile.delete(); itemsList.remove(position); adapter.notifyItemRemoved(position); showToast("File deleted successfully."); } } }) .setNegativeButton(getResources().getString(R.string.no), null) .setIcon(android.R.drawable.ic_delete) .show(); } private void shareFile(File DocFile) { if (DocFile.exists()) { Intent intentShareFile = new Intent(Intent.ACTION_SEND); if (DocFile.exists()) { intentShareFile.setType("application/*"); intentShareFile.putExtra(Intent.EXTRA_STREAM, Uri.parse(DocFile.getAbsolutePath())); intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing File..."); intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing File..."); startActivity(Intent.createChooser(intentShareFile, "Share File")); } } } private void deleteMultipleDialoge() { new AlertDialog.Builder(ActivityFilesHolder.this) .setTitle("Delete Alert") .setMessage(R.string.delete_msg) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mInterstitialAd.isLoaded() && !myPreferences.isItemPurchased()) { mInterstitialAd.show(); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { super.onAdClosed(); doDeleteMultiFiles(); } }); } else { doDeleteMultiFiles(); } } }) .setNegativeButton(R.string.no, null) .show(); } private void doDeleteMultiFiles() { new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { super.onPreExecute(); loadingBar.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... voids) { for (int i = 0; i < multiSelectedItemList.size(); i++) { File file = new File(multiSelectedItemList.get(i).getFileUri()); if (file.exists()) { file.delete(); } itemsList.remove(multiSelectedItemList.get(i)); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); buildRecyclerView(); if (multiSelectedItemList.size() == 1) { showToast(multiSelectedItemList.size() + " File deleted successfully."); } else { showToast(multiSelectedItemList.size() + " Files deleted successfully."); } closeContextualMenu(); loadingBar.setVisibility(View.GONE); } }.execute(); } private void shareMultipleFile() { Intent intentShareFile = new Intent(Intent.ACTION_SEND_MULTIPLE); ArrayList<Uri> uris = new ArrayList<>(); for (int i = 0; i < multiSelectedItemList.size(); i++) { File file = new File(multiSelectedItemList.get(i).getFileUri()); Uri photoURI = FileProvider.getUriForFile(ActivityFilesHolder.this, getApplicationContext().getPackageName() + ".provider", file); uris.add(photoURI); } intentShareFile.setType("application/*"); intentShareFile.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris); intentShareFile.putExtra(Intent.EXTRA_SUBJECT, "Sharing Files..."); intentShareFile.putExtra(Intent.EXTRA_TEXT, "Sharing Files..."); startActivity(Intent.createChooser(intentShareFile, "Share File")); } void showToast(String message) { Toast.makeText(ActivityFilesHolder.this, message, Toast.LENGTH_SHORT).show(); } public void changeRecyclerViewScrollColor(Context mContext, int colorToSet) { if (scrollBars instanceof ShapeDrawable) { // cast to 'ShapeDrawable' ShapeDrawable shapeDrawable = (ShapeDrawable) scrollBars; shapeDrawable.getPaint().setColor(ContextCompat.getColor(mContext, colorToSet)); } else if (scrollBars instanceof GradientDrawable) { // cast to 'GradientDrawable' GradientDrawable gradientDrawable = (GradientDrawable) scrollBars; gradientDrawable.setColor(ContextCompat.getColor(mContext, colorToSet)); } else if (scrollBars instanceof ColorDrawable) { // alpha value may need to be set again after this call ColorDrawable colorDrawable = (ColorDrawable) scrollBars; colorDrawable.setColor(ContextCompat.getColor(mContext, colorToSet)); } } @Override public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { getDocumentFiles(); } else { } } } }
package com.tencent.mm.plugin.appbrand.appcache; import com.tencent.mm.plugin.appbrand.appcache.s.a; import com.tencent.mm.pluginsdk.g.a.c.m; final class g { static final a ffx = new a() { public final void abs() { } public final void abt() { } public final void abu() { } public final void a(m mVar) { } public final void abv() { } public final void jD(int i) { } public final void abw() { } public final void abx() { } public final void ct(boolean z) { } }; }
package cci_linked_lists; import java.util.Stack; import cci_linked_lists.SumLists_2_5.LinkedListNode; /** * Palindrome: Implement a function to check if a linked list is a palindrome. * * @author chenfeng * */ public class Palindrome_2_6 { public static void main(String[] args) { // create test case LinkedListNode l1 = new LinkedListNode(7); l1.next = new LinkedListNode(1); l1.next.next = new LinkedListNode(1); l1.next.next.next = new LinkedListNode(7); // compute result boolean result = isPalindrome(l1); System.out.println("result is: " + result); } public static boolean isPalindrome(LinkedListNode head) { LinkedListNode fast = head; LinkedListNode slow = head; Stack<Integer> s = new Stack<>(); while (fast != null && fast.next != null) { s.push(slow.value); slow = slow.next; fast = fast.next.next; } // if odd, skip middle node if (fast != null) { slow = slow.next; } while (slow != null) { int val = s.pop(); if (val != slow.value) return false; slow = slow.next; } return true; } public static class LinkedListNode { LinkedListNode next; int value; public LinkedListNode(int v) { this.value = v; } } }
package com.tencent.mm.protocal.c; import f.a.a.c.a; import java.util.LinkedList; public final class bvq extends bhd { public String bKv; public int blZ; public String byN; public String dxK; public String sjf; public int ssb; public int ssc; public String ssd; public int sse; public String ssf; public LinkedList<bqr> ssg = new LinkedList(); public int ssh; public int ssi; protected final int a(int i, Object... objArr) { int fS; byte[] bArr; if (i == 0) { a aVar = (a) objArr[0]; if (this.shX != null) { aVar.fV(1, this.shX.boi()); this.shX.a(aVar); } if (this.byN != null) { aVar.g(2, this.byN); } if (this.bKv != null) { aVar.g(3, this.bKv); } aVar.fT(4, this.ssb); aVar.fT(5, this.ssc); aVar.fT(6, this.blZ); if (this.ssd != null) { aVar.g(7, this.ssd); } if (this.sjf != null) { aVar.g(8, this.sjf); } if (this.dxK != null) { aVar.g(9, this.dxK); } aVar.fT(10, this.sse); if (this.ssf != null) { aVar.g(11, this.ssf); } aVar.d(12, 8, this.ssg); aVar.fT(13, this.ssh); aVar.fT(14, this.ssi); return 0; } else if (i == 1) { if (this.shX != null) { fS = f.a.a.a.fS(1, this.shX.boi()) + 0; } else { fS = 0; } if (this.byN != null) { fS += f.a.a.b.b.a.h(2, this.byN); } if (this.bKv != null) { fS += f.a.a.b.b.a.h(3, this.bKv); } fS = ((fS + f.a.a.a.fQ(4, this.ssb)) + f.a.a.a.fQ(5, this.ssc)) + f.a.a.a.fQ(6, this.blZ); if (this.ssd != null) { fS += f.a.a.b.b.a.h(7, this.ssd); } if (this.sjf != null) { fS += f.a.a.b.b.a.h(8, this.sjf); } if (this.dxK != null) { fS += f.a.a.b.b.a.h(9, this.dxK); } fS += f.a.a.a.fQ(10, this.sse); if (this.ssf != null) { fS += f.a.a.b.b.a.h(11, this.ssf); } return ((fS + f.a.a.a.c(12, 8, this.ssg)) + f.a.a.a.fQ(13, this.ssh)) + f.a.a.a.fQ(14, this.ssi); } else if (i == 2) { bArr = (byte[]) objArr[0]; this.ssg.clear(); f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler); for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; bvq bvq = (bvq) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); fk fkVar = new fk(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) { } bvq.shX = fkVar; } return 0; case 2: bvq.byN = aVar3.vHC.readString(); return 0; case 3: bvq.bKv = aVar3.vHC.readString(); return 0; case 4: bvq.ssb = aVar3.vHC.rY(); return 0; case 5: bvq.ssc = aVar3.vHC.rY(); return 0; case 6: bvq.blZ = aVar3.vHC.rY(); return 0; case 7: bvq.ssd = aVar3.vHC.readString(); return 0; case 8: bvq.sjf = aVar3.vHC.readString(); return 0; case 9: bvq.dxK = aVar3.vHC.readString(); return 0; case 10: bvq.sse = aVar3.vHC.rY(); return 0; case 11: bvq.ssf = aVar3.vHC.readString(); return 0; case 12: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); bqr bqr = new bqr(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = bqr.a(aVar4, bqr, bhd.a(aVar4))) { } bvq.ssg.add(bqr); } return 0; case 13: bvq.ssh = aVar3.vHC.rY(); return 0; case 14: bvq.ssi = aVar3.vHC.rY(); return 0; default: return -1; } } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mariopractica; import java.awt.Image; import java.awt.Rectangle; import javax.swing.ImageIcon; /** * * @author G42368LA */ public class Marito { public int x; public int y; public int width; public int hiegth; public boolean vista; public Image img; public Marito (int x, int y){ this.x=x; this.y=y; vista=true; } public void getImageDimensions(){ width = img.getWidth(null); hiegth = img.getHeight(null); } public void loadImage(String imageName){ ImageIcon ii = new ImageIcon(imageName); img = ii.getImage(); } public boolean isVisible(){ return vista; } public Rectangle getBounds(){ return new Rectangle (x,y,width,hiegth); } public Image getImage(){ return img; } public int getX(){ return x; } public int getY(){ return y; } }
package com.espendwise.manta.web.forms; import com.espendwise.manta.util.validation.Validation; import com.espendwise.manta.web.validator.AccountSiteHierarchyManageFilterFormValidator; @Validation(AccountSiteHierarchyManageFilterFormValidator.class) public class AccountSiteHierarchyManageFilterForm extends AbstractSimpleFilterForm { }
package com.sixmac.service.impl; import com.sixmac.core.Constant; import com.sixmac.dao.SysCredibilityDao; import com.sixmac.entity.SysCredibility; import com.sixmac.service.SysCredibilityService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * Created by Administrator on 2016/6/12 0012 上午 11:48. */ @Service public class SysCredibilityServiceImpl implements SysCredibilityService { @Autowired private SysCredibilityDao sysCredibilityDao; @Override public List<SysCredibility> findAll() { return sysCredibilityDao.findAll(); } @Override public Page<SysCredibility> find(int pageNum, int pageSize) { return sysCredibilityDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id")); } @Override public Page<SysCredibility> find(int pageNum) { return find(pageNum, Constant.PAGE_DEF_SZIE); } @Override public SysCredibility getById(Long id) { return sysCredibilityDao.findOne(id); } @Override public SysCredibility deleteById(Long id) { SysCredibility sysCredibility = getById(id); sysCredibilityDao.delete(sysCredibility); return sysCredibility; } @Override public SysCredibility create(SysCredibility sysCredibility) { return sysCredibilityDao.save(sysCredibility); } @Override public SysCredibility update(SysCredibility sysCredibility) { return sysCredibilityDao.save(sysCredibility); } @Override @Transactional public void deleteAll(Long[] ids) { for (Long id : ids) { deleteById(id); } } @Override public SysCredibility findByAction(Integer action) { return sysCredibilityDao.findByAction(action); } }
package com.isystk.sample.web.base.controller.api.resource; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.isystk.sample.common.dto.Dto; import lombok.Data; @Data @JsonIgnoreProperties(ignoreUnknown = true) public class ResourceImpl implements Resource { List<? extends Dto> data; // メッセージ String message; }